aframe-master.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  2. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. module.exports = function numtype(num, def) {
  13. return typeof num === 'number'
  14. ? num
  15. : (typeof def === 'number' ? def : 0)
  16. }
  17. },{}],3:[function(_dereq_,module,exports){
  18. 'use strict'
  19. exports.byteLength = byteLength
  20. exports.toByteArray = toByteArray
  21. exports.fromByteArray = fromByteArray
  22. var lookup = []
  23. var revLookup = []
  24. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  25. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  26. for (var i = 0, len = code.length; i < len; ++i) {
  27. lookup[i] = code[i]
  28. revLookup[code.charCodeAt(i)] = i
  29. }
  30. // Support decoding URL-safe base64 strings, as Node.js does.
  31. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  32. revLookup['-'.charCodeAt(0)] = 62
  33. revLookup['_'.charCodeAt(0)] = 63
  34. function getLens (b64) {
  35. var len = b64.length
  36. if (len % 4 > 0) {
  37. throw new Error('Invalid string. Length must be a multiple of 4')
  38. }
  39. // Trim off extra bytes after placeholder bytes are found
  40. // See: https://github.com/beatgammit/base64-js/issues/42
  41. var validLen = b64.indexOf('=')
  42. if (validLen === -1) validLen = len
  43. var placeHoldersLen = validLen === len
  44. ? 0
  45. : 4 - (validLen % 4)
  46. return [validLen, placeHoldersLen]
  47. }
  48. // base64 is 4/3 + up to two characters of the original data
  49. function byteLength (b64) {
  50. var lens = getLens(b64)
  51. var validLen = lens[0]
  52. var placeHoldersLen = lens[1]
  53. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  54. }
  55. function _byteLength (b64, validLen, placeHoldersLen) {
  56. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  57. }
  58. function toByteArray (b64) {
  59. var tmp
  60. var lens = getLens(b64)
  61. var validLen = lens[0]
  62. var placeHoldersLen = lens[1]
  63. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  64. var curByte = 0
  65. // if there are placeholders, only get up to the last complete 4 chars
  66. var len = placeHoldersLen > 0
  67. ? validLen - 4
  68. : validLen
  69. for (var i = 0; i < len; i += 4) {
  70. tmp =
  71. (revLookup[b64.charCodeAt(i)] << 18) |
  72. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  73. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  74. revLookup[b64.charCodeAt(i + 3)]
  75. arr[curByte++] = (tmp >> 16) & 0xFF
  76. arr[curByte++] = (tmp >> 8) & 0xFF
  77. arr[curByte++] = tmp & 0xFF
  78. }
  79. if (placeHoldersLen === 2) {
  80. tmp =
  81. (revLookup[b64.charCodeAt(i)] << 2) |
  82. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  83. arr[curByte++] = tmp & 0xFF
  84. }
  85. if (placeHoldersLen === 1) {
  86. tmp =
  87. (revLookup[b64.charCodeAt(i)] << 10) |
  88. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  89. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  90. arr[curByte++] = (tmp >> 8) & 0xFF
  91. arr[curByte++] = tmp & 0xFF
  92. }
  93. return arr
  94. }
  95. function tripletToBase64 (num) {
  96. return lookup[num >> 18 & 0x3F] +
  97. lookup[num >> 12 & 0x3F] +
  98. lookup[num >> 6 & 0x3F] +
  99. lookup[num & 0x3F]
  100. }
  101. function encodeChunk (uint8, start, end) {
  102. var tmp
  103. var output = []
  104. for (var i = start; i < end; i += 3) {
  105. tmp =
  106. ((uint8[i] << 16) & 0xFF0000) +
  107. ((uint8[i + 1] << 8) & 0xFF00) +
  108. (uint8[i + 2] & 0xFF)
  109. output.push(tripletToBase64(tmp))
  110. }
  111. return output.join('')
  112. }
  113. function fromByteArray (uint8) {
  114. var tmp
  115. var len = uint8.length
  116. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  117. var parts = []
  118. var maxChunkLength = 16383 // must be multiple of 3
  119. // go through the array every three bytes, we'll deal with trailing stuff later
  120. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  121. parts.push(encodeChunk(
  122. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  123. ))
  124. }
  125. // pad the end with zeros, but make sure to not forget the extra bytes
  126. if (extraBytes === 1) {
  127. tmp = uint8[len - 1]
  128. parts.push(
  129. lookup[tmp >> 2] +
  130. lookup[(tmp << 4) & 0x3F] +
  131. '=='
  132. )
  133. } else if (extraBytes === 2) {
  134. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  135. parts.push(
  136. lookup[tmp >> 10] +
  137. lookup[(tmp >> 4) & 0x3F] +
  138. lookup[(tmp << 2) & 0x3F] +
  139. '='
  140. )
  141. }
  142. return parts.join('')
  143. }
  144. },{}],4:[function(_dereq_,module,exports){
  145. 'use strict';
  146. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  147. module.exports = {
  148. // Create a <link> tag with optional data attributes
  149. createLink: function(href, attributes) {
  150. var head = document.head || document.getElementsByTagName('head')[0];
  151. var link = document.createElement('link');
  152. link.href = href;
  153. link.rel = 'stylesheet';
  154. for (var key in attributes) {
  155. if ( ! attributes.hasOwnProperty(key)) {
  156. continue;
  157. }
  158. var value = attributes[key];
  159. link.setAttribute('data-' + key, value);
  160. }
  161. head.appendChild(link);
  162. },
  163. // Create a <style> tag with optional data attributes
  164. createStyle: function(cssText, attributes) {
  165. var head = document.head || document.getElementsByTagName('head')[0],
  166. style = document.createElement('style');
  167. style.type = 'text/css';
  168. for (var key in attributes) {
  169. if ( ! attributes.hasOwnProperty(key)) {
  170. continue;
  171. }
  172. var value = attributes[key];
  173. style.setAttribute('data-' + key, value);
  174. }
  175. if (style.sheet) { // for jsdom and IE9+
  176. style.innerHTML = cssText;
  177. style.sheet.cssText = cssText;
  178. head.appendChild(style);
  179. } else if (style.styleSheet) { // for IE8 and below
  180. head.appendChild(style);
  181. style.styleSheet.cssText = cssText;
  182. } else { // for Chrome, Firefox, and Safari
  183. style.appendChild(document.createTextNode(cssText));
  184. head.appendChild(style);
  185. }
  186. }
  187. };
  188. },{}],5:[function(_dereq_,module,exports){
  189. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  190. module.exports = function (a, b) {
  191. if (!Buffer.isBuffer(a)) return undefined;
  192. if (!Buffer.isBuffer(b)) return undefined;
  193. if (typeof a.equals === 'function') return a.equals(b);
  194. if (a.length !== b.length) return false;
  195. for (var i = 0; i < a.length; i++) {
  196. if (a[i] !== b[i]) return false;
  197. }
  198. return true;
  199. };
  200. },{"buffer":6}],6:[function(_dereq_,module,exports){
  201. (function (global,Buffer){
  202. /*!
  203. * The buffer module from node.js, for the browser.
  204. *
  205. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  206. * @license MIT
  207. */
  208. /* eslint-disable no-proto */
  209. 'use strict'
  210. var base64 = _dereq_('base64-js')
  211. var ieee754 = _dereq_('ieee754')
  212. var isArray = _dereq_('isarray')
  213. exports.Buffer = Buffer
  214. exports.SlowBuffer = SlowBuffer
  215. exports.INSPECT_MAX_BYTES = 50
  216. /**
  217. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  218. * === true Use Uint8Array implementation (fastest)
  219. * === false Use Object implementation (most compatible, even IE6)
  220. *
  221. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  222. * Opera 11.6+, iOS 4.2+.
  223. *
  224. * Due to various browser bugs, sometimes the Object implementation will be used even
  225. * when the browser supports typed arrays.
  226. *
  227. * Note:
  228. *
  229. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  230. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  231. *
  232. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  233. *
  234. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  235. * incorrect length in some situations.
  236. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  237. * get the Object implementation, which is slower but behaves correctly.
  238. */
  239. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  240. ? global.TYPED_ARRAY_SUPPORT
  241. : typedArraySupport()
  242. /*
  243. * Export kMaxLength after typed array support is determined.
  244. */
  245. exports.kMaxLength = kMaxLength()
  246. function typedArraySupport () {
  247. try {
  248. var arr = new Uint8Array(1)
  249. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  250. return arr.foo() === 42 && // typed array instances can be augmented
  251. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  252. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  253. } catch (e) {
  254. return false
  255. }
  256. }
  257. function kMaxLength () {
  258. return Buffer.TYPED_ARRAY_SUPPORT
  259. ? 0x7fffffff
  260. : 0x3fffffff
  261. }
  262. function createBuffer (that, length) {
  263. if (kMaxLength() < length) {
  264. throw new RangeError('Invalid typed array length')
  265. }
  266. if (Buffer.TYPED_ARRAY_SUPPORT) {
  267. // Return an augmented `Uint8Array` instance, for best performance
  268. that = new Uint8Array(length)
  269. that.__proto__ = Buffer.prototype
  270. } else {
  271. // Fallback: Return an object instance of the Buffer class
  272. if (that === null) {
  273. that = new Buffer(length)
  274. }
  275. that.length = length
  276. }
  277. return that
  278. }
  279. /**
  280. * The Buffer constructor returns instances of `Uint8Array` that have their
  281. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  282. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  283. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  284. * returns a single octet.
  285. *
  286. * The `Uint8Array` prototype remains unmodified.
  287. */
  288. function Buffer (arg, encodingOrOffset, length) {
  289. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  290. return new Buffer(arg, encodingOrOffset, length)
  291. }
  292. // Common case.
  293. if (typeof arg === 'number') {
  294. if (typeof encodingOrOffset === 'string') {
  295. throw new Error(
  296. 'If encoding is specified then the first argument must be a string'
  297. )
  298. }
  299. return allocUnsafe(this, arg)
  300. }
  301. return from(this, arg, encodingOrOffset, length)
  302. }
  303. Buffer.poolSize = 8192 // not used by this implementation
  304. // TODO: Legacy, not needed anymore. Remove in next major version.
  305. Buffer._augment = function (arr) {
  306. arr.__proto__ = Buffer.prototype
  307. return arr
  308. }
  309. function from (that, value, encodingOrOffset, length) {
  310. if (typeof value === 'number') {
  311. throw new TypeError('"value" argument must not be a number')
  312. }
  313. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  314. return fromArrayBuffer(that, value, encodingOrOffset, length)
  315. }
  316. if (typeof value === 'string') {
  317. return fromString(that, value, encodingOrOffset)
  318. }
  319. return fromObject(that, value)
  320. }
  321. /**
  322. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  323. * if value is a number.
  324. * Buffer.from(str[, encoding])
  325. * Buffer.from(array)
  326. * Buffer.from(buffer)
  327. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  328. **/
  329. Buffer.from = function (value, encodingOrOffset, length) {
  330. return from(null, value, encodingOrOffset, length)
  331. }
  332. if (Buffer.TYPED_ARRAY_SUPPORT) {
  333. Buffer.prototype.__proto__ = Uint8Array.prototype
  334. Buffer.__proto__ = Uint8Array
  335. if (typeof Symbol !== 'undefined' && Symbol.species &&
  336. Buffer[Symbol.species] === Buffer) {
  337. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  338. Object.defineProperty(Buffer, Symbol.species, {
  339. value: null,
  340. configurable: true
  341. })
  342. }
  343. }
  344. function assertSize (size) {
  345. if (typeof size !== 'number') {
  346. throw new TypeError('"size" argument must be a number')
  347. } else if (size < 0) {
  348. throw new RangeError('"size" argument must not be negative')
  349. }
  350. }
  351. function alloc (that, size, fill, encoding) {
  352. assertSize(size)
  353. if (size <= 0) {
  354. return createBuffer(that, size)
  355. }
  356. if (fill !== undefined) {
  357. // Only pay attention to encoding if it's a string. This
  358. // prevents accidentally sending in a number that would
  359. // be interpretted as a start offset.
  360. return typeof encoding === 'string'
  361. ? createBuffer(that, size).fill(fill, encoding)
  362. : createBuffer(that, size).fill(fill)
  363. }
  364. return createBuffer(that, size)
  365. }
  366. /**
  367. * Creates a new filled Buffer instance.
  368. * alloc(size[, fill[, encoding]])
  369. **/
  370. Buffer.alloc = function (size, fill, encoding) {
  371. return alloc(null, size, fill, encoding)
  372. }
  373. function allocUnsafe (that, size) {
  374. assertSize(size)
  375. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  376. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  377. for (var i = 0; i < size; ++i) {
  378. that[i] = 0
  379. }
  380. }
  381. return that
  382. }
  383. /**
  384. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  385. * */
  386. Buffer.allocUnsafe = function (size) {
  387. return allocUnsafe(null, size)
  388. }
  389. /**
  390. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  391. */
  392. Buffer.allocUnsafeSlow = function (size) {
  393. return allocUnsafe(null, size)
  394. }
  395. function fromString (that, string, encoding) {
  396. if (typeof encoding !== 'string' || encoding === '') {
  397. encoding = 'utf8'
  398. }
  399. if (!Buffer.isEncoding(encoding)) {
  400. throw new TypeError('"encoding" must be a valid string encoding')
  401. }
  402. var length = byteLength(string, encoding) | 0
  403. that = createBuffer(that, length)
  404. var actual = that.write(string, encoding)
  405. if (actual !== length) {
  406. // Writing a hex string, for example, that contains invalid characters will
  407. // cause everything after the first invalid character to be ignored. (e.g.
  408. // 'abxxcd' will be treated as 'ab')
  409. that = that.slice(0, actual)
  410. }
  411. return that
  412. }
  413. function fromArrayLike (that, array) {
  414. var length = array.length < 0 ? 0 : checked(array.length) | 0
  415. that = createBuffer(that, length)
  416. for (var i = 0; i < length; i += 1) {
  417. that[i] = array[i] & 255
  418. }
  419. return that
  420. }
  421. function fromArrayBuffer (that, array, byteOffset, length) {
  422. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  423. if (byteOffset < 0 || array.byteLength < byteOffset) {
  424. throw new RangeError('\'offset\' is out of bounds')
  425. }
  426. if (array.byteLength < byteOffset + (length || 0)) {
  427. throw new RangeError('\'length\' is out of bounds')
  428. }
  429. if (byteOffset === undefined && length === undefined) {
  430. array = new Uint8Array(array)
  431. } else if (length === undefined) {
  432. array = new Uint8Array(array, byteOffset)
  433. } else {
  434. array = new Uint8Array(array, byteOffset, length)
  435. }
  436. if (Buffer.TYPED_ARRAY_SUPPORT) {
  437. // Return an augmented `Uint8Array` instance, for best performance
  438. that = array
  439. that.__proto__ = Buffer.prototype
  440. } else {
  441. // Fallback: Return an object instance of the Buffer class
  442. that = fromArrayLike(that, array)
  443. }
  444. return that
  445. }
  446. function fromObject (that, obj) {
  447. if (Buffer.isBuffer(obj)) {
  448. var len = checked(obj.length) | 0
  449. that = createBuffer(that, len)
  450. if (that.length === 0) {
  451. return that
  452. }
  453. obj.copy(that, 0, 0, len)
  454. return that
  455. }
  456. if (obj) {
  457. if ((typeof ArrayBuffer !== 'undefined' &&
  458. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  459. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  460. return createBuffer(that, 0)
  461. }
  462. return fromArrayLike(that, obj)
  463. }
  464. if (obj.type === 'Buffer' && isArray(obj.data)) {
  465. return fromArrayLike(that, obj.data)
  466. }
  467. }
  468. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  469. }
  470. function checked (length) {
  471. // Note: cannot use `length < kMaxLength()` here because that fails when
  472. // length is NaN (which is otherwise coerced to zero.)
  473. if (length >= kMaxLength()) {
  474. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  475. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  476. }
  477. return length | 0
  478. }
  479. function SlowBuffer (length) {
  480. if (+length != length) { // eslint-disable-line eqeqeq
  481. length = 0
  482. }
  483. return Buffer.alloc(+length)
  484. }
  485. Buffer.isBuffer = function isBuffer (b) {
  486. return !!(b != null && b._isBuffer)
  487. }
  488. Buffer.compare = function compare (a, b) {
  489. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  490. throw new TypeError('Arguments must be Buffers')
  491. }
  492. if (a === b) return 0
  493. var x = a.length
  494. var y = b.length
  495. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  496. if (a[i] !== b[i]) {
  497. x = a[i]
  498. y = b[i]
  499. break
  500. }
  501. }
  502. if (x < y) return -1
  503. if (y < x) return 1
  504. return 0
  505. }
  506. Buffer.isEncoding = function isEncoding (encoding) {
  507. switch (String(encoding).toLowerCase()) {
  508. case 'hex':
  509. case 'utf8':
  510. case 'utf-8':
  511. case 'ascii':
  512. case 'latin1':
  513. case 'binary':
  514. case 'base64':
  515. case 'ucs2':
  516. case 'ucs-2':
  517. case 'utf16le':
  518. case 'utf-16le':
  519. return true
  520. default:
  521. return false
  522. }
  523. }
  524. Buffer.concat = function concat (list, length) {
  525. if (!isArray(list)) {
  526. throw new TypeError('"list" argument must be an Array of Buffers')
  527. }
  528. if (list.length === 0) {
  529. return Buffer.alloc(0)
  530. }
  531. var i
  532. if (length === undefined) {
  533. length = 0
  534. for (i = 0; i < list.length; ++i) {
  535. length += list[i].length
  536. }
  537. }
  538. var buffer = Buffer.allocUnsafe(length)
  539. var pos = 0
  540. for (i = 0; i < list.length; ++i) {
  541. var buf = list[i]
  542. if (!Buffer.isBuffer(buf)) {
  543. throw new TypeError('"list" argument must be an Array of Buffers')
  544. }
  545. buf.copy(buffer, pos)
  546. pos += buf.length
  547. }
  548. return buffer
  549. }
  550. function byteLength (string, encoding) {
  551. if (Buffer.isBuffer(string)) {
  552. return string.length
  553. }
  554. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  555. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  556. return string.byteLength
  557. }
  558. if (typeof string !== 'string') {
  559. string = '' + string
  560. }
  561. var len = string.length
  562. if (len === 0) return 0
  563. // Use a for loop to avoid recursion
  564. var loweredCase = false
  565. for (;;) {
  566. switch (encoding) {
  567. case 'ascii':
  568. case 'latin1':
  569. case 'binary':
  570. return len
  571. case 'utf8':
  572. case 'utf-8':
  573. case undefined:
  574. return utf8ToBytes(string).length
  575. case 'ucs2':
  576. case 'ucs-2':
  577. case 'utf16le':
  578. case 'utf-16le':
  579. return len * 2
  580. case 'hex':
  581. return len >>> 1
  582. case 'base64':
  583. return base64ToBytes(string).length
  584. default:
  585. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  586. encoding = ('' + encoding).toLowerCase()
  587. loweredCase = true
  588. }
  589. }
  590. }
  591. Buffer.byteLength = byteLength
  592. function slowToString (encoding, start, end) {
  593. var loweredCase = false
  594. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  595. // property of a typed array.
  596. // This behaves neither like String nor Uint8Array in that we set start/end
  597. // to their upper/lower bounds if the value passed is out of range.
  598. // undefined is handled specially as per ECMA-262 6th Edition,
  599. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  600. if (start === undefined || start < 0) {
  601. start = 0
  602. }
  603. // Return early if start > this.length. Done here to prevent potential uint32
  604. // coercion fail below.
  605. if (start > this.length) {
  606. return ''
  607. }
  608. if (end === undefined || end > this.length) {
  609. end = this.length
  610. }
  611. if (end <= 0) {
  612. return ''
  613. }
  614. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  615. end >>>= 0
  616. start >>>= 0
  617. if (end <= start) {
  618. return ''
  619. }
  620. if (!encoding) encoding = 'utf8'
  621. while (true) {
  622. switch (encoding) {
  623. case 'hex':
  624. return hexSlice(this, start, end)
  625. case 'utf8':
  626. case 'utf-8':
  627. return utf8Slice(this, start, end)
  628. case 'ascii':
  629. return asciiSlice(this, start, end)
  630. case 'latin1':
  631. case 'binary':
  632. return latin1Slice(this, start, end)
  633. case 'base64':
  634. return base64Slice(this, start, end)
  635. case 'ucs2':
  636. case 'ucs-2':
  637. case 'utf16le':
  638. case 'utf-16le':
  639. return utf16leSlice(this, start, end)
  640. default:
  641. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  642. encoding = (encoding + '').toLowerCase()
  643. loweredCase = true
  644. }
  645. }
  646. }
  647. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  648. // Buffer instances.
  649. Buffer.prototype._isBuffer = true
  650. function swap (b, n, m) {
  651. var i = b[n]
  652. b[n] = b[m]
  653. b[m] = i
  654. }
  655. Buffer.prototype.swap16 = function swap16 () {
  656. var len = this.length
  657. if (len % 2 !== 0) {
  658. throw new RangeError('Buffer size must be a multiple of 16-bits')
  659. }
  660. for (var i = 0; i < len; i += 2) {
  661. swap(this, i, i + 1)
  662. }
  663. return this
  664. }
  665. Buffer.prototype.swap32 = function swap32 () {
  666. var len = this.length
  667. if (len % 4 !== 0) {
  668. throw new RangeError('Buffer size must be a multiple of 32-bits')
  669. }
  670. for (var i = 0; i < len; i += 4) {
  671. swap(this, i, i + 3)
  672. swap(this, i + 1, i + 2)
  673. }
  674. return this
  675. }
  676. Buffer.prototype.swap64 = function swap64 () {
  677. var len = this.length
  678. if (len % 8 !== 0) {
  679. throw new RangeError('Buffer size must be a multiple of 64-bits')
  680. }
  681. for (var i = 0; i < len; i += 8) {
  682. swap(this, i, i + 7)
  683. swap(this, i + 1, i + 6)
  684. swap(this, i + 2, i + 5)
  685. swap(this, i + 3, i + 4)
  686. }
  687. return this
  688. }
  689. Buffer.prototype.toString = function toString () {
  690. var length = this.length | 0
  691. if (length === 0) return ''
  692. if (arguments.length === 0) return utf8Slice(this, 0, length)
  693. return slowToString.apply(this, arguments)
  694. }
  695. Buffer.prototype.equals = function equals (b) {
  696. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  697. if (this === b) return true
  698. return Buffer.compare(this, b) === 0
  699. }
  700. Buffer.prototype.inspect = function inspect () {
  701. var str = ''
  702. var max = exports.INSPECT_MAX_BYTES
  703. if (this.length > 0) {
  704. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  705. if (this.length > max) str += ' ... '
  706. }
  707. return '<Buffer ' + str + '>'
  708. }
  709. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  710. if (!Buffer.isBuffer(target)) {
  711. throw new TypeError('Argument must be a Buffer')
  712. }
  713. if (start === undefined) {
  714. start = 0
  715. }
  716. if (end === undefined) {
  717. end = target ? target.length : 0
  718. }
  719. if (thisStart === undefined) {
  720. thisStart = 0
  721. }
  722. if (thisEnd === undefined) {
  723. thisEnd = this.length
  724. }
  725. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  726. throw new RangeError('out of range index')
  727. }
  728. if (thisStart >= thisEnd && start >= end) {
  729. return 0
  730. }
  731. if (thisStart >= thisEnd) {
  732. return -1
  733. }
  734. if (start >= end) {
  735. return 1
  736. }
  737. start >>>= 0
  738. end >>>= 0
  739. thisStart >>>= 0
  740. thisEnd >>>= 0
  741. if (this === target) return 0
  742. var x = thisEnd - thisStart
  743. var y = end - start
  744. var len = Math.min(x, y)
  745. var thisCopy = this.slice(thisStart, thisEnd)
  746. var targetCopy = target.slice(start, end)
  747. for (var i = 0; i < len; ++i) {
  748. if (thisCopy[i] !== targetCopy[i]) {
  749. x = thisCopy[i]
  750. y = targetCopy[i]
  751. break
  752. }
  753. }
  754. if (x < y) return -1
  755. if (y < x) return 1
  756. return 0
  757. }
  758. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  759. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  760. //
  761. // Arguments:
  762. // - buffer - a Buffer to search
  763. // - val - a string, Buffer, or number
  764. // - byteOffset - an index into `buffer`; will be clamped to an int32
  765. // - encoding - an optional encoding, relevant is val is a string
  766. // - dir - true for indexOf, false for lastIndexOf
  767. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  768. // Empty buffer means no match
  769. if (buffer.length === 0) return -1
  770. // Normalize byteOffset
  771. if (typeof byteOffset === 'string') {
  772. encoding = byteOffset
  773. byteOffset = 0
  774. } else if (byteOffset > 0x7fffffff) {
  775. byteOffset = 0x7fffffff
  776. } else if (byteOffset < -0x80000000) {
  777. byteOffset = -0x80000000
  778. }
  779. byteOffset = +byteOffset // Coerce to Number.
  780. if (isNaN(byteOffset)) {
  781. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  782. byteOffset = dir ? 0 : (buffer.length - 1)
  783. }
  784. // Normalize byteOffset: negative offsets start from the end of the buffer
  785. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  786. if (byteOffset >= buffer.length) {
  787. if (dir) return -1
  788. else byteOffset = buffer.length - 1
  789. } else if (byteOffset < 0) {
  790. if (dir) byteOffset = 0
  791. else return -1
  792. }
  793. // Normalize val
  794. if (typeof val === 'string') {
  795. val = Buffer.from(val, encoding)
  796. }
  797. // Finally, search either indexOf (if dir is true) or lastIndexOf
  798. if (Buffer.isBuffer(val)) {
  799. // Special case: looking for empty string/buffer always fails
  800. if (val.length === 0) {
  801. return -1
  802. }
  803. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  804. } else if (typeof val === 'number') {
  805. val = val & 0xFF // Search for a byte value [0-255]
  806. if (Buffer.TYPED_ARRAY_SUPPORT &&
  807. typeof Uint8Array.prototype.indexOf === 'function') {
  808. if (dir) {
  809. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  810. } else {
  811. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  812. }
  813. }
  814. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  815. }
  816. throw new TypeError('val must be string, number or Buffer')
  817. }
  818. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  819. var indexSize = 1
  820. var arrLength = arr.length
  821. var valLength = val.length
  822. if (encoding !== undefined) {
  823. encoding = String(encoding).toLowerCase()
  824. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  825. encoding === 'utf16le' || encoding === 'utf-16le') {
  826. if (arr.length < 2 || val.length < 2) {
  827. return -1
  828. }
  829. indexSize = 2
  830. arrLength /= 2
  831. valLength /= 2
  832. byteOffset /= 2
  833. }
  834. }
  835. function read (buf, i) {
  836. if (indexSize === 1) {
  837. return buf[i]
  838. } else {
  839. return buf.readUInt16BE(i * indexSize)
  840. }
  841. }
  842. var i
  843. if (dir) {
  844. var foundIndex = -1
  845. for (i = byteOffset; i < arrLength; i++) {
  846. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  847. if (foundIndex === -1) foundIndex = i
  848. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  849. } else {
  850. if (foundIndex !== -1) i -= i - foundIndex
  851. foundIndex = -1
  852. }
  853. }
  854. } else {
  855. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  856. for (i = byteOffset; i >= 0; i--) {
  857. var found = true
  858. for (var j = 0; j < valLength; j++) {
  859. if (read(arr, i + j) !== read(val, j)) {
  860. found = false
  861. break
  862. }
  863. }
  864. if (found) return i
  865. }
  866. }
  867. return -1
  868. }
  869. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  870. return this.indexOf(val, byteOffset, encoding) !== -1
  871. }
  872. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  873. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  874. }
  875. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  876. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  877. }
  878. function hexWrite (buf, string, offset, length) {
  879. offset = Number(offset) || 0
  880. var remaining = buf.length - offset
  881. if (!length) {
  882. length = remaining
  883. } else {
  884. length = Number(length)
  885. if (length > remaining) {
  886. length = remaining
  887. }
  888. }
  889. // must be an even number of digits
  890. var strLen = string.length
  891. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  892. if (length > strLen / 2) {
  893. length = strLen / 2
  894. }
  895. for (var i = 0; i < length; ++i) {
  896. var parsed = parseInt(string.substr(i * 2, 2), 16)
  897. if (isNaN(parsed)) return i
  898. buf[offset + i] = parsed
  899. }
  900. return i
  901. }
  902. function utf8Write (buf, string, offset, length) {
  903. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  904. }
  905. function asciiWrite (buf, string, offset, length) {
  906. return blitBuffer(asciiToBytes(string), buf, offset, length)
  907. }
  908. function latin1Write (buf, string, offset, length) {
  909. return asciiWrite(buf, string, offset, length)
  910. }
  911. function base64Write (buf, string, offset, length) {
  912. return blitBuffer(base64ToBytes(string), buf, offset, length)
  913. }
  914. function ucs2Write (buf, string, offset, length) {
  915. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  916. }
  917. Buffer.prototype.write = function write (string, offset, length, encoding) {
  918. // Buffer#write(string)
  919. if (offset === undefined) {
  920. encoding = 'utf8'
  921. length = this.length
  922. offset = 0
  923. // Buffer#write(string, encoding)
  924. } else if (length === undefined && typeof offset === 'string') {
  925. encoding = offset
  926. length = this.length
  927. offset = 0
  928. // Buffer#write(string, offset[, length][, encoding])
  929. } else if (isFinite(offset)) {
  930. offset = offset | 0
  931. if (isFinite(length)) {
  932. length = length | 0
  933. if (encoding === undefined) encoding = 'utf8'
  934. } else {
  935. encoding = length
  936. length = undefined
  937. }
  938. // legacy write(string, encoding, offset, length) - remove in v0.13
  939. } else {
  940. throw new Error(
  941. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  942. )
  943. }
  944. var remaining = this.length - offset
  945. if (length === undefined || length > remaining) length = remaining
  946. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  947. throw new RangeError('Attempt to write outside buffer bounds')
  948. }
  949. if (!encoding) encoding = 'utf8'
  950. var loweredCase = false
  951. for (;;) {
  952. switch (encoding) {
  953. case 'hex':
  954. return hexWrite(this, string, offset, length)
  955. case 'utf8':
  956. case 'utf-8':
  957. return utf8Write(this, string, offset, length)
  958. case 'ascii':
  959. return asciiWrite(this, string, offset, length)
  960. case 'latin1':
  961. case 'binary':
  962. return latin1Write(this, string, offset, length)
  963. case 'base64':
  964. // Warning: maxLength not taken into account in base64Write
  965. return base64Write(this, string, offset, length)
  966. case 'ucs2':
  967. case 'ucs-2':
  968. case 'utf16le':
  969. case 'utf-16le':
  970. return ucs2Write(this, string, offset, length)
  971. default:
  972. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  973. encoding = ('' + encoding).toLowerCase()
  974. loweredCase = true
  975. }
  976. }
  977. }
  978. Buffer.prototype.toJSON = function toJSON () {
  979. return {
  980. type: 'Buffer',
  981. data: Array.prototype.slice.call(this._arr || this, 0)
  982. }
  983. }
  984. function base64Slice (buf, start, end) {
  985. if (start === 0 && end === buf.length) {
  986. return base64.fromByteArray(buf)
  987. } else {
  988. return base64.fromByteArray(buf.slice(start, end))
  989. }
  990. }
  991. function utf8Slice (buf, start, end) {
  992. end = Math.min(buf.length, end)
  993. var res = []
  994. var i = start
  995. while (i < end) {
  996. var firstByte = buf[i]
  997. var codePoint = null
  998. var bytesPerSequence = (firstByte > 0xEF) ? 4
  999. : (firstByte > 0xDF) ? 3
  1000. : (firstByte > 0xBF) ? 2
  1001. : 1
  1002. if (i + bytesPerSequence <= end) {
  1003. var secondByte, thirdByte, fourthByte, tempCodePoint
  1004. switch (bytesPerSequence) {
  1005. case 1:
  1006. if (firstByte < 0x80) {
  1007. codePoint = firstByte
  1008. }
  1009. break
  1010. case 2:
  1011. secondByte = buf[i + 1]
  1012. if ((secondByte & 0xC0) === 0x80) {
  1013. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1014. if (tempCodePoint > 0x7F) {
  1015. codePoint = tempCodePoint
  1016. }
  1017. }
  1018. break
  1019. case 3:
  1020. secondByte = buf[i + 1]
  1021. thirdByte = buf[i + 2]
  1022. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1023. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1024. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1025. codePoint = tempCodePoint
  1026. }
  1027. }
  1028. break
  1029. case 4:
  1030. secondByte = buf[i + 1]
  1031. thirdByte = buf[i + 2]
  1032. fourthByte = buf[i + 3]
  1033. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1034. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1035. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1036. codePoint = tempCodePoint
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if (codePoint === null) {
  1042. // we did not generate a valid codePoint so insert a
  1043. // replacement char (U+FFFD) and advance only 1 byte
  1044. codePoint = 0xFFFD
  1045. bytesPerSequence = 1
  1046. } else if (codePoint > 0xFFFF) {
  1047. // encode to utf16 (surrogate pair dance)
  1048. codePoint -= 0x10000
  1049. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1050. codePoint = 0xDC00 | codePoint & 0x3FF
  1051. }
  1052. res.push(codePoint)
  1053. i += bytesPerSequence
  1054. }
  1055. return decodeCodePointsArray(res)
  1056. }
  1057. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1058. // the lowest limit is Chrome, with 0x10000 args.
  1059. // We go 1 magnitude less, for safety
  1060. var MAX_ARGUMENTS_LENGTH = 0x1000
  1061. function decodeCodePointsArray (codePoints) {
  1062. var len = codePoints.length
  1063. if (len <= MAX_ARGUMENTS_LENGTH) {
  1064. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1065. }
  1066. // Decode in chunks to avoid "call stack size exceeded".
  1067. var res = ''
  1068. var i = 0
  1069. while (i < len) {
  1070. res += String.fromCharCode.apply(
  1071. String,
  1072. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1073. )
  1074. }
  1075. return res
  1076. }
  1077. function asciiSlice (buf, start, end) {
  1078. var ret = ''
  1079. end = Math.min(buf.length, end)
  1080. for (var i = start; i < end; ++i) {
  1081. ret += String.fromCharCode(buf[i] & 0x7F)
  1082. }
  1083. return ret
  1084. }
  1085. function latin1Slice (buf, start, end) {
  1086. var ret = ''
  1087. end = Math.min(buf.length, end)
  1088. for (var i = start; i < end; ++i) {
  1089. ret += String.fromCharCode(buf[i])
  1090. }
  1091. return ret
  1092. }
  1093. function hexSlice (buf, start, end) {
  1094. var len = buf.length
  1095. if (!start || start < 0) start = 0
  1096. if (!end || end < 0 || end > len) end = len
  1097. var out = ''
  1098. for (var i = start; i < end; ++i) {
  1099. out += toHex(buf[i])
  1100. }
  1101. return out
  1102. }
  1103. function utf16leSlice (buf, start, end) {
  1104. var bytes = buf.slice(start, end)
  1105. var res = ''
  1106. for (var i = 0; i < bytes.length; i += 2) {
  1107. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1108. }
  1109. return res
  1110. }
  1111. Buffer.prototype.slice = function slice (start, end) {
  1112. var len = this.length
  1113. start = ~~start
  1114. end = end === undefined ? len : ~~end
  1115. if (start < 0) {
  1116. start += len
  1117. if (start < 0) start = 0
  1118. } else if (start > len) {
  1119. start = len
  1120. }
  1121. if (end < 0) {
  1122. end += len
  1123. if (end < 0) end = 0
  1124. } else if (end > len) {
  1125. end = len
  1126. }
  1127. if (end < start) end = start
  1128. var newBuf
  1129. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1130. newBuf = this.subarray(start, end)
  1131. newBuf.__proto__ = Buffer.prototype
  1132. } else {
  1133. var sliceLen = end - start
  1134. newBuf = new Buffer(sliceLen, undefined)
  1135. for (var i = 0; i < sliceLen; ++i) {
  1136. newBuf[i] = this[i + start]
  1137. }
  1138. }
  1139. return newBuf
  1140. }
  1141. /*
  1142. * Need to make sure that buffer isn't trying to write out of bounds.
  1143. */
  1144. function checkOffset (offset, ext, length) {
  1145. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1146. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1147. }
  1148. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1149. offset = offset | 0
  1150. byteLength = byteLength | 0
  1151. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1152. var val = this[offset]
  1153. var mul = 1
  1154. var i = 0
  1155. while (++i < byteLength && (mul *= 0x100)) {
  1156. val += this[offset + i] * mul
  1157. }
  1158. return val
  1159. }
  1160. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1161. offset = offset | 0
  1162. byteLength = byteLength | 0
  1163. if (!noAssert) {
  1164. checkOffset(offset, byteLength, this.length)
  1165. }
  1166. var val = this[offset + --byteLength]
  1167. var mul = 1
  1168. while (byteLength > 0 && (mul *= 0x100)) {
  1169. val += this[offset + --byteLength] * mul
  1170. }
  1171. return val
  1172. }
  1173. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1174. if (!noAssert) checkOffset(offset, 1, this.length)
  1175. return this[offset]
  1176. }
  1177. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1178. if (!noAssert) checkOffset(offset, 2, this.length)
  1179. return this[offset] | (this[offset + 1] << 8)
  1180. }
  1181. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1182. if (!noAssert) checkOffset(offset, 2, this.length)
  1183. return (this[offset] << 8) | this[offset + 1]
  1184. }
  1185. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1186. if (!noAssert) checkOffset(offset, 4, this.length)
  1187. return ((this[offset]) |
  1188. (this[offset + 1] << 8) |
  1189. (this[offset + 2] << 16)) +
  1190. (this[offset + 3] * 0x1000000)
  1191. }
  1192. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 4, this.length)
  1194. return (this[offset] * 0x1000000) +
  1195. ((this[offset + 1] << 16) |
  1196. (this[offset + 2] << 8) |
  1197. this[offset + 3])
  1198. }
  1199. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1200. offset = offset | 0
  1201. byteLength = byteLength | 0
  1202. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1203. var val = this[offset]
  1204. var mul = 1
  1205. var i = 0
  1206. while (++i < byteLength && (mul *= 0x100)) {
  1207. val += this[offset + i] * mul
  1208. }
  1209. mul *= 0x80
  1210. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1211. return val
  1212. }
  1213. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1214. offset = offset | 0
  1215. byteLength = byteLength | 0
  1216. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1217. var i = byteLength
  1218. var mul = 1
  1219. var val = this[offset + --i]
  1220. while (i > 0 && (mul *= 0x100)) {
  1221. val += this[offset + --i] * mul
  1222. }
  1223. mul *= 0x80
  1224. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1225. return val
  1226. }
  1227. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1228. if (!noAssert) checkOffset(offset, 1, this.length)
  1229. if (!(this[offset] & 0x80)) return (this[offset])
  1230. return ((0xff - this[offset] + 1) * -1)
  1231. }
  1232. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1233. if (!noAssert) checkOffset(offset, 2, this.length)
  1234. var val = this[offset] | (this[offset + 1] << 8)
  1235. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1236. }
  1237. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 2, this.length)
  1239. var val = this[offset + 1] | (this[offset] << 8)
  1240. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1241. }
  1242. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1243. if (!noAssert) checkOffset(offset, 4, this.length)
  1244. return (this[offset]) |
  1245. (this[offset + 1] << 8) |
  1246. (this[offset + 2] << 16) |
  1247. (this[offset + 3] << 24)
  1248. }
  1249. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1250. if (!noAssert) checkOffset(offset, 4, this.length)
  1251. return (this[offset] << 24) |
  1252. (this[offset + 1] << 16) |
  1253. (this[offset + 2] << 8) |
  1254. (this[offset + 3])
  1255. }
  1256. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1257. if (!noAssert) checkOffset(offset, 4, this.length)
  1258. return ieee754.read(this, offset, true, 23, 4)
  1259. }
  1260. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1261. if (!noAssert) checkOffset(offset, 4, this.length)
  1262. return ieee754.read(this, offset, false, 23, 4)
  1263. }
  1264. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1265. if (!noAssert) checkOffset(offset, 8, this.length)
  1266. return ieee754.read(this, offset, true, 52, 8)
  1267. }
  1268. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1269. if (!noAssert) checkOffset(offset, 8, this.length)
  1270. return ieee754.read(this, offset, false, 52, 8)
  1271. }
  1272. function checkInt (buf, value, offset, ext, max, min) {
  1273. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1274. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1275. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1276. }
  1277. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1278. value = +value
  1279. offset = offset | 0
  1280. byteLength = byteLength | 0
  1281. if (!noAssert) {
  1282. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1283. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1284. }
  1285. var mul = 1
  1286. var i = 0
  1287. this[offset] = value & 0xFF
  1288. while (++i < byteLength && (mul *= 0x100)) {
  1289. this[offset + i] = (value / mul) & 0xFF
  1290. }
  1291. return offset + byteLength
  1292. }
  1293. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. byteLength = byteLength | 0
  1297. if (!noAssert) {
  1298. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1299. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1300. }
  1301. var i = byteLength - 1
  1302. var mul = 1
  1303. this[offset + i] = value & 0xFF
  1304. while (--i >= 0 && (mul *= 0x100)) {
  1305. this[offset + i] = (value / mul) & 0xFF
  1306. }
  1307. return offset + byteLength
  1308. }
  1309. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1310. value = +value
  1311. offset = offset | 0
  1312. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1313. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1314. this[offset] = (value & 0xff)
  1315. return offset + 1
  1316. }
  1317. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1318. if (value < 0) value = 0xffff + value + 1
  1319. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1320. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1321. (littleEndian ? i : 1 - i) * 8
  1322. }
  1323. }
  1324. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1325. value = +value
  1326. offset = offset | 0
  1327. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1328. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1329. this[offset] = (value & 0xff)
  1330. this[offset + 1] = (value >>> 8)
  1331. } else {
  1332. objectWriteUInt16(this, value, offset, true)
  1333. }
  1334. return offset + 2
  1335. }
  1336. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1337. value = +value
  1338. offset = offset | 0
  1339. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1340. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1341. this[offset] = (value >>> 8)
  1342. this[offset + 1] = (value & 0xff)
  1343. } else {
  1344. objectWriteUInt16(this, value, offset, false)
  1345. }
  1346. return offset + 2
  1347. }
  1348. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1349. if (value < 0) value = 0xffffffff + value + 1
  1350. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1351. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1352. }
  1353. }
  1354. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1355. value = +value
  1356. offset = offset | 0
  1357. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1358. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1359. this[offset + 3] = (value >>> 24)
  1360. this[offset + 2] = (value >>> 16)
  1361. this[offset + 1] = (value >>> 8)
  1362. this[offset] = (value & 0xff)
  1363. } else {
  1364. objectWriteUInt32(this, value, offset, true)
  1365. }
  1366. return offset + 4
  1367. }
  1368. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1369. value = +value
  1370. offset = offset | 0
  1371. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1372. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1373. this[offset] = (value >>> 24)
  1374. this[offset + 1] = (value >>> 16)
  1375. this[offset + 2] = (value >>> 8)
  1376. this[offset + 3] = (value & 0xff)
  1377. } else {
  1378. objectWriteUInt32(this, value, offset, false)
  1379. }
  1380. return offset + 4
  1381. }
  1382. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1383. value = +value
  1384. offset = offset | 0
  1385. if (!noAssert) {
  1386. var limit = Math.pow(2, 8 * byteLength - 1)
  1387. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1388. }
  1389. var i = 0
  1390. var mul = 1
  1391. var sub = 0
  1392. this[offset] = value & 0xFF
  1393. while (++i < byteLength && (mul *= 0x100)) {
  1394. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1395. sub = 1
  1396. }
  1397. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1398. }
  1399. return offset + byteLength
  1400. }
  1401. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1402. value = +value
  1403. offset = offset | 0
  1404. if (!noAssert) {
  1405. var limit = Math.pow(2, 8 * byteLength - 1)
  1406. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1407. }
  1408. var i = byteLength - 1
  1409. var mul = 1
  1410. var sub = 0
  1411. this[offset + i] = value & 0xFF
  1412. while (--i >= 0 && (mul *= 0x100)) {
  1413. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1414. sub = 1
  1415. }
  1416. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1417. }
  1418. return offset + byteLength
  1419. }
  1420. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1421. value = +value
  1422. offset = offset | 0
  1423. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1424. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1425. if (value < 0) value = 0xff + value + 1
  1426. this[offset] = (value & 0xff)
  1427. return offset + 1
  1428. }
  1429. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1430. value = +value
  1431. offset = offset | 0
  1432. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1433. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1434. this[offset] = (value & 0xff)
  1435. this[offset + 1] = (value >>> 8)
  1436. } else {
  1437. objectWriteUInt16(this, value, offset, true)
  1438. }
  1439. return offset + 2
  1440. }
  1441. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1442. value = +value
  1443. offset = offset | 0
  1444. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1445. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1446. this[offset] = (value >>> 8)
  1447. this[offset + 1] = (value & 0xff)
  1448. } else {
  1449. objectWriteUInt16(this, value, offset, false)
  1450. }
  1451. return offset + 2
  1452. }
  1453. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1454. value = +value
  1455. offset = offset | 0
  1456. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1457. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1458. this[offset] = (value & 0xff)
  1459. this[offset + 1] = (value >>> 8)
  1460. this[offset + 2] = (value >>> 16)
  1461. this[offset + 3] = (value >>> 24)
  1462. } else {
  1463. objectWriteUInt32(this, value, offset, true)
  1464. }
  1465. return offset + 4
  1466. }
  1467. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1468. value = +value
  1469. offset = offset | 0
  1470. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1471. if (value < 0) value = 0xffffffff + value + 1
  1472. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1473. this[offset] = (value >>> 24)
  1474. this[offset + 1] = (value >>> 16)
  1475. this[offset + 2] = (value >>> 8)
  1476. this[offset + 3] = (value & 0xff)
  1477. } else {
  1478. objectWriteUInt32(this, value, offset, false)
  1479. }
  1480. return offset + 4
  1481. }
  1482. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1483. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1484. if (offset < 0) throw new RangeError('Index out of range')
  1485. }
  1486. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1487. if (!noAssert) {
  1488. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1489. }
  1490. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1491. return offset + 4
  1492. }
  1493. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1494. return writeFloat(this, value, offset, true, noAssert)
  1495. }
  1496. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1497. return writeFloat(this, value, offset, false, noAssert)
  1498. }
  1499. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1500. if (!noAssert) {
  1501. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1502. }
  1503. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1504. return offset + 8
  1505. }
  1506. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1507. return writeDouble(this, value, offset, true, noAssert)
  1508. }
  1509. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1510. return writeDouble(this, value, offset, false, noAssert)
  1511. }
  1512. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1513. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1514. if (!start) start = 0
  1515. if (!end && end !== 0) end = this.length
  1516. if (targetStart >= target.length) targetStart = target.length
  1517. if (!targetStart) targetStart = 0
  1518. if (end > 0 && end < start) end = start
  1519. // Copy 0 bytes; we're done
  1520. if (end === start) return 0
  1521. if (target.length === 0 || this.length === 0) return 0
  1522. // Fatal error conditions
  1523. if (targetStart < 0) {
  1524. throw new RangeError('targetStart out of bounds')
  1525. }
  1526. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1527. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1528. // Are we oob?
  1529. if (end > this.length) end = this.length
  1530. if (target.length - targetStart < end - start) {
  1531. end = target.length - targetStart + start
  1532. }
  1533. var len = end - start
  1534. var i
  1535. if (this === target && start < targetStart && targetStart < end) {
  1536. // descending copy from end
  1537. for (i = len - 1; i >= 0; --i) {
  1538. target[i + targetStart] = this[i + start]
  1539. }
  1540. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1541. // ascending copy from start
  1542. for (i = 0; i < len; ++i) {
  1543. target[i + targetStart] = this[i + start]
  1544. }
  1545. } else {
  1546. Uint8Array.prototype.set.call(
  1547. target,
  1548. this.subarray(start, start + len),
  1549. targetStart
  1550. )
  1551. }
  1552. return len
  1553. }
  1554. // Usage:
  1555. // buffer.fill(number[, offset[, end]])
  1556. // buffer.fill(buffer[, offset[, end]])
  1557. // buffer.fill(string[, offset[, end]][, encoding])
  1558. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1559. // Handle string cases:
  1560. if (typeof val === 'string') {
  1561. if (typeof start === 'string') {
  1562. encoding = start
  1563. start = 0
  1564. end = this.length
  1565. } else if (typeof end === 'string') {
  1566. encoding = end
  1567. end = this.length
  1568. }
  1569. if (val.length === 1) {
  1570. var code = val.charCodeAt(0)
  1571. if (code < 256) {
  1572. val = code
  1573. }
  1574. }
  1575. if (encoding !== undefined && typeof encoding !== 'string') {
  1576. throw new TypeError('encoding must be a string')
  1577. }
  1578. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1579. throw new TypeError('Unknown encoding: ' + encoding)
  1580. }
  1581. } else if (typeof val === 'number') {
  1582. val = val & 255
  1583. }
  1584. // Invalid ranges are not set to a default, so can range check early.
  1585. if (start < 0 || this.length < start || this.length < end) {
  1586. throw new RangeError('Out of range index')
  1587. }
  1588. if (end <= start) {
  1589. return this
  1590. }
  1591. start = start >>> 0
  1592. end = end === undefined ? this.length : end >>> 0
  1593. if (!val) val = 0
  1594. var i
  1595. if (typeof val === 'number') {
  1596. for (i = start; i < end; ++i) {
  1597. this[i] = val
  1598. }
  1599. } else {
  1600. var bytes = Buffer.isBuffer(val)
  1601. ? val
  1602. : utf8ToBytes(new Buffer(val, encoding).toString())
  1603. var len = bytes.length
  1604. for (i = 0; i < end - start; ++i) {
  1605. this[i + start] = bytes[i % len]
  1606. }
  1607. }
  1608. return this
  1609. }
  1610. // HELPER FUNCTIONS
  1611. // ================
  1612. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1613. function base64clean (str) {
  1614. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1615. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1616. // Node converts strings with length < 2 to ''
  1617. if (str.length < 2) return ''
  1618. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1619. while (str.length % 4 !== 0) {
  1620. str = str + '='
  1621. }
  1622. return str
  1623. }
  1624. function stringtrim (str) {
  1625. if (str.trim) return str.trim()
  1626. return str.replace(/^\s+|\s+$/g, '')
  1627. }
  1628. function toHex (n) {
  1629. if (n < 16) return '0' + n.toString(16)
  1630. return n.toString(16)
  1631. }
  1632. function utf8ToBytes (string, units) {
  1633. units = units || Infinity
  1634. var codePoint
  1635. var length = string.length
  1636. var leadSurrogate = null
  1637. var bytes = []
  1638. for (var i = 0; i < length; ++i) {
  1639. codePoint = string.charCodeAt(i)
  1640. // is surrogate component
  1641. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1642. // last char was a lead
  1643. if (!leadSurrogate) {
  1644. // no lead yet
  1645. if (codePoint > 0xDBFF) {
  1646. // unexpected trail
  1647. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1648. continue
  1649. } else if (i + 1 === length) {
  1650. // unpaired lead
  1651. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1652. continue
  1653. }
  1654. // valid lead
  1655. leadSurrogate = codePoint
  1656. continue
  1657. }
  1658. // 2 leads in a row
  1659. if (codePoint < 0xDC00) {
  1660. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1661. leadSurrogate = codePoint
  1662. continue
  1663. }
  1664. // valid surrogate pair
  1665. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1666. } else if (leadSurrogate) {
  1667. // valid bmp char, but last char was a lead
  1668. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1669. }
  1670. leadSurrogate = null
  1671. // encode utf8
  1672. if (codePoint < 0x80) {
  1673. if ((units -= 1) < 0) break
  1674. bytes.push(codePoint)
  1675. } else if (codePoint < 0x800) {
  1676. if ((units -= 2) < 0) break
  1677. bytes.push(
  1678. codePoint >> 0x6 | 0xC0,
  1679. codePoint & 0x3F | 0x80
  1680. )
  1681. } else if (codePoint < 0x10000) {
  1682. if ((units -= 3) < 0) break
  1683. bytes.push(
  1684. codePoint >> 0xC | 0xE0,
  1685. codePoint >> 0x6 & 0x3F | 0x80,
  1686. codePoint & 0x3F | 0x80
  1687. )
  1688. } else if (codePoint < 0x110000) {
  1689. if ((units -= 4) < 0) break
  1690. bytes.push(
  1691. codePoint >> 0x12 | 0xF0,
  1692. codePoint >> 0xC & 0x3F | 0x80,
  1693. codePoint >> 0x6 & 0x3F | 0x80,
  1694. codePoint & 0x3F | 0x80
  1695. )
  1696. } else {
  1697. throw new Error('Invalid code point')
  1698. }
  1699. }
  1700. return bytes
  1701. }
  1702. function asciiToBytes (str) {
  1703. var byteArray = []
  1704. for (var i = 0; i < str.length; ++i) {
  1705. // Node's code seems to be doing this and not & 0x7F..
  1706. byteArray.push(str.charCodeAt(i) & 0xFF)
  1707. }
  1708. return byteArray
  1709. }
  1710. function utf16leToBytes (str, units) {
  1711. var c, hi, lo
  1712. var byteArray = []
  1713. for (var i = 0; i < str.length; ++i) {
  1714. if ((units -= 2) < 0) break
  1715. c = str.charCodeAt(i)
  1716. hi = c >> 8
  1717. lo = c % 256
  1718. byteArray.push(lo)
  1719. byteArray.push(hi)
  1720. }
  1721. return byteArray
  1722. }
  1723. function base64ToBytes (str) {
  1724. return base64.toByteArray(base64clean(str))
  1725. }
  1726. function blitBuffer (src, dst, offset, length) {
  1727. for (var i = 0; i < length; ++i) {
  1728. if ((i + offset >= dst.length) || (i >= src.length)) break
  1729. dst[i + offset] = src[i]
  1730. }
  1731. return i
  1732. }
  1733. function isnan (val) {
  1734. return val !== val // eslint-disable-line no-self-compare
  1735. }
  1736. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  1737. },{"base64-js":3,"buffer":6,"ieee754":29,"isarray":35}],7:[function(_dereq_,module,exports){
  1738. // Polyfill for creating CustomEvents on IE9/10/11
  1739. // code pulled from:
  1740. // https://github.com/d4tocchini/customevent-polyfill
  1741. // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
  1742. (function() {
  1743. if (typeof window === 'undefined') {
  1744. return;
  1745. }
  1746. try {
  1747. var ce = new window.CustomEvent('test', { cancelable: true });
  1748. ce.preventDefault();
  1749. if (ce.defaultPrevented !== true) {
  1750. // IE has problems with .preventDefault() on custom events
  1751. // http://stackoverflow.com/questions/23349191
  1752. throw new Error('Could not prevent default');
  1753. }
  1754. } catch (e) {
  1755. var CustomEvent = function(event, params) {
  1756. var evt, origPrevent;
  1757. params = params || {};
  1758. params.bubbles = !!params.bubbles;
  1759. params.cancelable = !!params.cancelable;
  1760. evt = document.createEvent('CustomEvent');
  1761. evt.initCustomEvent(
  1762. event,
  1763. params.bubbles,
  1764. params.cancelable,
  1765. params.detail
  1766. );
  1767. origPrevent = evt.preventDefault;
  1768. evt.preventDefault = function() {
  1769. origPrevent.call(this);
  1770. try {
  1771. Object.defineProperty(this, 'defaultPrevented', {
  1772. get: function() {
  1773. return true;
  1774. }
  1775. });
  1776. } catch (e) {
  1777. this.defaultPrevented = true;
  1778. }
  1779. };
  1780. return evt;
  1781. };
  1782. CustomEvent.prototype = window.Event.prototype;
  1783. window.CustomEvent = CustomEvent; // expose definition to window
  1784. }
  1785. })();
  1786. },{}],8:[function(_dereq_,module,exports){
  1787. /**
  1788. * This is the web browser implementation of `debug()`.
  1789. *
  1790. * Expose `debug()` as the module.
  1791. */
  1792. exports = module.exports = _dereq_('./debug');
  1793. exports.log = log;
  1794. exports.formatArgs = formatArgs;
  1795. exports.save = save;
  1796. exports.load = load;
  1797. exports.useColors = useColors;
  1798. exports.storage = 'undefined' != typeof chrome
  1799. && 'undefined' != typeof chrome.storage
  1800. ? chrome.storage.local
  1801. : localstorage();
  1802. /**
  1803. * Colors.
  1804. */
  1805. exports.colors = [
  1806. 'lightseagreen',
  1807. 'forestgreen',
  1808. 'goldenrod',
  1809. 'dodgerblue',
  1810. 'darkorchid',
  1811. 'crimson'
  1812. ];
  1813. /**
  1814. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1815. * and the Firebug extension (any Firefox version) are known
  1816. * to support "%c" CSS customizations.
  1817. *
  1818. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1819. */
  1820. function useColors() {
  1821. // is webkit? http://stackoverflow.com/a/16459606/376773
  1822. return ('WebkitAppearance' in document.documentElement.style) ||
  1823. // is firebug? http://stackoverflow.com/a/398120/376773
  1824. (window.console && (console.firebug || (console.exception && console.table))) ||
  1825. // is firefox >= v31?
  1826. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1827. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1828. }
  1829. /**
  1830. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1831. */
  1832. exports.formatters.j = function(v) {
  1833. return JSON.stringify(v);
  1834. };
  1835. /**
  1836. * Colorize log arguments if enabled.
  1837. *
  1838. * @api public
  1839. */
  1840. function formatArgs() {
  1841. var args = arguments;
  1842. var useColors = this.useColors;
  1843. args[0] = (useColors ? '%c' : '')
  1844. + this.namespace
  1845. + (useColors ? ' %c' : ' ')
  1846. + args[0]
  1847. + (useColors ? '%c ' : ' ');
  1848. if (!useColors) return args;
  1849. var c = 'color: ' + this.color;
  1850. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1851. // the final "%c" is somewhat tricky, because there could be other
  1852. // arguments passed either before or after the %c, so we need to
  1853. // figure out the correct index to insert the CSS into
  1854. var index = 0;
  1855. var lastC = 0;
  1856. args[0].replace(/%[a-z%]/g, function(match) {
  1857. if ('%%' === match) return;
  1858. index++;
  1859. if ('%c' === match) {
  1860. // we only are interested in the *last* %c
  1861. // (the user may have provided their own)
  1862. lastC = index;
  1863. }
  1864. });
  1865. args.splice(lastC, 0, c);
  1866. return args;
  1867. }
  1868. /**
  1869. * Invokes `console.log()` when available.
  1870. * No-op when `console.log` is not a "function".
  1871. *
  1872. * @api public
  1873. */
  1874. function log() {
  1875. // this hackery is required for IE8/9, where
  1876. // the `console.log` function doesn't have 'apply'
  1877. return 'object' === typeof console
  1878. && console.log
  1879. && Function.prototype.apply.call(console.log, console, arguments);
  1880. }
  1881. /**
  1882. * Save `namespaces`.
  1883. *
  1884. * @param {String} namespaces
  1885. * @api private
  1886. */
  1887. function save(namespaces) {
  1888. try {
  1889. if (null == namespaces) {
  1890. exports.storage.removeItem('debug');
  1891. } else {
  1892. exports.storage.debug = namespaces;
  1893. }
  1894. } catch(e) {}
  1895. }
  1896. /**
  1897. * Load `namespaces`.
  1898. *
  1899. * @return {String} returns the previously persisted debug modes
  1900. * @api private
  1901. */
  1902. function load() {
  1903. var r;
  1904. try {
  1905. r = exports.storage.debug;
  1906. } catch(e) {}
  1907. return r;
  1908. }
  1909. /**
  1910. * Enable namespaces listed in `localStorage.debug` initially.
  1911. */
  1912. exports.enable(load());
  1913. /**
  1914. * Localstorage attempts to return the localstorage.
  1915. *
  1916. * This is necessary because safari throws
  1917. * when a user disables cookies/localstorage
  1918. * and you attempt to access it.
  1919. *
  1920. * @return {LocalStorage}
  1921. * @api private
  1922. */
  1923. function localstorage(){
  1924. try {
  1925. return window.localStorage;
  1926. } catch (e) {}
  1927. }
  1928. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1929. /**
  1930. * This is the common logic for both the Node.js and web browser
  1931. * implementations of `debug()`.
  1932. *
  1933. * Expose `debug()` as the module.
  1934. */
  1935. exports = module.exports = debug;
  1936. exports.coerce = coerce;
  1937. exports.disable = disable;
  1938. exports.enable = enable;
  1939. exports.enabled = enabled;
  1940. /**
  1941. * The currently active debug mode names, and names to skip.
  1942. */
  1943. exports.names = [];
  1944. exports.skips = [];
  1945. /**
  1946. * Map of special "%n" handling functions, for the debug "format" argument.
  1947. *
  1948. * Valid key names are a single, lowercased letter, i.e. "n".
  1949. */
  1950. exports.formatters = {};
  1951. /**
  1952. * Previously assigned color.
  1953. */
  1954. var prevColor = 0;
  1955. /**
  1956. * Select a color.
  1957. *
  1958. * @return {Number}
  1959. * @api private
  1960. */
  1961. function selectColor() {
  1962. return exports.colors[prevColor++ % exports.colors.length];
  1963. }
  1964. /**
  1965. * Create a debugger with the given `namespace`.
  1966. *
  1967. * @param {String} namespace
  1968. * @return {Function}
  1969. * @api public
  1970. */
  1971. function debug(namespace) {
  1972. // define the `disabled` version
  1973. function disabled() {
  1974. }
  1975. disabled.enabled = false;
  1976. // define the `enabled` version
  1977. function enabled() {
  1978. var self = enabled;
  1979. // add the `color` if not set
  1980. if (null == self.useColors) self.useColors = exports.useColors();
  1981. if (null == self.color && self.useColors) self.color = selectColor();
  1982. var args = Array.prototype.slice.call(arguments);
  1983. args[0] = exports.coerce(args[0]);
  1984. if ('string' !== typeof args[0]) {
  1985. // anything else let's inspect with %o
  1986. args = ['%o'].concat(args);
  1987. }
  1988. // apply any `formatters` transformations
  1989. var index = 0;
  1990. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1991. // if we encounter an escaped % then don't increase the array index
  1992. if (match === '%%') return match;
  1993. index++;
  1994. var formatter = exports.formatters[format];
  1995. if ('function' === typeof formatter) {
  1996. var val = args[index];
  1997. match = formatter.call(self, val);
  1998. // now we need to remove `args[index]` since it's inlined in the `format`
  1999. args.splice(index, 1);
  2000. index--;
  2001. }
  2002. return match;
  2003. });
  2004. if ('function' === typeof exports.formatArgs) {
  2005. args = exports.formatArgs.apply(self, args);
  2006. }
  2007. var logFn = enabled.log || exports.log || console.log.bind(console);
  2008. logFn.apply(self, args);
  2009. }
  2010. enabled.enabled = true;
  2011. var fn = exports.enabled(namespace) ? enabled : disabled;
  2012. fn.namespace = namespace;
  2013. return fn;
  2014. }
  2015. /**
  2016. * Enables a debug mode by namespaces. This can include modes
  2017. * separated by a colon and wildcards.
  2018. *
  2019. * @param {String} namespaces
  2020. * @api public
  2021. */
  2022. function enable(namespaces) {
  2023. exports.save(namespaces);
  2024. var split = (namespaces || '').split(/[\s,]+/);
  2025. var len = split.length;
  2026. for (var i = 0; i < len; i++) {
  2027. if (!split[i]) continue; // ignore empty strings
  2028. namespaces = split[i].replace(/\*/g, '.*?');
  2029. if (namespaces[0] === '-') {
  2030. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2031. } else {
  2032. exports.names.push(new RegExp('^' + namespaces + '$'));
  2033. }
  2034. }
  2035. }
  2036. /**
  2037. * Disable debug output.
  2038. *
  2039. * @api public
  2040. */
  2041. function disable() {
  2042. exports.enable('');
  2043. }
  2044. /**
  2045. * Returns true if the given mode name is enabled, false otherwise.
  2046. *
  2047. * @param {String} name
  2048. * @return {Boolean}
  2049. * @api public
  2050. */
  2051. function enabled(name) {
  2052. var i, len;
  2053. for (i = 0, len = exports.skips.length; i < len; i++) {
  2054. if (exports.skips[i].test(name)) {
  2055. return false;
  2056. }
  2057. }
  2058. for (i = 0, len = exports.names.length; i < len; i++) {
  2059. if (exports.names[i].test(name)) {
  2060. return true;
  2061. }
  2062. }
  2063. return false;
  2064. }
  2065. /**
  2066. * Coerce `val`.
  2067. *
  2068. * @param {Mixed} val
  2069. * @return {Mixed}
  2070. * @api private
  2071. */
  2072. function coerce(val) {
  2073. if (val instanceof Error) return val.stack || val.message;
  2074. return val;
  2075. }
  2076. },{}],10:[function(_dereq_,module,exports){
  2077. 'use strict';
  2078. var isObj = _dereq_('is-obj');
  2079. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2080. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2081. function toObject(val) {
  2082. if (val === null || val === undefined) {
  2083. throw new TypeError('Sources cannot be null or undefined');
  2084. }
  2085. return Object(val);
  2086. }
  2087. function assignKey(to, from, key) {
  2088. var val = from[key];
  2089. if (val === undefined || val === null) {
  2090. return;
  2091. }
  2092. if (hasOwnProperty.call(to, key)) {
  2093. if (to[key] === undefined || to[key] === null) {
  2094. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2095. }
  2096. }
  2097. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2098. to[key] = val;
  2099. } else {
  2100. to[key] = assign(Object(to[key]), from[key]);
  2101. }
  2102. }
  2103. function assign(to, from) {
  2104. if (to === from) {
  2105. return to;
  2106. }
  2107. from = Object(from);
  2108. for (var key in from) {
  2109. if (hasOwnProperty.call(from, key)) {
  2110. assignKey(to, from, key);
  2111. }
  2112. }
  2113. if (Object.getOwnPropertySymbols) {
  2114. var symbols = Object.getOwnPropertySymbols(from);
  2115. for (var i = 0; i < symbols.length; i++) {
  2116. if (propIsEnumerable.call(from, symbols[i])) {
  2117. assignKey(to, from, symbols[i]);
  2118. }
  2119. }
  2120. }
  2121. return to;
  2122. }
  2123. module.exports = function deepAssign(target) {
  2124. target = toObject(target);
  2125. for (var s = 1; s < arguments.length; s++) {
  2126. assign(target, arguments[s]);
  2127. }
  2128. return target;
  2129. };
  2130. },{"is-obj":34}],11:[function(_dereq_,module,exports){
  2131. 'use strict';
  2132. var keys = _dereq_('object-keys');
  2133. var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
  2134. var toStr = Object.prototype.toString;
  2135. var concat = Array.prototype.concat;
  2136. var origDefineProperty = Object.defineProperty;
  2137. var isFunction = function (fn) {
  2138. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  2139. };
  2140. var arePropertyDescriptorsSupported = function () {
  2141. var obj = {};
  2142. try {
  2143. origDefineProperty(obj, 'x', { enumerable: false, value: obj });
  2144. // eslint-disable-next-line no-unused-vars, no-restricted-syntax
  2145. for (var _ in obj) { // jscs:ignore disallowUnusedVariables
  2146. return false;
  2147. }
  2148. return obj.x === obj;
  2149. } catch (e) { /* this is IE 8. */
  2150. return false;
  2151. }
  2152. };
  2153. var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  2154. var defineProperty = function (object, name, value, predicate) {
  2155. if (name in object && (!isFunction(predicate) || !predicate())) {
  2156. return;
  2157. }
  2158. if (supportsDescriptors) {
  2159. origDefineProperty(object, name, {
  2160. configurable: true,
  2161. enumerable: false,
  2162. value: value,
  2163. writable: true
  2164. });
  2165. } else {
  2166. object[name] = value;
  2167. }
  2168. };
  2169. var defineProperties = function (object, map) {
  2170. var predicates = arguments.length > 2 ? arguments[2] : {};
  2171. var props = keys(map);
  2172. if (hasSymbols) {
  2173. props = concat.call(props, Object.getOwnPropertySymbols(map));
  2174. }
  2175. for (var i = 0; i < props.length; i += 1) {
  2176. defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
  2177. }
  2178. };
  2179. defineProperties.supportsDescriptors = !!supportsDescriptors;
  2180. module.exports = defineProperties;
  2181. },{"object-keys":41}],12:[function(_dereq_,module,exports){
  2182. /*! (C) WebReflection Mit Style License */
  2183. (function(t,n,r,i){"use strict";function st(e,t){for(var n=0,r=e.length;n<r;n++)gt(e[n],t)}function ot(e){for(var t=0,n=e.length,r;t<n;t++)r=e[t],it(r,w[at(r)])}function ut(e){return function(t){F(t)&&(gt(t,e),st(t.querySelectorAll(E),e))}}function at(e){var t=R.call(e,"is"),n=e.nodeName.toUpperCase(),r=x.call(b,t?m+t.toUpperCase():v+n);return t&&-1<r&&!ft(n,t)?-1:r}function ft(e,t){return-1<E.indexOf(e+'[is="'+t+'"]')}function lt(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,i=e.target;Y&&(!i||i===t)&&t.attributeChangedCallback&&r!=="style"&&e.prevValue!==e.newValue&&t.attributeChangedCallback(r,n===e[f]?null:e.prevValue,n===e[c]?null:e.newValue)}function ct(e){var t=ut(e);return function(e){$.push(t,e.target)}}function ht(e){G&&(G=!1,e.currentTarget.removeEventListener(p,ht)),st((e.target||n).querySelectorAll(E),e.detail===u?u:o),j&&vt()}function pt(e,t){var n=this;U.call(n,e,t),Z.call(n,{target:n})}function dt(e,t){P(e,t),nt?nt.observe(e,X):(Q&&(e.setAttribute=pt,e[s]=tt(e),e.addEventListener(d,Z)),e.addEventListener(h,lt)),e.createdCallback&&Y&&(e.created=!0,e.createdCallback(),e.created=!1)}function vt(){for(var e,t=0,n=I.length;t<n;t++)e=I[t],S.contains(e)||(n--,I.splice(t--,1),gt(e,u))}function mt(e){throw new Error("A "+e+" type is already registered")}function gt(e,t){var n,r=at(e);-1<r&&(rt(e,w[r]),r=0,t===o&&!e[o]?(e[u]=!1,e[o]=!0,r=1,j&&x.call(I,e)<0&&I.push(e)):t===u&&!e[u]&&(e[o]=!1,e[u]=!0,r=1),r&&(n=e[t+"Callback"])&&n.call(e))}if(i in n)return;var s="__"+i+(Math.random()*1e5>>0),o="attached",u="detached",a="extends",f="ADDITION",l="MODIFICATION",c="REMOVAL",h="DOMAttrModified",p="DOMContentLoaded",d="DOMSubtreeModified",v="<",m="=",g=/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,y=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],b=[],w=[],E="",S=n.documentElement,x=b.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},T=r.prototype,N=T.hasOwnProperty,C=T.isPrototypeOf,k=r.defineProperty,L=r.getOwnPropertyDescriptor,A=r.getOwnPropertyNames,O=r.getPrototypeOf,M=r.setPrototypeOf,_=!!r.__proto__,D=r.create||function yt(e){return e?(yt.prototype=e,new yt):this},P=M||(_?function(e,t){return e.__proto__=t,e}:A&&L?function(){function e(e,t){for(var n,r=A(t),i=0,s=r.length;i<s;i++)n=r[i],N.call(e,n)||k(e,n,L(t,n))}return function(t,n){do e(t,n);while((n=O(n))&&!C.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),H=t.MutationObserver||t.WebKitMutationObserver,B=(t.HTMLElement||t.Element||t.Node).prototype,j=!C.call(B,S),F=j?function(e){return e.nodeType===1}:function(e){return C.call(B,e)},I=j&&[],q=B.cloneNode,R=B.getAttribute,U=B.setAttribute,z=B.removeAttribute,W=n.createElement,X=H&&{attributes:!0,characterData:!0,attributeOldValue:!0},V=H||function(e){Q=!1,S.removeEventListener(h,V)},$,J=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,10)},K=!1,Q=!0,G=!0,Y=!0,Z,et,tt,nt,rt,it;M||_?(rt=function(e,t){C.call(t,e)||dt(e,t)},it=dt):(rt=function(e,t){e[s]||(e[s]=r(!0),dt(e,t))},it=rt),j?(Q=!1,function(){var t=L(B,"addEventListener"),n=t.value,r=function(e){var t=new CustomEvent(h,{bubbles:!0});t.attrName=e,t.prevValue=R.call(this,e),t.newValue=null,t[c]=t.attrChange=2,z.call(this,e),this.dispatchEvent(t)},i=function(t,n){var r=this.hasAttribute(t),i=r&&R.call(this,t);e=new CustomEvent(h,{bubbles:!0}),U.call(this,t,n),e.attrName=t,e.prevValue=r?i:null,e.newValue=n,r?e[l]=e.attrChange=1:e[f]=e.attrChange=0,this.dispatchEvent(e)},o=function(e){var t=e.currentTarget,n=t[s],r=e.propertyName,i;n.hasOwnProperty(r)&&(n=n[r],i=new CustomEvent(h,{bubbles:!0}),i.attrName=n.name,i.prevValue=n.value||null,i.newValue=n.value=t[r]||null,i.prevValue==null?i[f]=i.attrChange=0:i[l]=i.attrChange=1,t.dispatchEvent(i))};t.value=function(e,t,u){e===h&&this.attributeChangedCallback&&this.setAttribute!==i&&(this[s]={className:{name:"class",value:this.className}},this.setAttribute=i,this.removeAttribute=r,n.call(this,"propertychange",o)),n.call(this,e,t,u)},k(B,"addEventListener",t)}()):H||(S.addEventListener(h,V),S.setAttribute(s,1),S.removeAttribute(s),Q&&(Z=function(e){var t=this,n,r,i;if(t===e.target){n=t[s],t[s]=r=tt(t);for(i in r){if(!(i in n))return et(0,t,i,n[i],r[i],f);if(r[i]!==n[i])return et(1,t,i,n[i],r[i],l)}for(i in n)if(!(i in r))return et(2,t,i,n[i],r[i],c)}},et=function(e,t,n,r,i,s){var o={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:i};o[s]=e,lt(o)},tt=function(e){for(var t,n,r={},i=e.attributes,s=0,o=i.length;s<o;s++)t=i[s],n=t.name,n!=="setAttribute"&&(r[n]=t.value);return r})),n[i]=function(t,r){c=t.toUpperCase(),K||(K=!0,H?(nt=function(e,t){function n(e,t){for(var n=0,r=e.length;n<r;t(e[n++]));}return new H(function(r){for(var i,s,o,u=0,a=r.length;u<a;u++)i=r[u],i.type==="childList"?(n(i.addedNodes,e),n(i.removedNodes,t)):(s=i.target,Y&&s.attributeChangedCallback&&i.attributeName!=="style"&&(o=R.call(s,i.attributeName),o!==i.oldValue&&s.attributeChangedCallback(i.attributeName,i.oldValue,o)))})}(ut(o),ut(u)),nt.observe(n,{childList:!0,subtree:!0})):($=[],J(function d(){while($.length)$.shift().call(null,$.shift());J(d)}),n.addEventListener("DOMNodeInserted",ct(o)),n.addEventListener("DOMNodeRemoved",ct(u))),n.addEventListener(p,ht),n.addEventListener("readystatechange",ht),n.createElement=function(e,t){var r=W.apply(n,arguments),i=""+e,s=x.call(b,(t?m:v)+(t||i).toUpperCase()),o=-1<s;return t&&(r.setAttribute("is",t=t.toLowerCase()),o&&(o=ft(i.toUpperCase(),t))),Y=!n.createElement.innerHTMLHelper,o&&it(r,w[s]),r},B.cloneNode=function(e){var t=q.call(this,!!e),n=at(t);return-1<n&&it(t,w[n]),e&&ot(t.querySelectorAll(E)),t}),-2<x.call(b,m+c)+x.call(b,v+c)&&mt(t);if(!g.test(c)||-1<x.call(y,c))throw new Error("The type "+t+" is invalid");var i=function(){return f?n.createElement(l,c):n.createElement(l)},s=r||T,f=N.call(s,a),l=f?r[a].toUpperCase():c,c,h;return f&&-1<x.call(b,v+l)&&mt(l),h=b.push((f?m:v)+c)-1,E=E.concat(E.length?",":"",f?l+'[is="'+t.toLowerCase()+'"]':l),i.prototype=w[h]=N.call(s,"prototype")?s.prototype:D(B),st(n.querySelectorAll(E),o),i}})(window,document,Object,"registerElement");
  2184. },{}],13:[function(_dereq_,module,exports){
  2185. module.exports = function(dtype) {
  2186. switch (dtype) {
  2187. case 'int8':
  2188. return Int8Array
  2189. case 'int16':
  2190. return Int16Array
  2191. case 'int32':
  2192. return Int32Array
  2193. case 'uint8':
  2194. return Uint8Array
  2195. case 'uint16':
  2196. return Uint16Array
  2197. case 'uint32':
  2198. return Uint32Array
  2199. case 'float32':
  2200. return Float32Array
  2201. case 'float64':
  2202. return Float64Array
  2203. case 'array':
  2204. return Array
  2205. case 'uint8_clamped':
  2206. return Uint8ClampedArray
  2207. }
  2208. }
  2209. },{}],14:[function(_dereq_,module,exports){
  2210. 'use strict';
  2211. /* globals
  2212. Set,
  2213. Map,
  2214. WeakSet,
  2215. WeakMap,
  2216. Promise,
  2217. Symbol,
  2218. Proxy,
  2219. Atomics,
  2220. SharedArrayBuffer,
  2221. ArrayBuffer,
  2222. DataView,
  2223. Uint8Array,
  2224. Float32Array,
  2225. Float64Array,
  2226. Int8Array,
  2227. Int16Array,
  2228. Int32Array,
  2229. Uint8ClampedArray,
  2230. Uint16Array,
  2231. Uint32Array,
  2232. */
  2233. var undefined; // eslint-disable-line no-shadow-restricted-names
  2234. var ThrowTypeError = Object.getOwnPropertyDescriptor
  2235. ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
  2236. : function () { throw new TypeError(); };
  2237. var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
  2238. var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
  2239. var generator; // = function * () {};
  2240. var generatorFunction = generator ? getProto(generator) : undefined;
  2241. var asyncFn; // async function() {};
  2242. var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
  2243. var asyncGen; // async function * () {};
  2244. var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
  2245. var asyncGenIterator = asyncGen ? asyncGen() : undefined;
  2246. var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
  2247. var INTRINSICS = {
  2248. '$ %Array%': Array,
  2249. '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
  2250. '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
  2251. '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
  2252. '$ %ArrayPrototype%': Array.prototype,
  2253. '$ %ArrayProto_entries%': Array.prototype.entries,
  2254. '$ %ArrayProto_forEach%': Array.prototype.forEach,
  2255. '$ %ArrayProto_keys%': Array.prototype.keys,
  2256. '$ %ArrayProto_values%': Array.prototype.values,
  2257. '$ %AsyncFromSyncIteratorPrototype%': undefined,
  2258. '$ %AsyncFunction%': asyncFunction,
  2259. '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
  2260. '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
  2261. '$ %AsyncGeneratorFunction%': asyncGenFunction,
  2262. '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
  2263. '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
  2264. '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
  2265. '$ %Boolean%': Boolean,
  2266. '$ %BooleanPrototype%': Boolean.prototype,
  2267. '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
  2268. '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
  2269. '$ %Date%': Date,
  2270. '$ %DatePrototype%': Date.prototype,
  2271. '$ %decodeURI%': decodeURI,
  2272. '$ %decodeURIComponent%': decodeURIComponent,
  2273. '$ %encodeURI%': encodeURI,
  2274. '$ %encodeURIComponent%': encodeURIComponent,
  2275. '$ %Error%': Error,
  2276. '$ %ErrorPrototype%': Error.prototype,
  2277. '$ %eval%': eval, // eslint-disable-line no-eval
  2278. '$ %EvalError%': EvalError,
  2279. '$ %EvalErrorPrototype%': EvalError.prototype,
  2280. '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
  2281. '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
  2282. '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
  2283. '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
  2284. '$ %Function%': Function,
  2285. '$ %FunctionPrototype%': Function.prototype,
  2286. '$ %Generator%': generator ? getProto(generator()) : undefined,
  2287. '$ %GeneratorFunction%': generatorFunction,
  2288. '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
  2289. '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
  2290. '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
  2291. '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
  2292. '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
  2293. '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
  2294. '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
  2295. '$ %isFinite%': isFinite,
  2296. '$ %isNaN%': isNaN,
  2297. '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
  2298. '$ %JSON%': JSON,
  2299. '$ %JSONParse%': JSON.parse,
  2300. '$ %Map%': typeof Map === 'undefined' ? undefined : Map,
  2301. '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
  2302. '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
  2303. '$ %Math%': Math,
  2304. '$ %Number%': Number,
  2305. '$ %NumberPrototype%': Number.prototype,
  2306. '$ %Object%': Object,
  2307. '$ %ObjectPrototype%': Object.prototype,
  2308. '$ %ObjProto_toString%': Object.prototype.toString,
  2309. '$ %ObjProto_valueOf%': Object.prototype.valueOf,
  2310. '$ %parseFloat%': parseFloat,
  2311. '$ %parseInt%': parseInt,
  2312. '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise,
  2313. '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
  2314. '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
  2315. '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
  2316. '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
  2317. '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
  2318. '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
  2319. '$ %RangeError%': RangeError,
  2320. '$ %RangeErrorPrototype%': RangeError.prototype,
  2321. '$ %ReferenceError%': ReferenceError,
  2322. '$ %ReferenceErrorPrototype%': ReferenceError.prototype,
  2323. '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
  2324. '$ %RegExp%': RegExp,
  2325. '$ %RegExpPrototype%': RegExp.prototype,
  2326. '$ %Set%': typeof Set === 'undefined' ? undefined : Set,
  2327. '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
  2328. '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
  2329. '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
  2330. '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
  2331. '$ %String%': String,
  2332. '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
  2333. '$ %StringPrototype%': String.prototype,
  2334. '$ %Symbol%': hasSymbols ? Symbol : undefined,
  2335. '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
  2336. '$ %SyntaxError%': SyntaxError,
  2337. '$ %SyntaxErrorPrototype%': SyntaxError.prototype,
  2338. '$ %ThrowTypeError%': ThrowTypeError,
  2339. '$ %TypedArray%': TypedArray,
  2340. '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
  2341. '$ %TypeError%': TypeError,
  2342. '$ %TypeErrorPrototype%': TypeError.prototype,
  2343. '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
  2344. '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
  2345. '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
  2346. '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
  2347. '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
  2348. '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
  2349. '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
  2350. '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
  2351. '$ %URIError%': URIError,
  2352. '$ %URIErrorPrototype%': URIError.prototype,
  2353. '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
  2354. '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
  2355. '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
  2356. '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
  2357. };
  2358. module.exports = function GetIntrinsic(name, allowMissing) {
  2359. if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
  2360. throw new TypeError('"allowMissing" argument must be a boolean');
  2361. }
  2362. var key = '$ ' + name;
  2363. if (!(key in INTRINSICS)) {
  2364. throw new SyntaxError('intrinsic ' + name + ' does not exist!');
  2365. }
  2366. // istanbul ignore if // hopefully this is impossible to test :-)
  2367. if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
  2368. throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
  2369. }
  2370. return INTRINSICS[key];
  2371. };
  2372. },{}],15:[function(_dereq_,module,exports){
  2373. 'use strict';
  2374. var GetIntrinsic = _dereq_('./GetIntrinsic');
  2375. var $Object = GetIntrinsic('%Object%');
  2376. var $TypeError = GetIntrinsic('%TypeError%');
  2377. var $String = GetIntrinsic('%String%');
  2378. var assertRecord = _dereq_('./helpers/assertRecord');
  2379. var $isNaN = _dereq_('./helpers/isNaN');
  2380. var $isFinite = _dereq_('./helpers/isFinite');
  2381. var sign = _dereq_('./helpers/sign');
  2382. var mod = _dereq_('./helpers/mod');
  2383. var IsCallable = _dereq_('is-callable');
  2384. var toPrimitive = _dereq_('es-to-primitive/es5');
  2385. var has = _dereq_('has');
  2386. // https://es5.github.io/#x9
  2387. var ES5 = {
  2388. ToPrimitive: toPrimitive,
  2389. ToBoolean: function ToBoolean(value) {
  2390. return !!value;
  2391. },
  2392. ToNumber: function ToNumber(value) {
  2393. return +value; // eslint-disable-line no-implicit-coercion
  2394. },
  2395. ToInteger: function ToInteger(value) {
  2396. var number = this.ToNumber(value);
  2397. if ($isNaN(number)) { return 0; }
  2398. if (number === 0 || !$isFinite(number)) { return number; }
  2399. return sign(number) * Math.floor(Math.abs(number));
  2400. },
  2401. ToInt32: function ToInt32(x) {
  2402. return this.ToNumber(x) >> 0;
  2403. },
  2404. ToUint32: function ToUint32(x) {
  2405. return this.ToNumber(x) >>> 0;
  2406. },
  2407. ToUint16: function ToUint16(value) {
  2408. var number = this.ToNumber(value);
  2409. if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
  2410. var posInt = sign(number) * Math.floor(Math.abs(number));
  2411. return mod(posInt, 0x10000);
  2412. },
  2413. ToString: function ToString(value) {
  2414. return $String(value);
  2415. },
  2416. ToObject: function ToObject(value) {
  2417. this.CheckObjectCoercible(value);
  2418. return $Object(value);
  2419. },
  2420. CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
  2421. /* jshint eqnull:true */
  2422. if (value == null) {
  2423. throw new $TypeError(optMessage || 'Cannot call method on ' + value);
  2424. }
  2425. return value;
  2426. },
  2427. IsCallable: IsCallable,
  2428. SameValue: function SameValue(x, y) {
  2429. if (x === y) { // 0 === -0, but they are not identical.
  2430. if (x === 0) { return 1 / x === 1 / y; }
  2431. return true;
  2432. }
  2433. return $isNaN(x) && $isNaN(y);
  2434. },
  2435. // https://www.ecma-international.org/ecma-262/5.1/#sec-8
  2436. Type: function Type(x) {
  2437. if (x === null) {
  2438. return 'Null';
  2439. }
  2440. if (typeof x === 'undefined') {
  2441. return 'Undefined';
  2442. }
  2443. if (typeof x === 'function' || typeof x === 'object') {
  2444. return 'Object';
  2445. }
  2446. if (typeof x === 'number') {
  2447. return 'Number';
  2448. }
  2449. if (typeof x === 'boolean') {
  2450. return 'Boolean';
  2451. }
  2452. if (typeof x === 'string') {
  2453. return 'String';
  2454. }
  2455. },
  2456. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2457. IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
  2458. if (this.Type(Desc) !== 'Object') {
  2459. return false;
  2460. }
  2461. var allowed = {
  2462. '[[Configurable]]': true,
  2463. '[[Enumerable]]': true,
  2464. '[[Get]]': true,
  2465. '[[Set]]': true,
  2466. '[[Value]]': true,
  2467. '[[Writable]]': true
  2468. };
  2469. for (var key in Desc) { // eslint-disable-line
  2470. if (has(Desc, key) && !allowed[key]) {
  2471. return false;
  2472. }
  2473. }
  2474. var isData = has(Desc, '[[Value]]');
  2475. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2476. if (isData && IsAccessor) {
  2477. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2478. }
  2479. return true;
  2480. },
  2481. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
  2482. IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
  2483. if (typeof Desc === 'undefined') {
  2484. return false;
  2485. }
  2486. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2487. if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
  2488. return false;
  2489. }
  2490. return true;
  2491. },
  2492. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
  2493. IsDataDescriptor: function IsDataDescriptor(Desc) {
  2494. if (typeof Desc === 'undefined') {
  2495. return false;
  2496. }
  2497. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2498. if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
  2499. return false;
  2500. }
  2501. return true;
  2502. },
  2503. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
  2504. IsGenericDescriptor: function IsGenericDescriptor(Desc) {
  2505. if (typeof Desc === 'undefined') {
  2506. return false;
  2507. }
  2508. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2509. if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
  2510. return true;
  2511. }
  2512. return false;
  2513. },
  2514. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
  2515. FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
  2516. if (typeof Desc === 'undefined') {
  2517. return Desc;
  2518. }
  2519. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2520. if (this.IsDataDescriptor(Desc)) {
  2521. return {
  2522. value: Desc['[[Value]]'],
  2523. writable: !!Desc['[[Writable]]'],
  2524. enumerable: !!Desc['[[Enumerable]]'],
  2525. configurable: !!Desc['[[Configurable]]']
  2526. };
  2527. } else if (this.IsAccessorDescriptor(Desc)) {
  2528. return {
  2529. get: Desc['[[Get]]'],
  2530. set: Desc['[[Set]]'],
  2531. enumerable: !!Desc['[[Enumerable]]'],
  2532. configurable: !!Desc['[[Configurable]]']
  2533. };
  2534. } else {
  2535. throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
  2536. }
  2537. },
  2538. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
  2539. ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
  2540. if (this.Type(Obj) !== 'Object') {
  2541. throw new $TypeError('ToPropertyDescriptor requires an object');
  2542. }
  2543. var desc = {};
  2544. if (has(Obj, 'enumerable')) {
  2545. desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
  2546. }
  2547. if (has(Obj, 'configurable')) {
  2548. desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
  2549. }
  2550. if (has(Obj, 'value')) {
  2551. desc['[[Value]]'] = Obj.value;
  2552. }
  2553. if (has(Obj, 'writable')) {
  2554. desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
  2555. }
  2556. if (has(Obj, 'get')) {
  2557. var getter = Obj.get;
  2558. if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
  2559. throw new TypeError('getter must be a function');
  2560. }
  2561. desc['[[Get]]'] = getter;
  2562. }
  2563. if (has(Obj, 'set')) {
  2564. var setter = Obj.set;
  2565. if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
  2566. throw new $TypeError('setter must be a function');
  2567. }
  2568. desc['[[Set]]'] = setter;
  2569. }
  2570. if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
  2571. throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
  2572. }
  2573. return desc;
  2574. }
  2575. };
  2576. module.exports = ES5;
  2577. },{"./GetIntrinsic":14,"./helpers/assertRecord":16,"./helpers/isFinite":17,"./helpers/isNaN":18,"./helpers/mod":19,"./helpers/sign":20,"es-to-primitive/es5":21,"has":28,"is-callable":32}],16:[function(_dereq_,module,exports){
  2578. 'use strict';
  2579. var GetIntrinsic = _dereq_('../GetIntrinsic');
  2580. var $TypeError = GetIntrinsic('%TypeError%');
  2581. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  2582. var has = _dereq_('has');
  2583. var predicates = {
  2584. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2585. 'Property Descriptor': function isPropertyDescriptor(ES, Desc) {
  2586. if (ES.Type(Desc) !== 'Object') {
  2587. return false;
  2588. }
  2589. var allowed = {
  2590. '[[Configurable]]': true,
  2591. '[[Enumerable]]': true,
  2592. '[[Get]]': true,
  2593. '[[Set]]': true,
  2594. '[[Value]]': true,
  2595. '[[Writable]]': true
  2596. };
  2597. for (var key in Desc) { // eslint-disable-line
  2598. if (has(Desc, key) && !allowed[key]) {
  2599. return false;
  2600. }
  2601. }
  2602. var isData = has(Desc, '[[Value]]');
  2603. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2604. if (isData && IsAccessor) {
  2605. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2606. }
  2607. return true;
  2608. }
  2609. };
  2610. module.exports = function assertRecord(ES, recordType, argumentName, value) {
  2611. var predicate = predicates[recordType];
  2612. if (typeof predicate !== 'function') {
  2613. throw new $SyntaxError('unknown record type: ' + recordType);
  2614. }
  2615. if (!predicate(ES, value)) {
  2616. throw new $TypeError(argumentName + ' must be a ' + recordType);
  2617. }
  2618. console.log(predicate(ES, value), value);
  2619. };
  2620. },{"../GetIntrinsic":14,"has":28}],17:[function(_dereq_,module,exports){
  2621. var $isNaN = Number.isNaN || function (a) { return a !== a; };
  2622. module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
  2623. },{}],18:[function(_dereq_,module,exports){
  2624. module.exports = Number.isNaN || function isNaN(a) {
  2625. return a !== a;
  2626. };
  2627. },{}],19:[function(_dereq_,module,exports){
  2628. module.exports = function mod(number, modulo) {
  2629. var remain = number % modulo;
  2630. return Math.floor(remain >= 0 ? remain : remain + modulo);
  2631. };
  2632. },{}],20:[function(_dereq_,module,exports){
  2633. module.exports = function sign(number) {
  2634. return number >= 0 ? 1 : -1;
  2635. };
  2636. },{}],21:[function(_dereq_,module,exports){
  2637. 'use strict';
  2638. var toStr = Object.prototype.toString;
  2639. var isPrimitive = _dereq_('./helpers/isPrimitive');
  2640. var isCallable = _dereq_('is-callable');
  2641. // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
  2642. var ES5internalSlots = {
  2643. '[[DefaultValue]]': function (O) {
  2644. var actualHint;
  2645. if (arguments.length > 1) {
  2646. actualHint = arguments[1];
  2647. } else {
  2648. actualHint = toStr.call(O) === '[object Date]' ? String : Number;
  2649. }
  2650. if (actualHint === String || actualHint === Number) {
  2651. var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  2652. var value, i;
  2653. for (i = 0; i < methods.length; ++i) {
  2654. if (isCallable(O[methods[i]])) {
  2655. value = O[methods[i]]();
  2656. if (isPrimitive(value)) {
  2657. return value;
  2658. }
  2659. }
  2660. }
  2661. throw new TypeError('No default value');
  2662. }
  2663. throw new TypeError('invalid [[DefaultValue]] hint supplied');
  2664. }
  2665. };
  2666. // http://ecma-international.org/ecma-262/5.1/#sec-9.1
  2667. module.exports = function ToPrimitive(input) {
  2668. if (isPrimitive(input)) {
  2669. return input;
  2670. }
  2671. if (arguments.length > 1) {
  2672. return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
  2673. }
  2674. return ES5internalSlots['[[DefaultValue]]'](input);
  2675. };
  2676. },{"./helpers/isPrimitive":22,"is-callable":32}],22:[function(_dereq_,module,exports){
  2677. module.exports = function isPrimitive(value) {
  2678. return value === null || (typeof value !== 'function' && typeof value !== 'object');
  2679. };
  2680. },{}],23:[function(_dereq_,module,exports){
  2681. /*eslint new-cap:0*/
  2682. var dtype = _dereq_('dtype')
  2683. module.exports = flattenVertexData
  2684. function flattenVertexData (data, output, offset) {
  2685. if (!data) throw new TypeError('must specify data as first parameter')
  2686. offset = +(offset || 0) | 0
  2687. if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) {
  2688. var dim = data[0].length
  2689. var length = data.length * dim
  2690. var i, j, k, l
  2691. // no output specified, create a new typed array
  2692. if (!output || typeof output === 'string') {
  2693. output = new (dtype(output || 'float32'))(length + offset)
  2694. }
  2695. var dstLength = output.length - offset
  2696. if (length !== dstLength) {
  2697. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2698. ' does not match destination length ' + dstLength)
  2699. }
  2700. for (i = 0, k = offset; i < data.length; i++) {
  2701. for (j = 0; j < dim; j++) {
  2702. output[k++] = data[i][j] === null ? NaN : data[i][j]
  2703. }
  2704. }
  2705. } else {
  2706. if (!output || typeof output === 'string') {
  2707. // no output, create a new one
  2708. var Ctor = dtype(output || 'float32')
  2709. // handle arrays separately due to possible nulls
  2710. if (Array.isArray(data) || output === 'array') {
  2711. output = new Ctor(data.length + offset)
  2712. for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
  2713. output[k] = data[i] === null ? NaN : data[i]
  2714. }
  2715. } else {
  2716. if (offset === 0) {
  2717. output = new Ctor(data)
  2718. } else {
  2719. output = new Ctor(data.length + offset)
  2720. output.set(data, offset)
  2721. }
  2722. }
  2723. } else {
  2724. // store output in existing array
  2725. output.set(data, offset)
  2726. }
  2727. }
  2728. return output
  2729. }
  2730. },{"dtype":13}],24:[function(_dereq_,module,exports){
  2731. 'use strict';
  2732. var isCallable = _dereq_('is-callable');
  2733. var toStr = Object.prototype.toString;
  2734. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2735. var forEachArray = function forEachArray(array, iterator, receiver) {
  2736. for (var i = 0, len = array.length; i < len; i++) {
  2737. if (hasOwnProperty.call(array, i)) {
  2738. if (receiver == null) {
  2739. iterator(array[i], i, array);
  2740. } else {
  2741. iterator.call(receiver, array[i], i, array);
  2742. }
  2743. }
  2744. }
  2745. };
  2746. var forEachString = function forEachString(string, iterator, receiver) {
  2747. for (var i = 0, len = string.length; i < len; i++) {
  2748. // no such thing as a sparse string.
  2749. if (receiver == null) {
  2750. iterator(string.charAt(i), i, string);
  2751. } else {
  2752. iterator.call(receiver, string.charAt(i), i, string);
  2753. }
  2754. }
  2755. };
  2756. var forEachObject = function forEachObject(object, iterator, receiver) {
  2757. for (var k in object) {
  2758. if (hasOwnProperty.call(object, k)) {
  2759. if (receiver == null) {
  2760. iterator(object[k], k, object);
  2761. } else {
  2762. iterator.call(receiver, object[k], k, object);
  2763. }
  2764. }
  2765. }
  2766. };
  2767. var forEach = function forEach(list, iterator, thisArg) {
  2768. if (!isCallable(iterator)) {
  2769. throw new TypeError('iterator must be a function');
  2770. }
  2771. var receiver;
  2772. if (arguments.length >= 3) {
  2773. receiver = thisArg;
  2774. }
  2775. if (toStr.call(list) === '[object Array]') {
  2776. forEachArray(list, iterator, receiver);
  2777. } else if (typeof list === 'string') {
  2778. forEachString(list, iterator, receiver);
  2779. } else {
  2780. forEachObject(list, iterator, receiver);
  2781. }
  2782. };
  2783. module.exports = forEach;
  2784. },{"is-callable":32}],25:[function(_dereq_,module,exports){
  2785. 'use strict';
  2786. /* eslint no-invalid-this: 1 */
  2787. var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
  2788. var slice = Array.prototype.slice;
  2789. var toStr = Object.prototype.toString;
  2790. var funcType = '[object Function]';
  2791. module.exports = function bind(that) {
  2792. var target = this;
  2793. if (typeof target !== 'function' || toStr.call(target) !== funcType) {
  2794. throw new TypeError(ERROR_MESSAGE + target);
  2795. }
  2796. var args = slice.call(arguments, 1);
  2797. var bound;
  2798. var binder = function () {
  2799. if (this instanceof bound) {
  2800. var result = target.apply(
  2801. this,
  2802. args.concat(slice.call(arguments))
  2803. );
  2804. if (Object(result) === result) {
  2805. return result;
  2806. }
  2807. return this;
  2808. } else {
  2809. return target.apply(
  2810. that,
  2811. args.concat(slice.call(arguments))
  2812. );
  2813. }
  2814. };
  2815. var boundLength = Math.max(0, target.length - args.length);
  2816. var boundArgs = [];
  2817. for (var i = 0; i < boundLength; i++) {
  2818. boundArgs.push('$' + i);
  2819. }
  2820. bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
  2821. if (target.prototype) {
  2822. var Empty = function Empty() {};
  2823. Empty.prototype = target.prototype;
  2824. bound.prototype = new Empty();
  2825. Empty.prototype = null;
  2826. }
  2827. return bound;
  2828. };
  2829. },{}],26:[function(_dereq_,module,exports){
  2830. 'use strict';
  2831. var implementation = _dereq_('./implementation');
  2832. module.exports = Function.prototype.bind || implementation;
  2833. },{"./implementation":25}],27:[function(_dereq_,module,exports){
  2834. (function (global){
  2835. var win;
  2836. if (typeof window !== "undefined") {
  2837. win = window;
  2838. } else if (typeof global !== "undefined") {
  2839. win = global;
  2840. } else if (typeof self !== "undefined"){
  2841. win = self;
  2842. } else {
  2843. win = {};
  2844. }
  2845. module.exports = win;
  2846. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2847. },{}],28:[function(_dereq_,module,exports){
  2848. 'use strict';
  2849. var bind = _dereq_('function-bind');
  2850. module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
  2851. },{"function-bind":26}],29:[function(_dereq_,module,exports){
  2852. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2853. var e, m
  2854. var eLen = (nBytes * 8) - mLen - 1
  2855. var eMax = (1 << eLen) - 1
  2856. var eBias = eMax >> 1
  2857. var nBits = -7
  2858. var i = isLE ? (nBytes - 1) : 0
  2859. var d = isLE ? -1 : 1
  2860. var s = buffer[offset + i]
  2861. i += d
  2862. e = s & ((1 << (-nBits)) - 1)
  2863. s >>= (-nBits)
  2864. nBits += eLen
  2865. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2866. m = e & ((1 << (-nBits)) - 1)
  2867. e >>= (-nBits)
  2868. nBits += mLen
  2869. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2870. if (e === 0) {
  2871. e = 1 - eBias
  2872. } else if (e === eMax) {
  2873. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2874. } else {
  2875. m = m + Math.pow(2, mLen)
  2876. e = e - eBias
  2877. }
  2878. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2879. }
  2880. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2881. var e, m, c
  2882. var eLen = (nBytes * 8) - mLen - 1
  2883. var eMax = (1 << eLen) - 1
  2884. var eBias = eMax >> 1
  2885. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2886. var i = isLE ? 0 : (nBytes - 1)
  2887. var d = isLE ? 1 : -1
  2888. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2889. value = Math.abs(value)
  2890. if (isNaN(value) || value === Infinity) {
  2891. m = isNaN(value) ? 1 : 0
  2892. e = eMax
  2893. } else {
  2894. e = Math.floor(Math.log(value) / Math.LN2)
  2895. if (value * (c = Math.pow(2, -e)) < 1) {
  2896. e--
  2897. c *= 2
  2898. }
  2899. if (e + eBias >= 1) {
  2900. value += rt / c
  2901. } else {
  2902. value += rt * Math.pow(2, 1 - eBias)
  2903. }
  2904. if (value * c >= 2) {
  2905. e++
  2906. c /= 2
  2907. }
  2908. if (e + eBias >= eMax) {
  2909. m = 0
  2910. e = eMax
  2911. } else if (e + eBias >= 1) {
  2912. m = ((value * c) - 1) * Math.pow(2, mLen)
  2913. e = e + eBias
  2914. } else {
  2915. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2916. e = 0
  2917. }
  2918. }
  2919. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2920. e = (e << mLen) | m
  2921. eLen += mLen
  2922. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2923. buffer[offset + i - d] |= s * 128
  2924. }
  2925. },{}],30:[function(_dereq_,module,exports){
  2926. if (typeof Object.create === 'function') {
  2927. // implementation from standard node.js 'util' module
  2928. module.exports = function inherits(ctor, superCtor) {
  2929. if (superCtor) {
  2930. ctor.super_ = superCtor
  2931. ctor.prototype = Object.create(superCtor.prototype, {
  2932. constructor: {
  2933. value: ctor,
  2934. enumerable: false,
  2935. writable: true,
  2936. configurable: true
  2937. }
  2938. })
  2939. }
  2940. };
  2941. } else {
  2942. // old school shim for old browsers
  2943. module.exports = function inherits(ctor, superCtor) {
  2944. if (superCtor) {
  2945. ctor.super_ = superCtor
  2946. var TempCtor = function () {}
  2947. TempCtor.prototype = superCtor.prototype
  2948. ctor.prototype = new TempCtor()
  2949. ctor.prototype.constructor = ctor
  2950. }
  2951. }
  2952. }
  2953. },{}],31:[function(_dereq_,module,exports){
  2954. /*!
  2955. * Determine if an object is a Buffer
  2956. *
  2957. * @author Feross Aboukhadijeh <https://feross.org>
  2958. * @license MIT
  2959. */
  2960. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2961. // Object.prototype.constructor. Remove this eventually
  2962. module.exports = function (obj) {
  2963. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2964. }
  2965. function isBuffer (obj) {
  2966. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2967. }
  2968. // For Node v0.10 support. Remove this eventually.
  2969. function isSlowBuffer (obj) {
  2970. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2971. }
  2972. },{}],32:[function(_dereq_,module,exports){
  2973. 'use strict';
  2974. var fnToStr = Function.prototype.toString;
  2975. var constructorRegex = /^\s*class\b/;
  2976. var isES6ClassFn = function isES6ClassFunction(value) {
  2977. try {
  2978. var fnStr = fnToStr.call(value);
  2979. return constructorRegex.test(fnStr);
  2980. } catch (e) {
  2981. return false; // not a function
  2982. }
  2983. };
  2984. var tryFunctionObject = function tryFunctionToStr(value) {
  2985. try {
  2986. if (isES6ClassFn(value)) { return false; }
  2987. fnToStr.call(value);
  2988. return true;
  2989. } catch (e) {
  2990. return false;
  2991. }
  2992. };
  2993. var toStr = Object.prototype.toString;
  2994. var fnClass = '[object Function]';
  2995. var genClass = '[object GeneratorFunction]';
  2996. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  2997. module.exports = function isCallable(value) {
  2998. if (!value) { return false; }
  2999. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  3000. if (typeof value === 'function' && !value.prototype) { return true; }
  3001. if (hasToStringTag) { return tryFunctionObject(value); }
  3002. if (isES6ClassFn(value)) { return false; }
  3003. var strClass = toStr.call(value);
  3004. return strClass === fnClass || strClass === genClass;
  3005. };
  3006. },{}],33:[function(_dereq_,module,exports){
  3007. module.exports = isFunction
  3008. var toString = Object.prototype.toString
  3009. function isFunction (fn) {
  3010. var string = toString.call(fn)
  3011. return string === '[object Function]' ||
  3012. (typeof fn === 'function' && string !== '[object RegExp]') ||
  3013. (typeof window !== 'undefined' &&
  3014. // IE8 and below
  3015. (fn === window.setTimeout ||
  3016. fn === window.alert ||
  3017. fn === window.confirm ||
  3018. fn === window.prompt))
  3019. };
  3020. },{}],34:[function(_dereq_,module,exports){
  3021. 'use strict';
  3022. module.exports = function (x) {
  3023. var type = typeof x;
  3024. return x !== null && (type === 'object' || type === 'function');
  3025. };
  3026. },{}],35:[function(_dereq_,module,exports){
  3027. var toString = {}.toString;
  3028. module.exports = Array.isArray || function (arr) {
  3029. return toString.call(arr) == '[object Array]';
  3030. };
  3031. },{}],36:[function(_dereq_,module,exports){
  3032. var wordWrap = _dereq_('word-wrapper')
  3033. var xtend = _dereq_('xtend')
  3034. var number = _dereq_('as-number')
  3035. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  3036. var M_WIDTHS = ['m', 'w']
  3037. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  3038. var TAB_ID = '\t'.charCodeAt(0)
  3039. var SPACE_ID = ' '.charCodeAt(0)
  3040. var ALIGN_LEFT = 0,
  3041. ALIGN_CENTER = 1,
  3042. ALIGN_RIGHT = 2
  3043. module.exports = function createLayout(opt) {
  3044. return new TextLayout(opt)
  3045. }
  3046. function TextLayout(opt) {
  3047. this.glyphs = []
  3048. this._measure = this.computeMetrics.bind(this)
  3049. this.update(opt)
  3050. }
  3051. TextLayout.prototype.update = function(opt) {
  3052. opt = xtend({
  3053. measure: this._measure
  3054. }, opt)
  3055. this._opt = opt
  3056. this._opt.tabSize = number(this._opt.tabSize, 4)
  3057. if (!opt.font)
  3058. throw new Error('must provide a valid bitmap font')
  3059. var glyphs = this.glyphs
  3060. var text = opt.text||''
  3061. var font = opt.font
  3062. this._setupSpaceGlyphs(font)
  3063. var lines = wordWrap.lines(text, opt)
  3064. var minWidth = opt.width || 0
  3065. //clear glyphs
  3066. glyphs.length = 0
  3067. //get max line width
  3068. var maxLineWidth = lines.reduce(function(prev, line) {
  3069. return Math.max(prev, line.width, minWidth)
  3070. }, 0)
  3071. //the pen position
  3072. var x = 0
  3073. var y = 0
  3074. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  3075. var baseline = font.common.base
  3076. var descender = lineHeight-baseline
  3077. var letterSpacing = opt.letterSpacing || 0
  3078. var height = lineHeight * lines.length - descender
  3079. var align = getAlignType(this._opt.align)
  3080. //draw text along baseline
  3081. y -= height
  3082. //the metrics for this text layout
  3083. this._width = maxLineWidth
  3084. this._height = height
  3085. this._descender = lineHeight - baseline
  3086. this._baseline = baseline
  3087. this._xHeight = getXHeight(font)
  3088. this._capHeight = getCapHeight(font)
  3089. this._lineHeight = lineHeight
  3090. this._ascender = lineHeight - descender - this._xHeight
  3091. //layout each glyph
  3092. var self = this
  3093. lines.forEach(function(line, lineIndex) {
  3094. var start = line.start
  3095. var end = line.end
  3096. var lineWidth = line.width
  3097. var lastGlyph
  3098. //for each glyph in that line...
  3099. for (var i=start; i<end; i++) {
  3100. var id = text.charCodeAt(i)
  3101. var glyph = self.getGlyph(font, id)
  3102. if (glyph) {
  3103. if (lastGlyph)
  3104. x += getKerning(font, lastGlyph.id, glyph.id)
  3105. var tx = x
  3106. if (align === ALIGN_CENTER)
  3107. tx += (maxLineWidth-lineWidth)/2
  3108. else if (align === ALIGN_RIGHT)
  3109. tx += (maxLineWidth-lineWidth)
  3110. glyphs.push({
  3111. position: [tx, y],
  3112. data: glyph,
  3113. index: i,
  3114. line: lineIndex
  3115. })
  3116. //move pen forward
  3117. x += glyph.xadvance + letterSpacing
  3118. lastGlyph = glyph
  3119. }
  3120. }
  3121. //next line down
  3122. y += lineHeight
  3123. x = 0
  3124. })
  3125. this._linesTotal = lines.length;
  3126. }
  3127. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  3128. //These are fallbacks, when the font doesn't include
  3129. //' ' or '\t' glyphs
  3130. this._fallbackSpaceGlyph = null
  3131. this._fallbackTabGlyph = null
  3132. if (!font.chars || font.chars.length === 0)
  3133. return
  3134. //try to get space glyph
  3135. //then fall back to the 'm' or 'w' glyphs
  3136. //then fall back to the first glyph available
  3137. var space = getGlyphById(font, SPACE_ID)
  3138. || getMGlyph(font)
  3139. || font.chars[0]
  3140. //and create a fallback for tab
  3141. var tabWidth = this._opt.tabSize * space.xadvance
  3142. this._fallbackSpaceGlyph = space
  3143. this._fallbackTabGlyph = xtend(space, {
  3144. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  3145. xoffset: 0, yoffset: 0, width: 0, height: 0
  3146. })
  3147. }
  3148. TextLayout.prototype.getGlyph = function(font, id) {
  3149. var glyph = getGlyphById(font, id)
  3150. if (glyph)
  3151. return glyph
  3152. else if (id === TAB_ID)
  3153. return this._fallbackTabGlyph
  3154. else if (id === SPACE_ID)
  3155. return this._fallbackSpaceGlyph
  3156. return null
  3157. }
  3158. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3159. var letterSpacing = this._opt.letterSpacing || 0
  3160. var font = this._opt.font
  3161. var curPen = 0
  3162. var curWidth = 0
  3163. var count = 0
  3164. var glyph
  3165. var lastGlyph
  3166. if (!font.chars || font.chars.length === 0) {
  3167. return {
  3168. start: start,
  3169. end: start,
  3170. width: 0
  3171. }
  3172. }
  3173. end = Math.min(text.length, end)
  3174. for (var i=start; i < end; i++) {
  3175. var id = text.charCodeAt(i)
  3176. var glyph = this.getGlyph(font, id)
  3177. if (glyph) {
  3178. //move pen forward
  3179. var xoff = glyph.xoffset
  3180. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3181. curPen += kern
  3182. var nextPen = curPen + glyph.xadvance + letterSpacing
  3183. var nextWidth = curPen + glyph.width
  3184. //we've hit our limit; we can't move onto the next glyph
  3185. if (nextWidth >= width || nextPen >= width)
  3186. break
  3187. //otherwise continue along our line
  3188. curPen = nextPen
  3189. curWidth = nextWidth
  3190. lastGlyph = glyph
  3191. }
  3192. count++
  3193. }
  3194. //make sure rightmost edge lines up with rendered glyphs
  3195. if (lastGlyph)
  3196. curWidth += lastGlyph.xoffset
  3197. return {
  3198. start: start,
  3199. end: start + count,
  3200. width: curWidth
  3201. }
  3202. }
  3203. //getters for the private vars
  3204. ;['width', 'height',
  3205. 'descender', 'ascender',
  3206. 'xHeight', 'baseline',
  3207. 'capHeight',
  3208. 'lineHeight' ].forEach(addGetter)
  3209. function addGetter(name) {
  3210. Object.defineProperty(TextLayout.prototype, name, {
  3211. get: wrapper(name),
  3212. configurable: true
  3213. })
  3214. }
  3215. //create lookups for private vars
  3216. function wrapper(name) {
  3217. return (new Function([
  3218. 'return function '+name+'() {',
  3219. ' return this._'+name,
  3220. '}'
  3221. ].join('\n')))()
  3222. }
  3223. function getGlyphById(font, id) {
  3224. if (!font.chars || font.chars.length === 0)
  3225. return null
  3226. var glyphIdx = findChar(font.chars, id)
  3227. if (glyphIdx >= 0)
  3228. return font.chars[glyphIdx]
  3229. return null
  3230. }
  3231. function getXHeight(font) {
  3232. for (var i=0; i<X_HEIGHTS.length; i++) {
  3233. var id = X_HEIGHTS[i].charCodeAt(0)
  3234. var idx = findChar(font.chars, id)
  3235. if (idx >= 0)
  3236. return font.chars[idx].height
  3237. }
  3238. return 0
  3239. }
  3240. function getMGlyph(font) {
  3241. for (var i=0; i<M_WIDTHS.length; i++) {
  3242. var id = M_WIDTHS[i].charCodeAt(0)
  3243. var idx = findChar(font.chars, id)
  3244. if (idx >= 0)
  3245. return font.chars[idx]
  3246. }
  3247. return 0
  3248. }
  3249. function getCapHeight(font) {
  3250. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3251. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3252. var idx = findChar(font.chars, id)
  3253. if (idx >= 0)
  3254. return font.chars[idx].height
  3255. }
  3256. return 0
  3257. }
  3258. function getKerning(font, left, right) {
  3259. if (!font.kernings || font.kernings.length === 0)
  3260. return 0
  3261. var table = font.kernings
  3262. for (var i=0; i<table.length; i++) {
  3263. var kern = table[i]
  3264. if (kern.first === left && kern.second === right)
  3265. return kern.amount
  3266. }
  3267. return 0
  3268. }
  3269. function getAlignType(align) {
  3270. if (align === 'center')
  3271. return ALIGN_CENTER
  3272. else if (align === 'right')
  3273. return ALIGN_RIGHT
  3274. return ALIGN_LEFT
  3275. }
  3276. function findChar (array, value, start) {
  3277. start = start || 0
  3278. for (var i = start; i < array.length; i++) {
  3279. if (array[i].id === value) {
  3280. return i
  3281. }
  3282. }
  3283. return -1
  3284. }
  3285. },{"as-number":2,"word-wrapper":68,"xtend":71}],37:[function(_dereq_,module,exports){
  3286. (function (Buffer){
  3287. var xhr = _dereq_('xhr')
  3288. var noop = function(){}
  3289. var parseASCII = _dereq_('parse-bmfont-ascii')
  3290. var parseXML = _dereq_('parse-bmfont-xml')
  3291. var readBinary = _dereq_('parse-bmfont-binary')
  3292. var isBinaryFormat = _dereq_('./lib/is-binary')
  3293. var xtend = _dereq_('xtend')
  3294. var xml2 = (function hasXML2() {
  3295. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3296. })()
  3297. module.exports = function(opt, cb) {
  3298. cb = typeof cb === 'function' ? cb : noop
  3299. if (typeof opt === 'string')
  3300. opt = { uri: opt }
  3301. else if (!opt)
  3302. opt = {}
  3303. var expectBinary = opt.binary
  3304. if (expectBinary)
  3305. opt = getBinaryOpts(opt)
  3306. xhr(opt, function(err, res, body) {
  3307. if (err)
  3308. return cb(err)
  3309. if (!/^2/.test(res.statusCode))
  3310. return cb(new Error('http status code: '+res.statusCode))
  3311. if (!body)
  3312. return cb(new Error('no body result'))
  3313. var binary = false
  3314. //if the response type is an array buffer,
  3315. //we need to convert it into a regular Buffer object
  3316. if (isArrayBuffer(body)) {
  3317. var array = new Uint8Array(body)
  3318. body = new Buffer(array, 'binary')
  3319. }
  3320. //now check the string/Buffer response
  3321. //and see if it has a binary BMF header
  3322. if (isBinaryFormat(body)) {
  3323. binary = true
  3324. //if we have a string, turn it into a Buffer
  3325. if (typeof body === 'string')
  3326. body = new Buffer(body, 'binary')
  3327. }
  3328. //we are not parsing a binary format, just ASCII/XML/etc
  3329. if (!binary) {
  3330. //might still be a buffer if responseType is 'arraybuffer'
  3331. if (Buffer.isBuffer(body))
  3332. body = body.toString(opt.encoding)
  3333. body = body.trim()
  3334. }
  3335. var result
  3336. try {
  3337. var type = res.headers['content-type']
  3338. if (binary)
  3339. result = readBinary(body)
  3340. else if (/json/.test(type) || body.charAt(0) === '{')
  3341. result = JSON.parse(body)
  3342. else if (/xml/.test(type) || body.charAt(0) === '<')
  3343. result = parseXML(body)
  3344. else
  3345. result = parseASCII(body)
  3346. } catch (e) {
  3347. cb(new Error('error parsing font '+e.message))
  3348. cb = noop
  3349. }
  3350. cb(null, result)
  3351. })
  3352. }
  3353. function isArrayBuffer(arr) {
  3354. var str = Object.prototype.toString
  3355. return str.call(arr) === '[object ArrayBuffer]'
  3356. }
  3357. function getBinaryOpts(opt) {
  3358. //IE10+ and other modern browsers support array buffers
  3359. if (xml2)
  3360. return xtend(opt, { responseType: 'arraybuffer' })
  3361. if (typeof self.XMLHttpRequest === 'undefined')
  3362. throw new Error('your browser does not support XHR loading')
  3363. //IE9 and XML1 browsers could still use an override
  3364. var req = new self.XMLHttpRequest()
  3365. req.overrideMimeType('text/plain; charset=x-user-defined')
  3366. return xtend({
  3367. xhr: req
  3368. }, opt)
  3369. }
  3370. }).call(this,_dereq_("buffer").Buffer)
  3371. },{"./lib/is-binary":38,"buffer":6,"parse-bmfont-ascii":43,"parse-bmfont-binary":44,"parse-bmfont-xml":45,"xhr":69,"xtend":71}],38:[function(_dereq_,module,exports){
  3372. (function (Buffer){
  3373. var equal = _dereq_('buffer-equal')
  3374. var HEADER = new Buffer([66, 77, 70, 3])
  3375. module.exports = function(buf) {
  3376. if (typeof buf === 'string')
  3377. return buf.substring(0, 3) === 'BMF'
  3378. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3379. }
  3380. }).call(this,_dereq_("buffer").Buffer)
  3381. },{"buffer":6,"buffer-equal":5}],39:[function(_dereq_,module,exports){
  3382. /*
  3383. object-assign
  3384. (c) Sindre Sorhus
  3385. @license MIT
  3386. */
  3387. 'use strict';
  3388. /* eslint-disable no-unused-vars */
  3389. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  3390. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3391. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3392. function toObject(val) {
  3393. if (val === null || val === undefined) {
  3394. throw new TypeError('Object.assign cannot be called with null or undefined');
  3395. }
  3396. return Object(val);
  3397. }
  3398. function shouldUseNative() {
  3399. try {
  3400. if (!Object.assign) {
  3401. return false;
  3402. }
  3403. // Detect buggy property enumeration order in older V8 versions.
  3404. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3405. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  3406. test1[5] = 'de';
  3407. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3408. return false;
  3409. }
  3410. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3411. var test2 = {};
  3412. for (var i = 0; i < 10; i++) {
  3413. test2['_' + String.fromCharCode(i)] = i;
  3414. }
  3415. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3416. return test2[n];
  3417. });
  3418. if (order2.join('') !== '0123456789') {
  3419. return false;
  3420. }
  3421. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3422. var test3 = {};
  3423. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3424. test3[letter] = letter;
  3425. });
  3426. if (Object.keys(Object.assign({}, test3)).join('') !==
  3427. 'abcdefghijklmnopqrst') {
  3428. return false;
  3429. }
  3430. return true;
  3431. } catch (err) {
  3432. // We don't expect any of the above to throw, but better to be safe.
  3433. return false;
  3434. }
  3435. }
  3436. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3437. var from;
  3438. var to = toObject(target);
  3439. var symbols;
  3440. for (var s = 1; s < arguments.length; s++) {
  3441. from = Object(arguments[s]);
  3442. for (var key in from) {
  3443. if (hasOwnProperty.call(from, key)) {
  3444. to[key] = from[key];
  3445. }
  3446. }
  3447. if (getOwnPropertySymbols) {
  3448. symbols = getOwnPropertySymbols(from);
  3449. for (var i = 0; i < symbols.length; i++) {
  3450. if (propIsEnumerable.call(from, symbols[i])) {
  3451. to[symbols[i]] = from[symbols[i]];
  3452. }
  3453. }
  3454. }
  3455. }
  3456. return to;
  3457. };
  3458. },{}],40:[function(_dereq_,module,exports){
  3459. 'use strict';
  3460. var keysShim;
  3461. if (!Object.keys) {
  3462. // modified from https://github.com/es-shims/es5-shim
  3463. var has = Object.prototype.hasOwnProperty;
  3464. var toStr = Object.prototype.toString;
  3465. var isArgs = _dereq_('./isArguments'); // eslint-disable-line global-require
  3466. var isEnumerable = Object.prototype.propertyIsEnumerable;
  3467. var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
  3468. var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
  3469. var dontEnums = [
  3470. 'toString',
  3471. 'toLocaleString',
  3472. 'valueOf',
  3473. 'hasOwnProperty',
  3474. 'isPrototypeOf',
  3475. 'propertyIsEnumerable',
  3476. 'constructor'
  3477. ];
  3478. var equalsConstructorPrototype = function (o) {
  3479. var ctor = o.constructor;
  3480. return ctor && ctor.prototype === o;
  3481. };
  3482. var excludedKeys = {
  3483. $applicationCache: true,
  3484. $console: true,
  3485. $external: true,
  3486. $frame: true,
  3487. $frameElement: true,
  3488. $frames: true,
  3489. $innerHeight: true,
  3490. $innerWidth: true,
  3491. $onmozfullscreenchange: true,
  3492. $onmozfullscreenerror: true,
  3493. $outerHeight: true,
  3494. $outerWidth: true,
  3495. $pageXOffset: true,
  3496. $pageYOffset: true,
  3497. $parent: true,
  3498. $scrollLeft: true,
  3499. $scrollTop: true,
  3500. $scrollX: true,
  3501. $scrollY: true,
  3502. $self: true,
  3503. $webkitIndexedDB: true,
  3504. $webkitStorageInfo: true,
  3505. $window: true
  3506. };
  3507. var hasAutomationEqualityBug = (function () {
  3508. /* global window */
  3509. if (typeof window === 'undefined') { return false; }
  3510. for (var k in window) {
  3511. try {
  3512. if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
  3513. try {
  3514. equalsConstructorPrototype(window[k]);
  3515. } catch (e) {
  3516. return true;
  3517. }
  3518. }
  3519. } catch (e) {
  3520. return true;
  3521. }
  3522. }
  3523. return false;
  3524. }());
  3525. var equalsConstructorPrototypeIfNotBuggy = function (o) {
  3526. /* global window */
  3527. if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
  3528. return equalsConstructorPrototype(o);
  3529. }
  3530. try {
  3531. return equalsConstructorPrototype(o);
  3532. } catch (e) {
  3533. return false;
  3534. }
  3535. };
  3536. keysShim = function keys(object) {
  3537. var isObject = object !== null && typeof object === 'object';
  3538. var isFunction = toStr.call(object) === '[object Function]';
  3539. var isArguments = isArgs(object);
  3540. var isString = isObject && toStr.call(object) === '[object String]';
  3541. var theKeys = [];
  3542. if (!isObject && !isFunction && !isArguments) {
  3543. throw new TypeError('Object.keys called on a non-object');
  3544. }
  3545. var skipProto = hasProtoEnumBug && isFunction;
  3546. if (isString && object.length > 0 && !has.call(object, 0)) {
  3547. for (var i = 0; i < object.length; ++i) {
  3548. theKeys.push(String(i));
  3549. }
  3550. }
  3551. if (isArguments && object.length > 0) {
  3552. for (var j = 0; j < object.length; ++j) {
  3553. theKeys.push(String(j));
  3554. }
  3555. } else {
  3556. for (var name in object) {
  3557. if (!(skipProto && name === 'prototype') && has.call(object, name)) {
  3558. theKeys.push(String(name));
  3559. }
  3560. }
  3561. }
  3562. if (hasDontEnumBug) {
  3563. var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
  3564. for (var k = 0; k < dontEnums.length; ++k) {
  3565. if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
  3566. theKeys.push(dontEnums[k]);
  3567. }
  3568. }
  3569. }
  3570. return theKeys;
  3571. };
  3572. }
  3573. module.exports = keysShim;
  3574. },{"./isArguments":42}],41:[function(_dereq_,module,exports){
  3575. 'use strict';
  3576. var slice = Array.prototype.slice;
  3577. var isArgs = _dereq_('./isArguments');
  3578. var origKeys = Object.keys;
  3579. var keysShim = origKeys ? function keys(o) { return origKeys(o); } : _dereq_('./implementation');
  3580. var originalKeys = Object.keys;
  3581. keysShim.shim = function shimObjectKeys() {
  3582. if (Object.keys) {
  3583. var keysWorksWithArguments = (function () {
  3584. // Safari 5.0 bug
  3585. var args = Object.keys(arguments);
  3586. return args && args.length === arguments.length;
  3587. }(1, 2));
  3588. if (!keysWorksWithArguments) {
  3589. Object.keys = function keys(object) { // eslint-disable-line func-name-matching
  3590. if (isArgs(object)) {
  3591. return originalKeys(slice.call(object));
  3592. }
  3593. return originalKeys(object);
  3594. };
  3595. }
  3596. } else {
  3597. Object.keys = keysShim;
  3598. }
  3599. return Object.keys || keysShim;
  3600. };
  3601. module.exports = keysShim;
  3602. },{"./implementation":40,"./isArguments":42}],42:[function(_dereq_,module,exports){
  3603. 'use strict';
  3604. var toStr = Object.prototype.toString;
  3605. module.exports = function isArguments(value) {
  3606. var str = toStr.call(value);
  3607. var isArgs = str === '[object Arguments]';
  3608. if (!isArgs) {
  3609. isArgs = str !== '[object Array]' &&
  3610. value !== null &&
  3611. typeof value === 'object' &&
  3612. typeof value.length === 'number' &&
  3613. value.length >= 0 &&
  3614. toStr.call(value.callee) === '[object Function]';
  3615. }
  3616. return isArgs;
  3617. };
  3618. },{}],43:[function(_dereq_,module,exports){
  3619. module.exports = function parseBMFontAscii(data) {
  3620. if (!data)
  3621. throw new Error('no data provided')
  3622. data = data.toString().trim()
  3623. var output = {
  3624. pages: [],
  3625. chars: [],
  3626. kernings: []
  3627. }
  3628. var lines = data.split(/\r\n?|\n/g)
  3629. if (lines.length === 0)
  3630. throw new Error('no data in BMFont file')
  3631. for (var i = 0; i < lines.length; i++) {
  3632. var lineData = splitLine(lines[i], i)
  3633. if (!lineData) //skip empty lines
  3634. continue
  3635. if (lineData.key === 'page') {
  3636. if (typeof lineData.data.id !== 'number')
  3637. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3638. if (typeof lineData.data.file !== 'string')
  3639. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3640. output.pages[lineData.data.id] = lineData.data.file
  3641. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3642. //... do nothing for these two ...
  3643. } else if (lineData.key === 'char') {
  3644. output.chars.push(lineData.data)
  3645. } else if (lineData.key === 'kerning') {
  3646. output.kernings.push(lineData.data)
  3647. } else {
  3648. output[lineData.key] = lineData.data
  3649. }
  3650. }
  3651. return output
  3652. }
  3653. function splitLine(line, idx) {
  3654. line = line.replace(/\t+/g, ' ').trim()
  3655. if (!line)
  3656. return null
  3657. var space = line.indexOf(' ')
  3658. if (space === -1)
  3659. throw new Error("no named row at line " + idx)
  3660. var key = line.substring(0, space)
  3661. line = line.substring(space + 1)
  3662. //clear "letter" field as it is non-standard and
  3663. //requires additional complexity to parse " / = symbols
  3664. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3665. line = line.split("=")
  3666. line = line.map(function(str) {
  3667. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3668. })
  3669. var data = []
  3670. for (var i = 0; i < line.length; i++) {
  3671. var dt = line[i]
  3672. if (i === 0) {
  3673. data.push({
  3674. key: dt[0],
  3675. data: ""
  3676. })
  3677. } else if (i === line.length - 1) {
  3678. data[data.length - 1].data = parseData(dt[0])
  3679. } else {
  3680. data[data.length - 1].data = parseData(dt[0])
  3681. data.push({
  3682. key: dt[1],
  3683. data: ""
  3684. })
  3685. }
  3686. }
  3687. var out = {
  3688. key: key,
  3689. data: {}
  3690. }
  3691. data.forEach(function(v) {
  3692. out.data[v.key] = v.data;
  3693. })
  3694. return out
  3695. }
  3696. function parseData(data) {
  3697. if (!data || data.length === 0)
  3698. return ""
  3699. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3700. return data.substring(1, data.length - 1)
  3701. if (data.indexOf(',') !== -1)
  3702. return parseIntList(data)
  3703. return parseInt(data, 10)
  3704. }
  3705. function parseIntList(data) {
  3706. return data.split(',').map(function(val) {
  3707. return parseInt(val, 10)
  3708. })
  3709. }
  3710. },{}],44:[function(_dereq_,module,exports){
  3711. var HEADER = [66, 77, 70]
  3712. module.exports = function readBMFontBinary(buf) {
  3713. if (buf.length < 6)
  3714. throw new Error('invalid buffer length for BMFont')
  3715. var header = HEADER.every(function(byte, i) {
  3716. return buf.readUInt8(i) === byte
  3717. })
  3718. if (!header)
  3719. throw new Error('BMFont missing BMF byte header')
  3720. var i = 3
  3721. var vers = buf.readUInt8(i++)
  3722. if (vers > 3)
  3723. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3724. var target = { kernings: [], chars: [] }
  3725. for (var b=0; b<5; b++)
  3726. i += readBlock(target, buf, i)
  3727. return target
  3728. }
  3729. function readBlock(target, buf, i) {
  3730. if (i > buf.length-1)
  3731. return 0
  3732. var blockID = buf.readUInt8(i++)
  3733. var blockSize = buf.readInt32LE(i)
  3734. i += 4
  3735. switch(blockID) {
  3736. case 1:
  3737. target.info = readInfo(buf, i)
  3738. break
  3739. case 2:
  3740. target.common = readCommon(buf, i)
  3741. break
  3742. case 3:
  3743. target.pages = readPages(buf, i, blockSize)
  3744. break
  3745. case 4:
  3746. target.chars = readChars(buf, i, blockSize)
  3747. break
  3748. case 5:
  3749. target.kernings = readKernings(buf, i, blockSize)
  3750. break
  3751. }
  3752. return 5 + blockSize
  3753. }
  3754. function readInfo(buf, i) {
  3755. var info = {}
  3756. info.size = buf.readInt16LE(i)
  3757. var bitField = buf.readUInt8(i+2)
  3758. info.smooth = (bitField >> 7) & 1
  3759. info.unicode = (bitField >> 6) & 1
  3760. info.italic = (bitField >> 5) & 1
  3761. info.bold = (bitField >> 4) & 1
  3762. //fixedHeight is only mentioned in binary spec
  3763. if ((bitField >> 3) & 1)
  3764. info.fixedHeight = 1
  3765. info.charset = buf.readUInt8(i+3) || ''
  3766. info.stretchH = buf.readUInt16LE(i+4)
  3767. info.aa = buf.readUInt8(i+6)
  3768. info.padding = [
  3769. buf.readInt8(i+7),
  3770. buf.readInt8(i+8),
  3771. buf.readInt8(i+9),
  3772. buf.readInt8(i+10)
  3773. ]
  3774. info.spacing = [
  3775. buf.readInt8(i+11),
  3776. buf.readInt8(i+12)
  3777. ]
  3778. info.outline = buf.readUInt8(i+13)
  3779. info.face = readStringNT(buf, i+14)
  3780. return info
  3781. }
  3782. function readCommon(buf, i) {
  3783. var common = {}
  3784. common.lineHeight = buf.readUInt16LE(i)
  3785. common.base = buf.readUInt16LE(i+2)
  3786. common.scaleW = buf.readUInt16LE(i+4)
  3787. common.scaleH = buf.readUInt16LE(i+6)
  3788. common.pages = buf.readUInt16LE(i+8)
  3789. var bitField = buf.readUInt8(i+10)
  3790. common.packed = 0
  3791. common.alphaChnl = buf.readUInt8(i+11)
  3792. common.redChnl = buf.readUInt8(i+12)
  3793. common.greenChnl = buf.readUInt8(i+13)
  3794. common.blueChnl = buf.readUInt8(i+14)
  3795. return common
  3796. }
  3797. function readPages(buf, i, size) {
  3798. var pages = []
  3799. var text = readNameNT(buf, i)
  3800. var len = text.length+1
  3801. var count = size / len
  3802. for (var c=0; c<count; c++) {
  3803. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3804. i += len
  3805. }
  3806. return pages
  3807. }
  3808. function readChars(buf, i, blockSize) {
  3809. var chars = []
  3810. var count = blockSize / 20
  3811. for (var c=0; c<count; c++) {
  3812. var char = {}
  3813. var off = c*20
  3814. char.id = buf.readUInt32LE(i + 0 + off)
  3815. char.x = buf.readUInt16LE(i + 4 + off)
  3816. char.y = buf.readUInt16LE(i + 6 + off)
  3817. char.width = buf.readUInt16LE(i + 8 + off)
  3818. char.height = buf.readUInt16LE(i + 10 + off)
  3819. char.xoffset = buf.readInt16LE(i + 12 + off)
  3820. char.yoffset = buf.readInt16LE(i + 14 + off)
  3821. char.xadvance = buf.readInt16LE(i + 16 + off)
  3822. char.page = buf.readUInt8(i + 18 + off)
  3823. char.chnl = buf.readUInt8(i + 19 + off)
  3824. chars[c] = char
  3825. }
  3826. return chars
  3827. }
  3828. function readKernings(buf, i, blockSize) {
  3829. var kernings = []
  3830. var count = blockSize / 10
  3831. for (var c=0; c<count; c++) {
  3832. var kern = {}
  3833. var off = c*10
  3834. kern.first = buf.readUInt32LE(i + 0 + off)
  3835. kern.second = buf.readUInt32LE(i + 4 + off)
  3836. kern.amount = buf.readInt16LE(i + 8 + off)
  3837. kernings[c] = kern
  3838. }
  3839. return kernings
  3840. }
  3841. function readNameNT(buf, offset) {
  3842. var pos=offset
  3843. for (; pos<buf.length; pos++) {
  3844. if (buf[pos] === 0x00)
  3845. break
  3846. }
  3847. return buf.slice(offset, pos)
  3848. }
  3849. function readStringNT(buf, offset) {
  3850. return readNameNT(buf, offset).toString('utf8')
  3851. }
  3852. },{}],45:[function(_dereq_,module,exports){
  3853. var parseAttributes = _dereq_('./parse-attribs')
  3854. var parseFromString = _dereq_('xml-parse-from-string')
  3855. //In some cases element.attribute.nodeName can return
  3856. //all lowercase values.. so we need to map them to the correct
  3857. //case
  3858. var NAME_MAP = {
  3859. scaleh: 'scaleH',
  3860. scalew: 'scaleW',
  3861. stretchh: 'stretchH',
  3862. lineheight: 'lineHeight',
  3863. alphachnl: 'alphaChnl',
  3864. redchnl: 'redChnl',
  3865. greenchnl: 'greenChnl',
  3866. bluechnl: 'blueChnl'
  3867. }
  3868. module.exports = function parse(data) {
  3869. data = data.toString()
  3870. var xmlRoot = parseFromString(data)
  3871. var output = {
  3872. pages: [],
  3873. chars: [],
  3874. kernings: []
  3875. }
  3876. //get config settings
  3877. ;['info', 'common'].forEach(function(key) {
  3878. var element = xmlRoot.getElementsByTagName(key)[0]
  3879. if (element)
  3880. output[key] = parseAttributes(getAttribs(element))
  3881. })
  3882. //get page info
  3883. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3884. if (!pageRoot)
  3885. throw new Error('malformed file -- no <pages> element')
  3886. var pages = pageRoot.getElementsByTagName('page')
  3887. for (var i=0; i<pages.length; i++) {
  3888. var p = pages[i]
  3889. var id = parseInt(p.getAttribute('id'), 10)
  3890. var file = p.getAttribute('file')
  3891. if (isNaN(id))
  3892. throw new Error('malformed file -- page "id" attribute is NaN')
  3893. if (!file)
  3894. throw new Error('malformed file -- needs page "file" attribute')
  3895. output.pages[parseInt(id, 10)] = file
  3896. }
  3897. //get kernings / chars
  3898. ;['chars', 'kernings'].forEach(function(key) {
  3899. var element = xmlRoot.getElementsByTagName(key)[0]
  3900. if (!element)
  3901. return
  3902. var childTag = key.substring(0, key.length-1)
  3903. var children = element.getElementsByTagName(childTag)
  3904. for (var i=0; i<children.length; i++) {
  3905. var child = children[i]
  3906. output[key].push(parseAttributes(getAttribs(child)))
  3907. }
  3908. })
  3909. return output
  3910. }
  3911. function getAttribs(element) {
  3912. var attribs = getAttribList(element)
  3913. return attribs.reduce(function(dict, attrib) {
  3914. var key = mapName(attrib.nodeName)
  3915. dict[key] = attrib.nodeValue
  3916. return dict
  3917. }, {})
  3918. }
  3919. function getAttribList(element) {
  3920. //IE8+ and modern browsers
  3921. var attribs = []
  3922. for (var i=0; i<element.attributes.length; i++)
  3923. attribs.push(element.attributes[i])
  3924. return attribs
  3925. }
  3926. function mapName(nodeName) {
  3927. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3928. }
  3929. },{"./parse-attribs":46,"xml-parse-from-string":70}],46:[function(_dereq_,module,exports){
  3930. //Some versions of GlyphDesigner have a typo
  3931. //that causes some bugs with parsing.
  3932. //Need to confirm with recent version of the software
  3933. //to see whether this is still an issue or not.
  3934. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3935. module.exports = function parseAttributes(obj) {
  3936. if (GLYPH_DESIGNER_ERROR in obj) {
  3937. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3938. delete obj[GLYPH_DESIGNER_ERROR]
  3939. }
  3940. for (var k in obj) {
  3941. if (k === 'face' || k === 'charset')
  3942. continue
  3943. else if (k === 'padding' || k === 'spacing')
  3944. obj[k] = parseIntList(obj[k])
  3945. else
  3946. obj[k] = parseInt(obj[k], 10)
  3947. }
  3948. return obj
  3949. }
  3950. function parseIntList(data) {
  3951. return data.split(',').map(function(val) {
  3952. return parseInt(val, 10)
  3953. })
  3954. }
  3955. },{}],47:[function(_dereq_,module,exports){
  3956. var trim = _dereq_('string.prototype.trim')
  3957. , forEach = _dereq_('for-each')
  3958. , isArray = function(arg) {
  3959. return Object.prototype.toString.call(arg) === '[object Array]';
  3960. }
  3961. module.exports = function (headers) {
  3962. if (!headers)
  3963. return {}
  3964. var result = {}
  3965. forEach(
  3966. trim(headers).split('\n')
  3967. , function (row) {
  3968. var index = row.indexOf(':')
  3969. , key = trim(row.slice(0, index)).toLowerCase()
  3970. , value = trim(row.slice(index + 1))
  3971. if (typeof(result[key]) === 'undefined') {
  3972. result[key] = value
  3973. } else if (isArray(result[key])) {
  3974. result[key].push(value)
  3975. } else {
  3976. result[key] = [ result[key], value ]
  3977. }
  3978. }
  3979. )
  3980. return result
  3981. }
  3982. },{"for-each":24,"string.prototype.trim":53}],48:[function(_dereq_,module,exports){
  3983. (function (global){
  3984. var performance = global.performance || {};
  3985. var present = (function () {
  3986. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3987. while (names.length) {
  3988. var name = names.shift();
  3989. if (name in performance) {
  3990. return performance[name].bind(performance);
  3991. }
  3992. }
  3993. var dateNow = Date.now || function () { return new Date().getTime(); };
  3994. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3995. return function () {
  3996. return dateNow() - navigationStart;
  3997. };
  3998. }());
  3999. present.performanceNow = performance.now;
  4000. present.noConflict = function () {
  4001. performance.now = present.performanceNow;
  4002. };
  4003. present.conflict = function () {
  4004. performance.now = present;
  4005. };
  4006. present.conflict();
  4007. module.exports = present;
  4008. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4009. },{}],49:[function(_dereq_,module,exports){
  4010. // shim for using process in browser
  4011. var process = module.exports = {};
  4012. // cached from whatever global is present so that test runners that stub it
  4013. // don't break things. But we need to wrap it in a try catch in case it is
  4014. // wrapped in strict mode code which doesn't define any globals. It's inside a
  4015. // function because try/catches deoptimize in certain engines.
  4016. var cachedSetTimeout;
  4017. var cachedClearTimeout;
  4018. function defaultSetTimout() {
  4019. throw new Error('setTimeout has not been defined');
  4020. }
  4021. function defaultClearTimeout () {
  4022. throw new Error('clearTimeout has not been defined');
  4023. }
  4024. (function () {
  4025. try {
  4026. if (typeof setTimeout === 'function') {
  4027. cachedSetTimeout = setTimeout;
  4028. } else {
  4029. cachedSetTimeout = defaultSetTimout;
  4030. }
  4031. } catch (e) {
  4032. cachedSetTimeout = defaultSetTimout;
  4033. }
  4034. try {
  4035. if (typeof clearTimeout === 'function') {
  4036. cachedClearTimeout = clearTimeout;
  4037. } else {
  4038. cachedClearTimeout = defaultClearTimeout;
  4039. }
  4040. } catch (e) {
  4041. cachedClearTimeout = defaultClearTimeout;
  4042. }
  4043. } ())
  4044. function runTimeout(fun) {
  4045. if (cachedSetTimeout === setTimeout) {
  4046. //normal enviroments in sane situations
  4047. return setTimeout(fun, 0);
  4048. }
  4049. // if setTimeout wasn't available but was latter defined
  4050. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  4051. cachedSetTimeout = setTimeout;
  4052. return setTimeout(fun, 0);
  4053. }
  4054. try {
  4055. // when when somebody has screwed with setTimeout but no I.E. maddness
  4056. return cachedSetTimeout(fun, 0);
  4057. } catch(e){
  4058. try {
  4059. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4060. return cachedSetTimeout.call(null, fun, 0);
  4061. } catch(e){
  4062. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  4063. return cachedSetTimeout.call(this, fun, 0);
  4064. }
  4065. }
  4066. }
  4067. function runClearTimeout(marker) {
  4068. if (cachedClearTimeout === clearTimeout) {
  4069. //normal enviroments in sane situations
  4070. return clearTimeout(marker);
  4071. }
  4072. // if clearTimeout wasn't available but was latter defined
  4073. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  4074. cachedClearTimeout = clearTimeout;
  4075. return clearTimeout(marker);
  4076. }
  4077. try {
  4078. // when when somebody has screwed with setTimeout but no I.E. maddness
  4079. return cachedClearTimeout(marker);
  4080. } catch (e){
  4081. try {
  4082. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4083. return cachedClearTimeout.call(null, marker);
  4084. } catch (e){
  4085. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  4086. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  4087. return cachedClearTimeout.call(this, marker);
  4088. }
  4089. }
  4090. }
  4091. var queue = [];
  4092. var draining = false;
  4093. var currentQueue;
  4094. var queueIndex = -1;
  4095. function cleanUpNextTick() {
  4096. if (!draining || !currentQueue) {
  4097. return;
  4098. }
  4099. draining = false;
  4100. if (currentQueue.length) {
  4101. queue = currentQueue.concat(queue);
  4102. } else {
  4103. queueIndex = -1;
  4104. }
  4105. if (queue.length) {
  4106. drainQueue();
  4107. }
  4108. }
  4109. function drainQueue() {
  4110. if (draining) {
  4111. return;
  4112. }
  4113. var timeout = runTimeout(cleanUpNextTick);
  4114. draining = true;
  4115. var len = queue.length;
  4116. while(len) {
  4117. currentQueue = queue;
  4118. queue = [];
  4119. while (++queueIndex < len) {
  4120. if (currentQueue) {
  4121. currentQueue[queueIndex].run();
  4122. }
  4123. }
  4124. queueIndex = -1;
  4125. len = queue.length;
  4126. }
  4127. currentQueue = null;
  4128. draining = false;
  4129. runClearTimeout(timeout);
  4130. }
  4131. process.nextTick = function (fun) {
  4132. var args = new Array(arguments.length - 1);
  4133. if (arguments.length > 1) {
  4134. for (var i = 1; i < arguments.length; i++) {
  4135. args[i - 1] = arguments[i];
  4136. }
  4137. }
  4138. queue.push(new Item(fun, args));
  4139. if (queue.length === 1 && !draining) {
  4140. runTimeout(drainQueue);
  4141. }
  4142. };
  4143. // v8 likes predictible objects
  4144. function Item(fun, array) {
  4145. this.fun = fun;
  4146. this.array = array;
  4147. }
  4148. Item.prototype.run = function () {
  4149. this.fun.apply(null, this.array);
  4150. };
  4151. process.title = 'browser';
  4152. process.browser = true;
  4153. process.env = {};
  4154. process.argv = [];
  4155. process.version = ''; // empty string to avoid regexp issues
  4156. process.versions = {};
  4157. function noop() {}
  4158. process.on = noop;
  4159. process.addListener = noop;
  4160. process.once = noop;
  4161. process.off = noop;
  4162. process.removeListener = noop;
  4163. process.removeAllListeners = noop;
  4164. process.emit = noop;
  4165. process.prependListener = noop;
  4166. process.prependOnceListener = noop;
  4167. process.listeners = function (name) { return [] }
  4168. process.binding = function (name) {
  4169. throw new Error('process.binding is not supported');
  4170. };
  4171. process.cwd = function () { return '/' };
  4172. process.chdir = function (dir) {
  4173. throw new Error('process.chdir is not supported');
  4174. };
  4175. process.umask = function() { return 0; };
  4176. },{}],50:[function(_dereq_,module,exports){
  4177. (function (setImmediate){
  4178. (function(root) {
  4179. // Store setTimeout reference so promise-polyfill will be unaffected by
  4180. // other code modifying setTimeout (like sinon.useFakeTimers())
  4181. var setTimeoutFunc = setTimeout;
  4182. // Use polyfill for setImmediate for performance gains
  4183. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  4184. function(fn) { setTimeoutFunc(fn, 1); };
  4185. // Polyfill for Function.prototype.bind
  4186. function bind(fn, thisArg) {
  4187. return function() {
  4188. fn.apply(thisArg, arguments);
  4189. }
  4190. }
  4191. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  4192. function Promise(fn) {
  4193. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  4194. if (typeof fn !== 'function') throw new TypeError('not a function');
  4195. this._state = null;
  4196. this._value = null;
  4197. this._deferreds = []
  4198. doResolve(fn, bind(resolve, this), bind(reject, this))
  4199. }
  4200. function handle(deferred) {
  4201. var me = this;
  4202. if (this._state === null) {
  4203. this._deferreds.push(deferred);
  4204. return
  4205. }
  4206. asap(function() {
  4207. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  4208. if (cb === null) {
  4209. (me._state ? deferred.resolve : deferred.reject)(me._value);
  4210. return;
  4211. }
  4212. var ret;
  4213. try {
  4214. ret = cb(me._value);
  4215. }
  4216. catch (e) {
  4217. deferred.reject(e);
  4218. return;
  4219. }
  4220. deferred.resolve(ret);
  4221. })
  4222. }
  4223. function resolve(newValue) {
  4224. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  4225. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  4226. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  4227. var then = newValue.then;
  4228. if (typeof then === 'function') {
  4229. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  4230. return;
  4231. }
  4232. }
  4233. this._state = true;
  4234. this._value = newValue;
  4235. finale.call(this);
  4236. } catch (e) { reject.call(this, e); }
  4237. }
  4238. function reject(newValue) {
  4239. this._state = false;
  4240. this._value = newValue;
  4241. finale.call(this);
  4242. }
  4243. function finale() {
  4244. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  4245. handle.call(this, this._deferreds[i]);
  4246. }
  4247. this._deferreds = null;
  4248. }
  4249. function Handler(onFulfilled, onRejected, resolve, reject){
  4250. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  4251. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  4252. this.resolve = resolve;
  4253. this.reject = reject;
  4254. }
  4255. /**
  4256. * Take a potentially misbehaving resolver function and make sure
  4257. * onFulfilled and onRejected are only called once.
  4258. *
  4259. * Makes no guarantees about asynchrony.
  4260. */
  4261. function doResolve(fn, onFulfilled, onRejected) {
  4262. var done = false;
  4263. try {
  4264. fn(function (value) {
  4265. if (done) return;
  4266. done = true;
  4267. onFulfilled(value);
  4268. }, function (reason) {
  4269. if (done) return;
  4270. done = true;
  4271. onRejected(reason);
  4272. })
  4273. } catch (ex) {
  4274. if (done) return;
  4275. done = true;
  4276. onRejected(ex);
  4277. }
  4278. }
  4279. Promise.prototype['catch'] = function (onRejected) {
  4280. return this.then(null, onRejected);
  4281. };
  4282. Promise.prototype.then = function(onFulfilled, onRejected) {
  4283. var me = this;
  4284. return new Promise(function(resolve, reject) {
  4285. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  4286. })
  4287. };
  4288. Promise.all = function () {
  4289. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  4290. return new Promise(function (resolve, reject) {
  4291. if (args.length === 0) return resolve([]);
  4292. var remaining = args.length;
  4293. function res(i, val) {
  4294. try {
  4295. if (val && (typeof val === 'object' || typeof val === 'function')) {
  4296. var then = val.then;
  4297. if (typeof then === 'function') {
  4298. then.call(val, function (val) { res(i, val) }, reject);
  4299. return;
  4300. }
  4301. }
  4302. args[i] = val;
  4303. if (--remaining === 0) {
  4304. resolve(args);
  4305. }
  4306. } catch (ex) {
  4307. reject(ex);
  4308. }
  4309. }
  4310. for (var i = 0; i < args.length; i++) {
  4311. res(i, args[i]);
  4312. }
  4313. });
  4314. };
  4315. Promise.resolve = function (value) {
  4316. if (value && typeof value === 'object' && value.constructor === Promise) {
  4317. return value;
  4318. }
  4319. return new Promise(function (resolve) {
  4320. resolve(value);
  4321. });
  4322. };
  4323. Promise.reject = function (value) {
  4324. return new Promise(function (resolve, reject) {
  4325. reject(value);
  4326. });
  4327. };
  4328. Promise.race = function (values) {
  4329. return new Promise(function (resolve, reject) {
  4330. for(var i = 0, len = values.length; i < len; i++) {
  4331. values[i].then(resolve, reject);
  4332. }
  4333. });
  4334. };
  4335. /**
  4336. * Set the immediate function to execute callbacks
  4337. * @param fn {function} Function to execute
  4338. * @private
  4339. */
  4340. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4341. asap = fn;
  4342. };
  4343. if (typeof module !== 'undefined' && module.exports) {
  4344. module.exports = Promise;
  4345. } else if (!root.Promise) {
  4346. root.Promise = Promise;
  4347. }
  4348. })(this);
  4349. }).call(this,_dereq_("timers").setImmediate)
  4350. },{"timers":66}],51:[function(_dereq_,module,exports){
  4351. var dtype = _dereq_('dtype')
  4352. var anArray = _dereq_('an-array')
  4353. var isBuffer = _dereq_('is-buffer')
  4354. var CW = [0, 2, 3]
  4355. var CCW = [2, 1, 3]
  4356. module.exports = function createQuadElements(array, opt) {
  4357. //if user didn't specify an output array
  4358. if (!array || !(anArray(array) || isBuffer(array))) {
  4359. opt = array || {}
  4360. array = null
  4361. }
  4362. if (typeof opt === 'number') //backwards-compatible
  4363. opt = { count: opt }
  4364. else
  4365. opt = opt || {}
  4366. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4367. var count = typeof opt.count === 'number' ? opt.count : 1
  4368. var start = (opt.start || 0)
  4369. var dir = opt.clockwise !== false ? CW : CCW,
  4370. a = dir[0],
  4371. b = dir[1],
  4372. c = dir[2]
  4373. var numIndices = count * 6
  4374. var indices = array || new (dtype(type))(numIndices)
  4375. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4376. var x = i + start
  4377. indices[x + 0] = j + 0
  4378. indices[x + 1] = j + 1
  4379. indices[x + 2] = j + 2
  4380. indices[x + 3] = j + a
  4381. indices[x + 4] = j + b
  4382. indices[x + 5] = j + c
  4383. }
  4384. return indices
  4385. }
  4386. },{"an-array":1,"dtype":13,"is-buffer":31}],52:[function(_dereq_,module,exports){
  4387. 'use strict';
  4388. var bind = _dereq_('function-bind');
  4389. var ES = _dereq_('es-abstract/es5');
  4390. var replace = bind.call(Function.call, String.prototype.replace);
  4391. /* eslint-disable no-control-regex */
  4392. var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
  4393. var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;
  4394. /* eslint-enable no-control-regex */
  4395. module.exports = function trim() {
  4396. var S = ES.ToString(ES.CheckObjectCoercible(this));
  4397. return replace(replace(S, leftWhitespace, ''), rightWhitespace, '');
  4398. };
  4399. },{"es-abstract/es5":15,"function-bind":26}],53:[function(_dereq_,module,exports){
  4400. 'use strict';
  4401. var bind = _dereq_('function-bind');
  4402. var define = _dereq_('define-properties');
  4403. var implementation = _dereq_('./implementation');
  4404. var getPolyfill = _dereq_('./polyfill');
  4405. var shim = _dereq_('./shim');
  4406. var boundTrim = bind.call(Function.call, getPolyfill());
  4407. define(boundTrim, {
  4408. getPolyfill: getPolyfill,
  4409. implementation: implementation,
  4410. shim: shim
  4411. });
  4412. module.exports = boundTrim;
  4413. },{"./implementation":52,"./polyfill":54,"./shim":55,"define-properties":11,"function-bind":26}],54:[function(_dereq_,module,exports){
  4414. 'use strict';
  4415. var implementation = _dereq_('./implementation');
  4416. var zeroWidthSpace = '\u200b';
  4417. module.exports = function getPolyfill() {
  4418. if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) {
  4419. return String.prototype.trim;
  4420. }
  4421. return implementation;
  4422. };
  4423. },{"./implementation":52}],55:[function(_dereq_,module,exports){
  4424. 'use strict';
  4425. var define = _dereq_('define-properties');
  4426. var getPolyfill = _dereq_('./polyfill');
  4427. module.exports = function shimStringTrim() {
  4428. var polyfill = getPolyfill();
  4429. define(String.prototype, { trim: polyfill }, {
  4430. trim: function testTrim() {
  4431. return String.prototype.trim !== polyfill;
  4432. }
  4433. });
  4434. return polyfill;
  4435. };
  4436. },{"./polyfill":54,"define-properties":11}],56:[function(_dereq_,module,exports){
  4437. /*
  4438. * anime.js v3.0.0
  4439. * (c) 2019 Julian Garnier
  4440. * Released under the MIT license
  4441. * animejs.com
  4442. */
  4443. 'use strict';
  4444. // Defaults
  4445. var defaultInstanceSettings = {
  4446. update: null,
  4447. begin: null,
  4448. loopBegin: null,
  4449. changeBegin: null,
  4450. change: null,
  4451. changeComplete: null,
  4452. loopComplete: null,
  4453. complete: null,
  4454. loop: 1,
  4455. direction: 'normal',
  4456. autoplay: true,
  4457. timelineOffset: 0
  4458. };
  4459. var defaultTweenSettings = {
  4460. duration: 1000,
  4461. delay: 0,
  4462. endDelay: 0,
  4463. easing: 'easeOutElastic(1, .5)',
  4464. round: 0
  4465. };
  4466. var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
  4467. // Caching
  4468. var cache = {
  4469. CSS: {},
  4470. springs: {}
  4471. };
  4472. // Utils
  4473. function minMax(val, min, max) {
  4474. return Math.min(Math.max(val, min), max);
  4475. }
  4476. function stringContains(str, text) {
  4477. return str.indexOf(text) > -1;
  4478. }
  4479. function applyArguments(func, args) {
  4480. return func.apply(null, args);
  4481. }
  4482. var hexRegex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
  4483. var rgbPrefixRegex = /^rgb/;
  4484. var hslRegex = /^hsl/;
  4485. var is = {
  4486. arr: function (a) { return Array.isArray(a); },
  4487. obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
  4488. pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
  4489. svg: function (a) { return a instanceof SVGElement; },
  4490. inp: function (a) { return a instanceof HTMLInputElement; },
  4491. dom: function (a) { return a.nodeType || is.svg(a); },
  4492. str: function (a) { return typeof a === 'string'; },
  4493. fnc: function (a) { return typeof a === 'function'; },
  4494. und: function (a) { return typeof a === 'undefined'; },
  4495. hex: function (a) { return hexRegex.test(a); },
  4496. rgb: function (a) { return rgbPrefixRegex.test(a); },
  4497. hsl: function (a) { return hslRegex.test(a); },
  4498. col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
  4499. key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
  4500. };
  4501. // Easings
  4502. var easingFunctionRegex = /\(([^)]+)\)/;
  4503. function parseEasingParameters(string) {
  4504. var match = easingFunctionRegex.exec(string);
  4505. return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
  4506. }
  4507. // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
  4508. function spring(string, duration) {
  4509. var params = parseEasingParameters(string);
  4510. var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
  4511. var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
  4512. var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
  4513. var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
  4514. var w0 = Math.sqrt(stiffness / mass);
  4515. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  4516. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  4517. var a = 1;
  4518. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  4519. function solver(t) {
  4520. var progress = duration ? (duration * t) / 1000 : t;
  4521. if (zeta < 1) {
  4522. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  4523. } else {
  4524. progress = (a + b * progress) * Math.exp(-progress * w0);
  4525. }
  4526. if (t === 0 || t === 1) { return t; }
  4527. return 1 - progress;
  4528. }
  4529. function getDuration() {
  4530. var cached = cache.springs[string];
  4531. if (cached) { return cached; }
  4532. var frame = 1/6;
  4533. var elapsed = 0;
  4534. var rest = 0;
  4535. while(true) {
  4536. elapsed += frame;
  4537. if (solver(elapsed) === 1) {
  4538. rest++;
  4539. if (rest >= 16) { break; }
  4540. } else {
  4541. rest = 0;
  4542. }
  4543. }
  4544. var duration = elapsed * frame * 1000;
  4545. cache.springs[string] = duration;
  4546. return duration;
  4547. }
  4548. return duration ? solver : getDuration;
  4549. }
  4550. // Elastic easing adapted from jQueryUI http://api.jqueryui.com/easings/
  4551. function elastic(amplitude, period) {
  4552. if ( amplitude === void 0 ) amplitude = 1;
  4553. if ( period === void 0 ) period = .5;
  4554. var a = minMax(amplitude, 1, 10);
  4555. var p = minMax(period, .1, 2);
  4556. return function (t) {
  4557. return (t === 0 || t === 1) ? t :
  4558. -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
  4559. }
  4560. }
  4561. // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
  4562. function steps(steps) {
  4563. if ( steps === void 0 ) steps = 10;
  4564. return function (t) { return Math.round(t * steps) * (1 / steps); };
  4565. }
  4566. // BezierEasing https://github.com/gre/bezier-easing
  4567. var bezier = (function () {
  4568. var kSplineTableSize = 11;
  4569. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  4570. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
  4571. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
  4572. function C(aA1) { return 3.0 * aA1 }
  4573. function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
  4574. function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
  4575. function binarySubdivide(aX, aA, aB, mX1, mX2) {
  4576. var currentX, currentT, i = 0;
  4577. do {
  4578. currentT = aA + (aB - aA) / 2.0;
  4579. currentX = calcBezier(currentT, mX1, mX2) - aX;
  4580. if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
  4581. } while (Math.abs(currentX) > 0.0000001 && ++i < 10);
  4582. return currentT;
  4583. }
  4584. function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  4585. for (var i = 0; i < 4; ++i) {
  4586. var currentSlope = getSlope(aGuessT, mX1, mX2);
  4587. if (currentSlope === 0.0) { return aGuessT; }
  4588. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  4589. aGuessT -= currentX / currentSlope;
  4590. }
  4591. return aGuessT;
  4592. }
  4593. function bezier(mX1, mY1, mX2, mY2) {
  4594. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
  4595. var sampleValues = new Float32Array(kSplineTableSize);
  4596. if (mX1 !== mY1 || mX2 !== mY2) {
  4597. for (var i = 0; i < kSplineTableSize; ++i) {
  4598. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  4599. }
  4600. }
  4601. function getTForX(aX) {
  4602. var intervalStart = 0;
  4603. var currentSample = 1;
  4604. var lastSample = kSplineTableSize - 1;
  4605. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  4606. intervalStart += kSampleStepSize;
  4607. }
  4608. --currentSample;
  4609. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  4610. var guessForT = intervalStart + dist * kSampleStepSize;
  4611. var initialSlope = getSlope(guessForT, mX1, mX2);
  4612. if (initialSlope >= 0.001) {
  4613. return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
  4614. } else if (initialSlope === 0.0) {
  4615. return guessForT;
  4616. } else {
  4617. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  4618. }
  4619. }
  4620. return function (x) {
  4621. if (mX1 === mY1 && mX2 === mY2) { return x; }
  4622. if (x === 0 || x === 1) { return x; }
  4623. return calcBezier(getTForX(x), mY1, mY2);
  4624. }
  4625. }
  4626. return bezier;
  4627. })();
  4628. var penner = (function () {
  4629. var names = ['Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Back', 'Elastic'];
  4630. // Approximated Penner equations http://matthewlein.com/ceaser/
  4631. var curves = {
  4632. In: [
  4633. [0.550, 0.085, 0.680, 0.530], /* inQuad */
  4634. [0.550, 0.055, 0.675, 0.190], /* inCubic */
  4635. [0.895, 0.030, 0.685, 0.220], /* inQuart */
  4636. [0.755, 0.050, 0.855, 0.060], /* inQuint */
  4637. [0.470, 0.000, 0.745, 0.715], /* inSine */
  4638. [0.950, 0.050, 0.795, 0.035], /* inExpo */
  4639. [0.600, 0.040, 0.980, 0.335], /* inCirc */
  4640. [0.600,-0.280, 0.735, 0.045], /* inBack */
  4641. elastic /* inElastic */
  4642. ],
  4643. Out: [
  4644. [0.250, 0.460, 0.450, 0.940], /* outQuad */
  4645. [0.215, 0.610, 0.355, 1.000], /* outCubic */
  4646. [0.165, 0.840, 0.440, 1.000], /* outQuart */
  4647. [0.230, 1.000, 0.320, 1.000], /* outQuint */
  4648. [0.390, 0.575, 0.565, 1.000], /* outSine */
  4649. [0.190, 1.000, 0.220, 1.000], /* outExpo */
  4650. [0.075, 0.820, 0.165, 1.000], /* outCirc */
  4651. [0.175, 0.885, 0.320, 1.275], /* outBack */
  4652. function (a, p) { return function (t) { return 1 - elastic(a, p)(1 - t); }; } /* outElastic */
  4653. ],
  4654. InOut: [
  4655. [0.455, 0.030, 0.515, 0.955], /* inOutQuad */
  4656. [0.645, 0.045, 0.355, 1.000], /* inOutCubic */
  4657. [0.770, 0.000, 0.175, 1.000], /* inOutQuart */
  4658. [0.860, 0.000, 0.070, 1.000], /* inOutQuint */
  4659. [0.445, 0.050, 0.550, 0.950], /* inOutSine */
  4660. [1.000, 0.000, 0.000, 1.000], /* inOutExpo */
  4661. [0.785, 0.135, 0.150, 0.860], /* inOutCirc */
  4662. [0.680,-0.550, 0.265, 1.550], /* inOutBack */
  4663. function (a, p) { return function (t) { return t < .5 ? elastic(a, p)(t * 2) / 2 : 1 - elastic(a, p)(t * -2 + 2) / 2; }; } /* inOutElastic */
  4664. ]
  4665. };
  4666. var eases = {
  4667. linear: [0.250, 0.250, 0.750, 0.750]
  4668. };
  4669. for (var coords in curves) {
  4670. for (var i = 0, len = curves[coords].length; i < len; i++) {
  4671. eases['ease'+coords+names[i]] = curves[coords][i];
  4672. }
  4673. }
  4674. return eases;
  4675. })();
  4676. function parseEasings(easing, duration) {
  4677. if (is.fnc(easing)) { return easing; }
  4678. var name = easing.split('(')[0];
  4679. var ease = penner[name];
  4680. var args = parseEasingParameters(easing);
  4681. switch (name) {
  4682. case 'spring' : return spring(easing, duration);
  4683. case 'cubicBezier' : return applyArguments(bezier, args);
  4684. case 'steps' : return applyArguments(steps, args);
  4685. default : return is.fnc(ease) ? applyArguments(ease, args) : applyArguments(bezier, ease);
  4686. }
  4687. }
  4688. // Strings
  4689. function selectString(str) {
  4690. try {
  4691. var nodes = document.querySelectorAll(str);
  4692. return nodes;
  4693. } catch(e) {
  4694. return;
  4695. }
  4696. }
  4697. // Arrays
  4698. var auxArrayFilter = [];
  4699. function filterArray(arr, callback) {
  4700. var result = auxArrayFilter;
  4701. var len = arr.length;
  4702. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  4703. for (var i = 0; i < len; i++) {
  4704. if (i in arr) {
  4705. var val = arr[i];
  4706. if (callback.call(thisArg, val, i, arr)) {
  4707. result.push(val);
  4708. }
  4709. }
  4710. }
  4711. // arr turns into the auxArray and we return the previously aux array.
  4712. auxArrayFilter = arr;
  4713. auxArrayFilter.length = 0;
  4714. return result;
  4715. }
  4716. function flattenArray (arr, result) {
  4717. if (!result) { result = []; }
  4718. for (var i = 0, length = arr.length; i < length; i++) {
  4719. var value = arr[i];
  4720. if (Array.isArray(value)) {
  4721. flattenArray(value, result);
  4722. } else {
  4723. result.push(value);
  4724. }
  4725. }
  4726. return result;
  4727. }
  4728. function toArray(o) {
  4729. if (is.arr(o)) { return o; }
  4730. if (is.str(o)) { o = selectString(o) || o; }
  4731. if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
  4732. return [o];
  4733. }
  4734. function arrayContains(arr, val) {
  4735. return arr.some(function (a) { return a === val; });
  4736. }
  4737. // Objects
  4738. function cloneObject(o) {
  4739. var clone = {};
  4740. for (var p in o) { clone[p] = o[p]; }
  4741. return clone;
  4742. }
  4743. function replaceObjectProps(o1, o2) {
  4744. var o = cloneObject(o1);
  4745. for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
  4746. return o;
  4747. }
  4748. function mergeObjects(o1, o2) {
  4749. var o = cloneObject(o1);
  4750. for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
  4751. return o;
  4752. }
  4753. // Colors
  4754. var rgbRegex = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g;
  4755. function rgbToRgba(rgbValue) {
  4756. var rgb = rgbRegex.exec(rgbValue);
  4757. return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
  4758. }
  4759. var hexToRgbaHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  4760. var hexToRgbaRgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  4761. function hexToRgba(hexValue) {
  4762. var hex = hexValue.replace(hexToRgbaHexRegex, function (m, r, g, b) { return r + r + g + g + b + b; } );
  4763. var rgb = hexToRgbaRgbRegex.exec(hex);
  4764. var r = parseInt(rgb[1], 16);
  4765. var g = parseInt(rgb[2], 16);
  4766. var b = parseInt(rgb[3], 16);
  4767. return ("rgba(" + r + "," + g + "," + b + ",1)");
  4768. }
  4769. var hslToRgbaHsl1Regex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g;
  4770. var hslToRgbaHsl2Regex = /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g;
  4771. function hslToRgba(hslValue) {
  4772. var hsl = hslToRgbaHsl1Regex.exec(hslValue) || hslToRgbaHsl2Regex.exec(hslValue);
  4773. var h = parseInt(hsl[1], 10) / 360;
  4774. var s = parseInt(hsl[2], 10) / 100;
  4775. var l = parseInt(hsl[3], 10) / 100;
  4776. var a = hsl[4] || 1;
  4777. function hue2rgb(p, q, t) {
  4778. if (t < 0) { t += 1; }
  4779. if (t > 1) { t -= 1; }
  4780. if (t < 1/6) { return p + (q - p) * 6 * t; }
  4781. if (t < 1/2) { return q; }
  4782. if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
  4783. return p;
  4784. }
  4785. var r, g, b;
  4786. if (s == 0) {
  4787. r = g = b = l;
  4788. } else {
  4789. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  4790. var p = 2 * l - q;
  4791. r = hue2rgb(p, q, h + 1/3);
  4792. g = hue2rgb(p, q, h);
  4793. b = hue2rgb(p, q, h - 1/3);
  4794. }
  4795. return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
  4796. }
  4797. function colorToRgb(val) {
  4798. if (is.rgb(val)) { return rgbToRgba(val); }
  4799. if (is.hex(val)) { return hexToRgba(val); }
  4800. if (is.hsl(val)) { return hslToRgba(val); }
  4801. }
  4802. // Units
  4803. var unitRegex = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  4804. function getUnit(val) {
  4805. var split = unitRegex.exec(val);
  4806. if (split) { return split[2]; }
  4807. }
  4808. function getTransformUnit(propName) {
  4809. if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
  4810. if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
  4811. }
  4812. // Values
  4813. function getFunctionValue(val, animatable) {
  4814. if (!is.fnc(val)) { return val; }
  4815. return val(animatable.target, animatable.id, animatable.total);
  4816. }
  4817. function getAttribute(el, prop) {
  4818. return el.getAttribute(prop);
  4819. }
  4820. function convertPxToUnit(el, value, unit) {
  4821. var valueUnit = getUnit(value);
  4822. if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
  4823. var cached = cache.CSS[value + unit];
  4824. if (!is.und(cached)) { return cached; }
  4825. var baseline = 100;
  4826. var tempEl = document.createElement(el.tagName);
  4827. var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
  4828. parentEl.appendChild(tempEl);
  4829. tempEl.style.position = 'absolute';
  4830. tempEl.style.width = baseline + unit;
  4831. var factor = baseline / tempEl.offsetWidth;
  4832. parentEl.removeChild(tempEl);
  4833. var convertedUnit = factor * parseFloat(value);
  4834. cache.CSS[value + unit] = convertedUnit;
  4835. return convertedUnit;
  4836. }
  4837. function getCSSValue(el, prop, unit) {
  4838. if (prop in el.style) {
  4839. var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  4840. var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
  4841. return unit ? convertPxToUnit(el, value, unit) : value;
  4842. }
  4843. }
  4844. function getAnimationType(el, prop) {
  4845. if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
  4846. if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
  4847. if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
  4848. if (el[prop] != null) { return 'object'; }
  4849. }
  4850. var transformRegex = /(\w+)\(([^)]*)\)/g;
  4851. function getElementTransforms(el) {
  4852. if (!is.dom(el)) { return; }
  4853. var str = el.style.transform || '';
  4854. var transforms = new Map();
  4855. var m; while (m = transformRegex.exec(str)) { transforms.set(m[1], m[2]); }
  4856. return transforms;
  4857. }
  4858. function getTransformValue(el, propName, animatable, unit) {
  4859. var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
  4860. var value = getElementTransforms(el).get(propName) || defaultVal;
  4861. if (animatable) {
  4862. animatable.transforms.list.set(propName, value);
  4863. animatable.transforms['last'] = propName;
  4864. }
  4865. return unit ? convertPxToUnit(el, value, unit) : value;
  4866. }
  4867. function getOriginalTargetValue(target, propName, unit, animatable) {
  4868. switch (getAnimationType(target, propName)) {
  4869. case 'transform': return getTransformValue(target, propName, animatable, unit);
  4870. case 'css': return getCSSValue(target, propName, unit);
  4871. case 'attribute': return getAttribute(target, propName);
  4872. default: return target[propName] || 0;
  4873. }
  4874. }
  4875. var operatorRegex = /^(\*=|\+=|-=)/;
  4876. function getRelativeValue(to, from) {
  4877. var operator = operatorRegex.exec(to);
  4878. if (!operator) { return to; }
  4879. var u = getUnit(to) || 0;
  4880. var x = parseFloat(from);
  4881. var y = parseFloat(to.replace(operator[0], ''));
  4882. switch (operator[0][0]) {
  4883. case '+': return x + y + u;
  4884. case '-': return x - y + u;
  4885. case '*': return x * y + u;
  4886. }
  4887. }
  4888. var whitespaceRegex = /\s/g;
  4889. function validateValue(val, unit) {
  4890. if (is.col(val)) { return colorToRgb(val); }
  4891. var originalUnit = getUnit(val);
  4892. var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
  4893. return unit && !whitespaceRegex.test(val) ? unitLess + unit : unitLess;
  4894. }
  4895. // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
  4896. // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
  4897. function getDistance(p1, p2) {
  4898. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  4899. }
  4900. function getCircleLength(el) {
  4901. return Math.PI * 2 * getAttribute(el, 'r');
  4902. }
  4903. function getRectLength(el) {
  4904. return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
  4905. }
  4906. function getLineLength(el) {
  4907. return getDistance(
  4908. {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
  4909. {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
  4910. );
  4911. }
  4912. function getPolylineLength(el) {
  4913. var points = el.points;
  4914. var totalLength = 0;
  4915. var previousPos;
  4916. for (var i = 0 ; i < points.numberOfItems; i++) {
  4917. var currentPos = points.getItem(i);
  4918. if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
  4919. previousPos = currentPos;
  4920. }
  4921. return totalLength;
  4922. }
  4923. function getPolygonLength(el) {
  4924. var points = el.points;
  4925. return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
  4926. }
  4927. // Path animation
  4928. function getTotalLength(el) {
  4929. if (el.getTotalLength) { return el.getTotalLength(); }
  4930. switch(el.tagName.toLowerCase()) {
  4931. case 'circle': return getCircleLength(el);
  4932. case 'rect': return getRectLength(el);
  4933. case 'line': return getLineLength(el);
  4934. case 'polyline': return getPolylineLength(el);
  4935. case 'polygon': return getPolygonLength(el);
  4936. }
  4937. }
  4938. function setDashoffset(el) {
  4939. var pathLength = getTotalLength(el);
  4940. el.setAttribute('stroke-dasharray', pathLength);
  4941. return pathLength;
  4942. }
  4943. // Motion path
  4944. function getParentSvgEl(el) {
  4945. var parentEl = el.parentNode;
  4946. while (is.svg(parentEl)) {
  4947. parentEl = parentEl.parentNode;
  4948. if (!is.svg(parentEl.parentNode)) { break; }
  4949. }
  4950. return parentEl;
  4951. }
  4952. function getParentSvg(pathEl, svgData) {
  4953. var svg = svgData || {};
  4954. var parentSvgEl = svg.el || getParentSvgEl(pathEl);
  4955. var rect = parentSvgEl.getBoundingClientRect();
  4956. var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
  4957. var width = rect.width;
  4958. var height = rect.height;
  4959. var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
  4960. return {
  4961. el: parentSvgEl,
  4962. viewBox: viewBox,
  4963. x: viewBox[0] / 1,
  4964. y: viewBox[1] / 1,
  4965. w: width / viewBox[2],
  4966. h: height / viewBox[3]
  4967. }
  4968. }
  4969. function getPath(path, percent) {
  4970. var pathEl = is.str(path) ? selectString(path)[0] : path;
  4971. var p = percent || 100;
  4972. return function(property) {
  4973. return {
  4974. property: property,
  4975. el: pathEl,
  4976. svg: getParentSvg(pathEl),
  4977. totalLength: getTotalLength(pathEl) * (p / 100)
  4978. }
  4979. }
  4980. }
  4981. function getPathProgress(path, progress) {
  4982. function point(offset) {
  4983. if ( offset === void 0 ) offset = 0;
  4984. var l = progress + offset >= 1 ? progress + offset : 0;
  4985. return path.el.getPointAtLength(l);
  4986. }
  4987. var svg = getParentSvg(path.el, path.svg);
  4988. var p = point();
  4989. var p0 = point(-1);
  4990. var p1 = point(+1);
  4991. switch (path.property) {
  4992. case 'x': return (p.x - svg.x) * svg.w;
  4993. case 'y': return (p.y - svg.y) * svg.h;
  4994. case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
  4995. }
  4996. }
  4997. // Decompose value
  4998. var valueRegex = /-?\d*\.?\d+/g;
  4999. function decomposeValue(val, unit) {
  5000. var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
  5001. return {
  5002. original: value,
  5003. numbers: value.match(valueRegex) ? value.match(valueRegex).map(Number) : [0],
  5004. strings: (is.str(val) || unit) ? value.split(valueRegex) : []
  5005. }
  5006. }
  5007. // Animatables
  5008. function parseTargets(targets) {
  5009. var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
  5010. return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
  5011. }
  5012. function getAnimatables(targets) {
  5013. var parsed = parseTargets(targets);
  5014. return parsed.map(function (t, i) {
  5015. return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
  5016. });
  5017. }
  5018. // Properties
  5019. var springRegex = /^spring/;
  5020. function normalizePropertyTweens(prop, tweenSettings) {
  5021. var settings = cloneObject(tweenSettings);
  5022. // Override duration if easing is a spring
  5023. if (springRegex.test(settings.easing)) { settings.duration = spring(settings.easing); }
  5024. if (is.arr(prop)) {
  5025. var l = prop.length;
  5026. var isFromTo = (l === 2 && !is.obj(prop[0]));
  5027. if (!isFromTo) {
  5028. // Duration divided by the number of tweens
  5029. if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
  5030. } else {
  5031. // Transform [from, to] values shorthand to a valid tween value
  5032. prop = {value: prop};
  5033. }
  5034. }
  5035. var propArray = is.arr(prop) ? prop : [prop];
  5036. return propArray.map(function (v, i) {
  5037. var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
  5038. // Default delay value should only be applied to the first tween
  5039. if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
  5040. // Default endDelay value should only be applied to the last tween
  5041. if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
  5042. return obj;
  5043. }).map(function (k) { return mergeObjects(k, settings); });
  5044. }
  5045. function flattenKeyframes(keyframes) {
  5046. var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
  5047. .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
  5048. var properties = {};
  5049. var loop = function ( i ) {
  5050. var propName = propertyNames[i];
  5051. properties[propName] = keyframes.map(function (key) {
  5052. var newKey = {};
  5053. for (var p in key) {
  5054. if (is.key(p)) {
  5055. if (p == propName) { newKey.value = key[p]; }
  5056. } else {
  5057. newKey[p] = key[p];
  5058. }
  5059. }
  5060. return newKey;
  5061. });
  5062. };
  5063. for (var i = 0; i < propertyNames.length; i++) loop( i );
  5064. return properties;
  5065. }
  5066. function getProperties(tweenSettings, params) {
  5067. var properties = [];
  5068. var keyframes = params.keyframes;
  5069. if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
  5070. for (var p in params) {
  5071. if (is.key(p)) {
  5072. properties.push({
  5073. name: p,
  5074. tweens: normalizePropertyTweens(params[p], tweenSettings)
  5075. });
  5076. }
  5077. }
  5078. return properties;
  5079. }
  5080. // Tweens
  5081. function normalizeTweenValues(tween, animatable) {
  5082. var t = {};
  5083. for (var p in tween) {
  5084. var value = getFunctionValue(tween[p], animatable);
  5085. if (is.arr(value)) {
  5086. value = value.map(function (v) { return getFunctionValue(v, animatable); });
  5087. if (value.length === 1) { value = value[0]; }
  5088. }
  5089. t[p] = value;
  5090. }
  5091. t.duration = parseFloat(t.duration);
  5092. t.delay = parseFloat(t.delay);
  5093. return t;
  5094. }
  5095. function normalizeTweens(prop, animatable) {
  5096. var previousTween;
  5097. return prop.tweens.map(function (t) {
  5098. var tween = normalizeTweenValues(t, animatable);
  5099. var tweenValue = tween.value;
  5100. var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
  5101. var toUnit = getUnit(to);
  5102. var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
  5103. var previousValue = previousTween ? previousTween.to.original : originalValue;
  5104. var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
  5105. var fromUnit = getUnit(from) || getUnit(originalValue);
  5106. var unit = toUnit || fromUnit;
  5107. if (is.und(to)) { to = previousValue; }
  5108. tween.from = decomposeValue(from, unit);
  5109. tween.to = decomposeValue(getRelativeValue(to, from), unit);
  5110. tween.start = previousTween ? previousTween.end : 0;
  5111. tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
  5112. tween.easing = parseEasings(tween.easing, tween.duration);
  5113. tween.isPath = is.pth(tweenValue);
  5114. tween.isColor = is.col(tween.from.original);
  5115. if (tween.isColor) { tween.round = 1; }
  5116. previousTween = tween;
  5117. return tween;
  5118. });
  5119. }
  5120. // Tween progress
  5121. var setProgressValue = {
  5122. css: function (t, p, v) { return t.style[p] = v; },
  5123. attribute: function (t, p, v) { return t.setAttribute(p, v); },
  5124. object: function (t, p, v) { return t[p] = v; },
  5125. transform: function (t, p, v, transforms, manual) {
  5126. transforms.list.set(p, v);
  5127. if (p === transforms.last || manual) {
  5128. var str = '';
  5129. transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
  5130. t.style.transform = str;
  5131. }
  5132. }
  5133. };
  5134. // Set Value helper
  5135. function setTargetsValue(targets, properties) {
  5136. var animatables = getAnimatables(targets);
  5137. for (var i = 0, len = animatables.length; i < len; i++) {
  5138. var animatable = animatables[i];
  5139. for (var property in properties) {
  5140. var value = getFunctionValue(properties[property], animatable);
  5141. var target = animatable.target;
  5142. var valueUnit = getUnit(value);
  5143. var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
  5144. var unit = valueUnit || getUnit(originalValue);
  5145. var to = getRelativeValue(validateValue(value, unit), originalValue);
  5146. var animType = getAnimationType(target, property);
  5147. setProgressValue[animType](target, property, to, animatable.transforms, true);
  5148. }
  5149. }
  5150. }
  5151. // Animations
  5152. function createAnimation(animatable, prop) {
  5153. var animType = getAnimationType(animatable.target, prop.name);
  5154. if (animType) {
  5155. var tweens = normalizeTweens(prop, animatable);
  5156. var lastTween = tweens[tweens.length - 1];
  5157. return {
  5158. type: animType,
  5159. property: prop.name,
  5160. animatable: animatable,
  5161. tweens: tweens,
  5162. duration: lastTween.end,
  5163. delay: tweens[0].delay,
  5164. endDelay: lastTween.endDelay
  5165. }
  5166. }
  5167. }
  5168. function getAnimations(animatables, properties) {
  5169. return filterArray(flattenArray(animatables.map(function (animatable) {
  5170. return properties.map(function (prop) {
  5171. return createAnimation(animatable, prop);
  5172. });
  5173. })), function (a) { return !is.und(a); });
  5174. }
  5175. // Create Instance
  5176. function getInstanceTimings(animations, tweenSettings) {
  5177. var animLength = animations.length;
  5178. var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
  5179. var timings = {};
  5180. timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
  5181. timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
  5182. timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
  5183. return timings;
  5184. }
  5185. var instanceID = 0;
  5186. function createNewInstance(params) {
  5187. var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
  5188. var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
  5189. var properties = getProperties(tweenSettings, params);
  5190. var animatables = getAnimatables(params.targets);
  5191. var animations = getAnimations(animatables, properties);
  5192. var timings = getInstanceTimings(animations, tweenSettings);
  5193. var id = instanceID;
  5194. instanceID++;
  5195. return mergeObjects(instanceSettings, {
  5196. id: id,
  5197. children: [],
  5198. animatables: animatables,
  5199. animations: animations,
  5200. duration: timings.duration,
  5201. delay: timings.delay,
  5202. endDelay: timings.endDelay
  5203. });
  5204. }
  5205. // Core
  5206. var activeInstances = [];
  5207. var pausedInstances = [];
  5208. var raf;
  5209. var engine = (function () {
  5210. function play() {
  5211. raf = requestAnimationFrame(step);
  5212. }
  5213. function step(t) {
  5214. var activeInstancesLength = activeInstances.length;
  5215. if (activeInstancesLength) {
  5216. var i = 0;
  5217. while (i < activeInstancesLength) {
  5218. var activeInstance = activeInstances[i];
  5219. if (!activeInstance.paused) {
  5220. activeInstance.tick(t);
  5221. } else {
  5222. var instanceIndex = activeInstances.indexOf(activeInstance);
  5223. if (instanceIndex > -1) {
  5224. activeInstances.splice(instanceIndex, 1);
  5225. activeInstancesLength = activeInstances.length;
  5226. }
  5227. }
  5228. i++;
  5229. }
  5230. play();
  5231. } else {
  5232. raf = cancelAnimationFrame(raf);
  5233. }
  5234. }
  5235. return play;
  5236. })();
  5237. function handleVisibilityChange() {
  5238. if (document.hidden) {
  5239. for (var i = 0, len = activeInstances.length; i < len; i++) {
  5240. activeInstance[i].pause();
  5241. }
  5242. pausedInstances = activeInstances.slice(0);
  5243. activeInstances = [];
  5244. } else {
  5245. for (var i$1 = 0, len$1 = pausedInstances.length; i$1 < len$1; i$1++) {
  5246. pausedInstances[i$1].play();
  5247. }
  5248. }
  5249. }
  5250. document.addEventListener('visibilitychange', handleVisibilityChange);
  5251. // Public Instance
  5252. function anime(params) {
  5253. if ( params === void 0 ) params = {};
  5254. var startTime = 0, lastTime = 0, now = 0;
  5255. var children, childrenLength = 0;
  5256. var resolve = null;
  5257. function makePromise() {
  5258. return window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
  5259. }
  5260. var promise = makePromise();
  5261. var instance = createNewInstance(params);
  5262. function toggleInstanceDirection() {
  5263. instance.reversed = !instance.reversed;
  5264. for (var i = 0, len = children.length; i < len; i++) {
  5265. children[i].reversed = instance.reversed;
  5266. }
  5267. }
  5268. function adjustTime(time) {
  5269. return instance.reversed ? instance.duration - time : time;
  5270. }
  5271. function resetTime() {
  5272. startTime = 0;
  5273. lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
  5274. }
  5275. function seekCild(time, child) {
  5276. if (child) { child.seek(time - child.timelineOffset); }
  5277. }
  5278. function syncInstanceChildren(time) {
  5279. if (!instance.reversePlayback) {
  5280. for (var i = 0; i < childrenLength; i++) { seekCild(time, children[i]); }
  5281. } else {
  5282. for (var i$1 = childrenLength; i$1--;) { seekCild(time, children[i$1]); }
  5283. }
  5284. }
  5285. function setAnimationsProgress(insTime) {
  5286. var i = 0;
  5287. var animations = instance.animations;
  5288. var animationsLength = animations.length;
  5289. while (i < animationsLength) {
  5290. var anim = animations[i];
  5291. var animatable = anim.animatable;
  5292. var tweens = anim.tweens;
  5293. var tweenLength = tweens.length - 1;
  5294. var tween = tweens[tweenLength];
  5295. // Only check for keyframes if there is more than one tween
  5296. if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
  5297. var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
  5298. var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
  5299. var strings = tween.to.strings;
  5300. var round = tween.round;
  5301. var numbers = [];
  5302. var toNumbersLength = tween.to.numbers.length;
  5303. var progress = (void 0);
  5304. for (var n = 0; n < toNumbersLength; n++) {
  5305. var value = (void 0);
  5306. var toNumber = tween.to.numbers[n];
  5307. var fromNumber = tween.from.numbers[n] || 0;
  5308. if (!tween.isPath) {
  5309. value = fromNumber + (eased * (toNumber - fromNumber));
  5310. } else {
  5311. value = getPathProgress(tween.value, eased * toNumber);
  5312. }
  5313. if (round) {
  5314. if (!(tween.isColor && n > 2)) {
  5315. value = Math.round(value * round) / round;
  5316. }
  5317. }
  5318. numbers.push(value);
  5319. }
  5320. // Manual Array.reduce for better performances
  5321. var stringsLength = strings.length;
  5322. if (!stringsLength) {
  5323. progress = numbers[0];
  5324. } else {
  5325. progress = strings[0];
  5326. for (var s = 0; s < stringsLength; s++) {
  5327. var a = strings[s];
  5328. var b = strings[s + 1];
  5329. var n$1 = numbers[s];
  5330. if (!isNaN(n$1)) {
  5331. if (!b) {
  5332. progress += n$1 + ' ';
  5333. } else {
  5334. progress += n$1 + b;
  5335. }
  5336. }
  5337. }
  5338. }
  5339. setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms);
  5340. anim.currentValue = progress;
  5341. i++;
  5342. }
  5343. }
  5344. function setCallback(cb) {
  5345. if (instance[cb] && !instance.passThrough) { instance[cb](instance); }
  5346. }
  5347. function countIteration() {
  5348. if (instance.remaining && instance.remaining !== true) {
  5349. instance.remaining--;
  5350. }
  5351. }
  5352. function setInstanceProgress(engineTime) {
  5353. var insDuration = instance.duration;
  5354. var insDelay = instance.delay;
  5355. var insEndDelay = insDuration - instance.endDelay;
  5356. var insTime = adjustTime(engineTime);
  5357. instance.progress = minMax((insTime / insDuration) * 100, 0, 100);
  5358. instance.reversePlayback = insTime < instance.currentTime;
  5359. if (children) { syncInstanceChildren(insTime); }
  5360. if (!instance.began && instance.currentTime > 0) {
  5361. instance.began = true;
  5362. setCallback('begin');
  5363. setCallback('loopBegin');
  5364. }
  5365. if (insTime <= insDelay && instance.currentTime !== 0) {
  5366. setAnimationsProgress(0);
  5367. }
  5368. if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) {
  5369. setAnimationsProgress(insDuration);
  5370. }
  5371. if (insTime > insDelay && insTime < insEndDelay) {
  5372. if (!instance.changeBegan) {
  5373. instance.changeBegan = true;
  5374. instance.changeCompleted = false;
  5375. setCallback('changeBegin');
  5376. }
  5377. setCallback('change');
  5378. setAnimationsProgress(insTime);
  5379. } else {
  5380. if (instance.changeBegan) {
  5381. instance.changeCompleted = true;
  5382. instance.changeBegan = false;
  5383. setCallback('changeComplete');
  5384. }
  5385. }
  5386. instance.currentTime = minMax(insTime, 0, insDuration);
  5387. if (instance.began) { setCallback('update'); }
  5388. if (engineTime >= insDuration) {
  5389. lastTime = 0;
  5390. countIteration();
  5391. if (instance.remaining) {
  5392. startTime = now;
  5393. setCallback('loopComplete');
  5394. setCallback('loopBegin');
  5395. if (instance.direction === 'alternate') { toggleInstanceDirection(); }
  5396. } else {
  5397. instance.paused = true;
  5398. if (!instance.completed) {
  5399. instance.completed = true;
  5400. setCallback('loopComplete');
  5401. setCallback('complete');
  5402. if ('Promise' in window) {
  5403. resolve();
  5404. promise = makePromise();
  5405. }
  5406. }
  5407. }
  5408. }
  5409. }
  5410. instance.reset = function() {
  5411. var direction = instance.direction;
  5412. instance.passThrough = false;
  5413. instance.currentTime = 0;
  5414. instance.progress = 0;
  5415. instance.paused = true;
  5416. instance.began = false;
  5417. instance.changeBegan = false;
  5418. instance.completed = false;
  5419. instance.changeCompleted = false;
  5420. instance.reversePlayback = false;
  5421. instance.reversed = direction === 'reverse';
  5422. instance.remaining = instance.loop;
  5423. children = instance.children;
  5424. childrenLength = children.length;
  5425. for (var i = childrenLength; i--;) { instance.children[i].reset(); }
  5426. if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; }
  5427. setAnimationsProgress(0);
  5428. };
  5429. // Set Value helper
  5430. instance.set = function(targets, properties) {
  5431. setTargetsValue(targets, properties);
  5432. return instance;
  5433. };
  5434. instance.tick = function(t) {
  5435. now = t;
  5436. if (!startTime) { startTime = now; }
  5437. setInstanceProgress((now + (lastTime - startTime)) * anime.speed);
  5438. };
  5439. instance.seek = function(time) {
  5440. setInstanceProgress(adjustTime(time));
  5441. };
  5442. instance.pause = function() {
  5443. instance.paused = true;
  5444. resetTime();
  5445. };
  5446. instance.play = function() {
  5447. if (!instance.paused) { return; }
  5448. instance.paused = false;
  5449. activeInstances.push(instance);
  5450. resetTime();
  5451. if (!raf) { engine(); }
  5452. };
  5453. instance.reverse = function() {
  5454. toggleInstanceDirection();
  5455. resetTime();
  5456. };
  5457. instance.restart = function() {
  5458. instance.reset();
  5459. instance.play();
  5460. };
  5461. instance.finished = promise;
  5462. instance.reset();
  5463. if (instance.autoplay) { instance.play(); }
  5464. return instance;
  5465. }
  5466. // Remove targets from animation
  5467. function removeTargetsFromAnimations(targetsArray, animations) {
  5468. for (var a = animations.length; a--;) {
  5469. if (arrayContains(targetsArray, animations[a].animatable.target)) {
  5470. animations.splice(a, 1);
  5471. }
  5472. }
  5473. }
  5474. function removeTargets(targets) {
  5475. var targetsArray = parseTargets(targets);
  5476. for (var i = activeInstances.length; i--;) {
  5477. var instance = activeInstances[i];
  5478. var animations = instance.animations;
  5479. var children = instance.children;
  5480. removeTargetsFromAnimations(targetsArray, animations);
  5481. for (var c = children.length; c--;) {
  5482. var child = children[c];
  5483. var childAnimations = child.animations;
  5484. removeTargetsFromAnimations(targetsArray, childAnimations);
  5485. if (!childAnimations.length && !child.children.length) { children.splice(c, 1); }
  5486. }
  5487. if (!animations.length && !children.length) { instance.pause(); }
  5488. }
  5489. }
  5490. // Stagger helpers
  5491. function stagger(val, params) {
  5492. if ( params === void 0 ) params = {};
  5493. var direction = params.direction || 'normal';
  5494. var easing = params.easing ? parseEasings(params.easing) : null;
  5495. var grid = params.grid;
  5496. var axis = params.axis;
  5497. var fromIndex = params.from || 0;
  5498. var fromFirst = fromIndex === 'first';
  5499. var fromCenter = fromIndex === 'center';
  5500. var fromLast = fromIndex === 'last';
  5501. var isRange = is.arr(val);
  5502. var val1 = isRange ? parseFloat(val[0]) : parseFloat(val);
  5503. var val2 = isRange ? parseFloat(val[1]) : 0;
  5504. var unit = getUnit(isRange ? val[1] : val) || 0;
  5505. var start = params.start || 0 + (isRange ? val1 : 0);
  5506. var values = [];
  5507. var maxValue = 0;
  5508. return function (el, i, t) {
  5509. if (fromFirst) { fromIndex = 0; }
  5510. if (fromCenter) { fromIndex = (t - 1) / 2; }
  5511. if (fromLast) { fromIndex = t - 1; }
  5512. if (!values.length) {
  5513. for (var index = 0; index < t; index++) {
  5514. if (!grid) {
  5515. values.push(Math.abs(fromIndex - index));
  5516. } else {
  5517. var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2;
  5518. var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2;
  5519. var toX = index%grid[0];
  5520. var toY = Math.floor(index/grid[0]);
  5521. var distanceX = fromX - toX;
  5522. var distanceY = fromY - toY;
  5523. var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
  5524. if (axis === 'x') { value = -distanceX; }
  5525. if (axis === 'y') { value = -distanceY; }
  5526. values.push(value);
  5527. }
  5528. maxValue = Math.max.apply(Math, values);
  5529. }
  5530. if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); }
  5531. if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); }
  5532. }
  5533. var spacing = isRange ? (val2 - val1) / maxValue : val1;
  5534. return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit;
  5535. }
  5536. }
  5537. // Timeline
  5538. function timeline(params) {
  5539. if ( params === void 0 ) params = {};
  5540. var tl = anime(params);
  5541. tl.duration = 0;
  5542. tl.add = function(instanceParams, timelineOffset) {
  5543. var tlIndex = activeInstances.indexOf(tl);
  5544. var children = tl.children;
  5545. if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); }
  5546. function passThrough(ins) { ins.passThrough = true; }
  5547. for (var i = 0; i < children.length; i++) { passThrough(children[i]); }
  5548. var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params));
  5549. insParams.targets = insParams.targets || params.targets;
  5550. var tlDuration = tl.duration;
  5551. insParams.autoplay = false;
  5552. insParams.direction = tl.direction;
  5553. insParams.timelineOffset = is.und(timelineOffset) ? tlDuration : getRelativeValue(timelineOffset, tlDuration);
  5554. passThrough(tl);
  5555. tl.seek(insParams.timelineOffset);
  5556. var ins = anime(insParams);
  5557. passThrough(ins);
  5558. children.push(ins);
  5559. var timings = getInstanceTimings(children, params);
  5560. tl.delay = timings.delay;
  5561. tl.endDelay = timings.endDelay;
  5562. tl.duration = timings.duration;
  5563. tl.seek(0);
  5564. tl.reset();
  5565. if (tl.autoplay) { tl.play(); }
  5566. return tl;
  5567. };
  5568. return tl;
  5569. }
  5570. anime.version = '3.0.0';
  5571. anime.speed = 1;
  5572. anime.running = activeInstances;
  5573. anime.remove = removeTargets;
  5574. anime.get = getOriginalTargetValue;
  5575. anime.set = setTargetsValue;
  5576. anime.convertPx = convertPxToUnit;
  5577. anime.path = getPath;
  5578. anime.setDashoffset = setDashoffset;
  5579. anime.stagger = stagger;
  5580. anime.timeline = timeline;
  5581. anime.easing = parseEasings;
  5582. anime.penner = penner;
  5583. anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
  5584. module.exports = anime;
  5585. },{}],57:[function(_dereq_,module,exports){
  5586. (function (global, factory) {
  5587. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5588. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5589. (global = global || self, factory(global.THREE = {}));
  5590. }(this, (function (exports) { 'use strict';
  5591. // Polyfills
  5592. if ( Number.EPSILON === undefined ) {
  5593. Number.EPSILON = Math.pow( 2, - 52 );
  5594. }
  5595. if ( Number.isInteger === undefined ) {
  5596. // Missing in IE
  5597. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  5598. Number.isInteger = function ( value ) {
  5599. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  5600. };
  5601. }
  5602. //
  5603. if ( Math.sign === undefined ) {
  5604. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  5605. Math.sign = function ( x ) {
  5606. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  5607. };
  5608. }
  5609. if ( 'name' in Function.prototype === false ) {
  5610. // Missing in IE
  5611. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  5612. Object.defineProperty( Function.prototype, 'name', {
  5613. get: function () {
  5614. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  5615. }
  5616. } );
  5617. }
  5618. if ( Object.assign === undefined ) {
  5619. // Missing in IE
  5620. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  5621. Object.assign = function ( target ) {
  5622. if ( target === undefined || target === null ) {
  5623. throw new TypeError( 'Cannot convert undefined or null to object' );
  5624. }
  5625. var output = Object( target );
  5626. for ( var index = 1; index < arguments.length; index ++ ) {
  5627. var source = arguments[ index ];
  5628. if ( source !== undefined && source !== null ) {
  5629. for ( var nextKey in source ) {
  5630. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  5631. output[ nextKey ] = source[ nextKey ];
  5632. }
  5633. }
  5634. }
  5635. }
  5636. return output;
  5637. };
  5638. }
  5639. var REVISION = '119';
  5640. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  5641. var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  5642. var CullFaceNone = 0;
  5643. var CullFaceBack = 1;
  5644. var CullFaceFront = 2;
  5645. var CullFaceFrontBack = 3;
  5646. var BasicShadowMap = 0;
  5647. var PCFShadowMap = 1;
  5648. var PCFSoftShadowMap = 2;
  5649. var VSMShadowMap = 3;
  5650. var FrontSide = 0;
  5651. var BackSide = 1;
  5652. var DoubleSide = 2;
  5653. var FlatShading = 1;
  5654. var SmoothShading = 2;
  5655. var NoBlending = 0;
  5656. var NormalBlending = 1;
  5657. var AdditiveBlending = 2;
  5658. var SubtractiveBlending = 3;
  5659. var MultiplyBlending = 4;
  5660. var CustomBlending = 5;
  5661. var AddEquation = 100;
  5662. var SubtractEquation = 101;
  5663. var ReverseSubtractEquation = 102;
  5664. var MinEquation = 103;
  5665. var MaxEquation = 104;
  5666. var ZeroFactor = 200;
  5667. var OneFactor = 201;
  5668. var SrcColorFactor = 202;
  5669. var OneMinusSrcColorFactor = 203;
  5670. var SrcAlphaFactor = 204;
  5671. var OneMinusSrcAlphaFactor = 205;
  5672. var DstAlphaFactor = 206;
  5673. var OneMinusDstAlphaFactor = 207;
  5674. var DstColorFactor = 208;
  5675. var OneMinusDstColorFactor = 209;
  5676. var SrcAlphaSaturateFactor = 210;
  5677. var NeverDepth = 0;
  5678. var AlwaysDepth = 1;
  5679. var LessDepth = 2;
  5680. var LessEqualDepth = 3;
  5681. var EqualDepth = 4;
  5682. var GreaterEqualDepth = 5;
  5683. var GreaterDepth = 6;
  5684. var NotEqualDepth = 7;
  5685. var MultiplyOperation = 0;
  5686. var MixOperation = 1;
  5687. var AddOperation = 2;
  5688. var NoToneMapping = 0;
  5689. var LinearToneMapping = 1;
  5690. var ReinhardToneMapping = 2;
  5691. var CineonToneMapping = 3;
  5692. var ACESFilmicToneMapping = 4;
  5693. var CustomToneMapping = 5;
  5694. var UVMapping = 300;
  5695. var CubeReflectionMapping = 301;
  5696. var CubeRefractionMapping = 302;
  5697. var EquirectangularReflectionMapping = 303;
  5698. var EquirectangularRefractionMapping = 304;
  5699. var CubeUVReflectionMapping = 306;
  5700. var CubeUVRefractionMapping = 307;
  5701. var RepeatWrapping = 1000;
  5702. var ClampToEdgeWrapping = 1001;
  5703. var MirroredRepeatWrapping = 1002;
  5704. var NearestFilter = 1003;
  5705. var NearestMipmapNearestFilter = 1004;
  5706. var NearestMipMapNearestFilter = 1004;
  5707. var NearestMipmapLinearFilter = 1005;
  5708. var NearestMipMapLinearFilter = 1005;
  5709. var LinearFilter = 1006;
  5710. var LinearMipmapNearestFilter = 1007;
  5711. var LinearMipMapNearestFilter = 1007;
  5712. var LinearMipmapLinearFilter = 1008;
  5713. var LinearMipMapLinearFilter = 1008;
  5714. var UnsignedByteType = 1009;
  5715. var ByteType = 1010;
  5716. var ShortType = 1011;
  5717. var UnsignedShortType = 1012;
  5718. var IntType = 1013;
  5719. var UnsignedIntType = 1014;
  5720. var FloatType = 1015;
  5721. var HalfFloatType = 1016;
  5722. var UnsignedShort4444Type = 1017;
  5723. var UnsignedShort5551Type = 1018;
  5724. var UnsignedShort565Type = 1019;
  5725. var UnsignedInt248Type = 1020;
  5726. var AlphaFormat = 1021;
  5727. var RGBFormat = 1022;
  5728. var RGBAFormat = 1023;
  5729. var LuminanceFormat = 1024;
  5730. var LuminanceAlphaFormat = 1025;
  5731. var RGBEFormat = RGBAFormat;
  5732. var DepthFormat = 1026;
  5733. var DepthStencilFormat = 1027;
  5734. var RedFormat = 1028;
  5735. var RedIntegerFormat = 1029;
  5736. var RGFormat = 1030;
  5737. var RGIntegerFormat = 1031;
  5738. var RGBIntegerFormat = 1032;
  5739. var RGBAIntegerFormat = 1033;
  5740. var RGB_S3TC_DXT1_Format = 33776;
  5741. var RGBA_S3TC_DXT1_Format = 33777;
  5742. var RGBA_S3TC_DXT3_Format = 33778;
  5743. var RGBA_S3TC_DXT5_Format = 33779;
  5744. var RGB_PVRTC_4BPPV1_Format = 35840;
  5745. var RGB_PVRTC_2BPPV1_Format = 35841;
  5746. var RGBA_PVRTC_4BPPV1_Format = 35842;
  5747. var RGBA_PVRTC_2BPPV1_Format = 35843;
  5748. var RGB_ETC1_Format = 36196;
  5749. var RGB_ETC2_Format = 37492;
  5750. var RGBA_ETC2_EAC_Format = 37496;
  5751. var RGBA_ASTC_4x4_Format = 37808;
  5752. var RGBA_ASTC_5x4_Format = 37809;
  5753. var RGBA_ASTC_5x5_Format = 37810;
  5754. var RGBA_ASTC_6x5_Format = 37811;
  5755. var RGBA_ASTC_6x6_Format = 37812;
  5756. var RGBA_ASTC_8x5_Format = 37813;
  5757. var RGBA_ASTC_8x6_Format = 37814;
  5758. var RGBA_ASTC_8x8_Format = 37815;
  5759. var RGBA_ASTC_10x5_Format = 37816;
  5760. var RGBA_ASTC_10x6_Format = 37817;
  5761. var RGBA_ASTC_10x8_Format = 37818;
  5762. var RGBA_ASTC_10x10_Format = 37819;
  5763. var RGBA_ASTC_12x10_Format = 37820;
  5764. var RGBA_ASTC_12x12_Format = 37821;
  5765. var RGBA_BPTC_Format = 36492;
  5766. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  5767. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  5768. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  5769. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  5770. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  5771. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  5772. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  5773. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  5774. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  5775. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  5776. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  5777. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  5778. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  5779. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  5780. var LoopOnce = 2200;
  5781. var LoopRepeat = 2201;
  5782. var LoopPingPong = 2202;
  5783. var InterpolateDiscrete = 2300;
  5784. var InterpolateLinear = 2301;
  5785. var InterpolateSmooth = 2302;
  5786. var ZeroCurvatureEnding = 2400;
  5787. var ZeroSlopeEnding = 2401;
  5788. var WrapAroundEnding = 2402;
  5789. var NormalAnimationBlendMode = 2500;
  5790. var AdditiveAnimationBlendMode = 2501;
  5791. var TrianglesDrawMode = 0;
  5792. var TriangleStripDrawMode = 1;
  5793. var TriangleFanDrawMode = 2;
  5794. var LinearEncoding = 3000;
  5795. var sRGBEncoding = 3001;
  5796. var GammaEncoding = 3007;
  5797. var RGBEEncoding = 3002;
  5798. var LogLuvEncoding = 3003;
  5799. var RGBM7Encoding = 3004;
  5800. var RGBM16Encoding = 3005;
  5801. var RGBDEncoding = 3006;
  5802. var BasicDepthPacking = 3200;
  5803. var RGBADepthPacking = 3201;
  5804. var TangentSpaceNormalMap = 0;
  5805. var ObjectSpaceNormalMap = 1;
  5806. var ZeroStencilOp = 0;
  5807. var KeepStencilOp = 7680;
  5808. var ReplaceStencilOp = 7681;
  5809. var IncrementStencilOp = 7682;
  5810. var DecrementStencilOp = 7683;
  5811. var IncrementWrapStencilOp = 34055;
  5812. var DecrementWrapStencilOp = 34056;
  5813. var InvertStencilOp = 5386;
  5814. var NeverStencilFunc = 512;
  5815. var LessStencilFunc = 513;
  5816. var EqualStencilFunc = 514;
  5817. var LessEqualStencilFunc = 515;
  5818. var GreaterStencilFunc = 516;
  5819. var NotEqualStencilFunc = 517;
  5820. var GreaterEqualStencilFunc = 518;
  5821. var AlwaysStencilFunc = 519;
  5822. var StaticDrawUsage = 35044;
  5823. var DynamicDrawUsage = 35048;
  5824. var StreamDrawUsage = 35040;
  5825. var StaticReadUsage = 35045;
  5826. var DynamicReadUsage = 35049;
  5827. var StreamReadUsage = 35041;
  5828. var StaticCopyUsage = 35046;
  5829. var DynamicCopyUsage = 35050;
  5830. var StreamCopyUsage = 35042;
  5831. /**
  5832. * https://github.com/mrdoob/eventdispatcher.js/
  5833. */
  5834. function EventDispatcher() {}
  5835. Object.assign( EventDispatcher.prototype, {
  5836. addEventListener: function ( type, listener ) {
  5837. if ( this._listeners === undefined ) { this._listeners = {}; }
  5838. var listeners = this._listeners;
  5839. if ( listeners[ type ] === undefined ) {
  5840. listeners[ type ] = [];
  5841. }
  5842. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  5843. listeners[ type ].push( listener );
  5844. }
  5845. },
  5846. hasEventListener: function ( type, listener ) {
  5847. if ( this._listeners === undefined ) { return false; }
  5848. var listeners = this._listeners;
  5849. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  5850. },
  5851. removeEventListener: function ( type, listener ) {
  5852. if ( this._listeners === undefined ) { return; }
  5853. var listeners = this._listeners;
  5854. var listenerArray = listeners[ type ];
  5855. if ( listenerArray !== undefined ) {
  5856. var index = listenerArray.indexOf( listener );
  5857. if ( index !== - 1 ) {
  5858. listenerArray.splice( index, 1 );
  5859. }
  5860. }
  5861. },
  5862. dispatchEvent: function ( event ) {
  5863. if ( this._listeners === undefined ) { return; }
  5864. var listeners = this._listeners;
  5865. var listenerArray = listeners[ event.type ];
  5866. if ( listenerArray !== undefined ) {
  5867. event.target = this;
  5868. // Make a copy, in case listeners are removed while iterating.
  5869. var array = listenerArray.slice( 0 );
  5870. for ( var i = 0, l = array.length; i < l; i ++ ) {
  5871. array[ i ].call( this, event );
  5872. }
  5873. }
  5874. }
  5875. } );
  5876. var _lut = [];
  5877. for ( var i = 0; i < 256; i ++ ) {
  5878. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  5879. }
  5880. var _seed = 1234567;
  5881. var MathUtils = {
  5882. DEG2RAD: Math.PI / 180,
  5883. RAD2DEG: 180 / Math.PI,
  5884. generateUUID: function () {
  5885. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  5886. var d0 = Math.random() * 0xffffffff | 0;
  5887. var d1 = Math.random() * 0xffffffff | 0;
  5888. var d2 = Math.random() * 0xffffffff | 0;
  5889. var d3 = Math.random() * 0xffffffff | 0;
  5890. var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  5891. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  5892. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  5893. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  5894. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  5895. return uuid.toUpperCase();
  5896. },
  5897. clamp: function ( value, min, max ) {
  5898. return Math.max( min, Math.min( max, value ) );
  5899. },
  5900. // compute euclidian modulo of m % n
  5901. // https://en.wikipedia.org/wiki/Modulo_operation
  5902. euclideanModulo: function ( n, m ) {
  5903. return ( ( n % m ) + m ) % m;
  5904. },
  5905. // Linear mapping from range <a1, a2> to range <b1, b2>
  5906. mapLinear: function ( x, a1, a2, b1, b2 ) {
  5907. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  5908. },
  5909. // https://en.wikipedia.org/wiki/Linear_interpolation
  5910. lerp: function ( x, y, t ) {
  5911. return ( 1 - t ) * x + t * y;
  5912. },
  5913. // http://en.wikipedia.org/wiki/Smoothstep
  5914. smoothstep: function ( x, min, max ) {
  5915. if ( x <= min ) { return 0; }
  5916. if ( x >= max ) { return 1; }
  5917. x = ( x - min ) / ( max - min );
  5918. return x * x * ( 3 - 2 * x );
  5919. },
  5920. smootherstep: function ( x, min, max ) {
  5921. if ( x <= min ) { return 0; }
  5922. if ( x >= max ) { return 1; }
  5923. x = ( x - min ) / ( max - min );
  5924. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  5925. },
  5926. // Random integer from <low, high> interval
  5927. randInt: function ( low, high ) {
  5928. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  5929. },
  5930. // Random float from <low, high> interval
  5931. randFloat: function ( low, high ) {
  5932. return low + Math.random() * ( high - low );
  5933. },
  5934. // Random float from <-range/2, range/2> interval
  5935. randFloatSpread: function ( range ) {
  5936. return range * ( 0.5 - Math.random() );
  5937. },
  5938. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  5939. seededRandom: function ( s ) {
  5940. if ( s !== undefined ) { _seed = s % 2147483647; }
  5941. // Park-Miller algorithm
  5942. _seed = _seed * 16807 % 2147483647;
  5943. return ( _seed - 1 ) / 2147483646;
  5944. },
  5945. degToRad: function ( degrees ) {
  5946. return degrees * MathUtils.DEG2RAD;
  5947. },
  5948. radToDeg: function ( radians ) {
  5949. return radians * MathUtils.RAD2DEG;
  5950. },
  5951. isPowerOfTwo: function ( value ) {
  5952. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  5953. },
  5954. ceilPowerOfTwo: function ( value ) {
  5955. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  5956. },
  5957. floorPowerOfTwo: function ( value ) {
  5958. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  5959. },
  5960. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  5961. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  5962. // rotations are applied to the axes in the order specified by 'order'
  5963. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  5964. // angles are in radians
  5965. var cos = Math.cos;
  5966. var sin = Math.sin;
  5967. var c2 = cos( b / 2 );
  5968. var s2 = sin( b / 2 );
  5969. var c13 = cos( ( a + c ) / 2 );
  5970. var s13 = sin( ( a + c ) / 2 );
  5971. var c1_3 = cos( ( a - c ) / 2 );
  5972. var s1_3 = sin( ( a - c ) / 2 );
  5973. var c3_1 = cos( ( c - a ) / 2 );
  5974. var s3_1 = sin( ( c - a ) / 2 );
  5975. switch ( order ) {
  5976. case 'XYX':
  5977. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  5978. break;
  5979. case 'YZY':
  5980. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  5981. break;
  5982. case 'ZXZ':
  5983. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  5984. break;
  5985. case 'XZX':
  5986. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  5987. break;
  5988. case 'YXY':
  5989. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  5990. break;
  5991. case 'ZYZ':
  5992. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  5993. break;
  5994. default:
  5995. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  5996. }
  5997. }
  5998. };
  5999. function Vector2( x, y ) {
  6000. if ( x === void 0 ) x = 0;
  6001. if ( y === void 0 ) y = 0;
  6002. this.x = x;
  6003. this.y = y;
  6004. }
  6005. Object.defineProperties( Vector2.prototype, {
  6006. "width": {
  6007. get: function () {
  6008. return this.x;
  6009. },
  6010. set: function ( value ) {
  6011. this.x = value;
  6012. }
  6013. },
  6014. "height": {
  6015. get: function () {
  6016. return this.y;
  6017. },
  6018. set: function ( value ) {
  6019. this.y = value;
  6020. }
  6021. }
  6022. } );
  6023. Object.assign( Vector2.prototype, {
  6024. isVector2: true,
  6025. set: function ( x, y ) {
  6026. this.x = x;
  6027. this.y = y;
  6028. return this;
  6029. },
  6030. setScalar: function ( scalar ) {
  6031. this.x = scalar;
  6032. this.y = scalar;
  6033. return this;
  6034. },
  6035. setX: function ( x ) {
  6036. this.x = x;
  6037. return this;
  6038. },
  6039. setY: function ( y ) {
  6040. this.y = y;
  6041. return this;
  6042. },
  6043. setComponent: function ( index, value ) {
  6044. switch ( index ) {
  6045. case 0: this.x = value; break;
  6046. case 1: this.y = value; break;
  6047. default: throw new Error( 'index is out of range: ' + index );
  6048. }
  6049. return this;
  6050. },
  6051. getComponent: function ( index ) {
  6052. switch ( index ) {
  6053. case 0: return this.x;
  6054. case 1: return this.y;
  6055. default: throw new Error( 'index is out of range: ' + index );
  6056. }
  6057. },
  6058. clone: function () {
  6059. return new this.constructor( this.x, this.y );
  6060. },
  6061. copy: function ( v ) {
  6062. this.x = v.x;
  6063. this.y = v.y;
  6064. return this;
  6065. },
  6066. add: function ( v, w ) {
  6067. if ( w !== undefined ) {
  6068. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6069. return this.addVectors( v, w );
  6070. }
  6071. this.x += v.x;
  6072. this.y += v.y;
  6073. return this;
  6074. },
  6075. addScalar: function ( s ) {
  6076. this.x += s;
  6077. this.y += s;
  6078. return this;
  6079. },
  6080. addVectors: function ( a, b ) {
  6081. this.x = a.x + b.x;
  6082. this.y = a.y + b.y;
  6083. return this;
  6084. },
  6085. addScaledVector: function ( v, s ) {
  6086. this.x += v.x * s;
  6087. this.y += v.y * s;
  6088. return this;
  6089. },
  6090. sub: function ( v, w ) {
  6091. if ( w !== undefined ) {
  6092. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6093. return this.subVectors( v, w );
  6094. }
  6095. this.x -= v.x;
  6096. this.y -= v.y;
  6097. return this;
  6098. },
  6099. subScalar: function ( s ) {
  6100. this.x -= s;
  6101. this.y -= s;
  6102. return this;
  6103. },
  6104. subVectors: function ( a, b ) {
  6105. this.x = a.x - b.x;
  6106. this.y = a.y - b.y;
  6107. return this;
  6108. },
  6109. multiply: function ( v ) {
  6110. this.x *= v.x;
  6111. this.y *= v.y;
  6112. return this;
  6113. },
  6114. multiplyScalar: function ( scalar ) {
  6115. this.x *= scalar;
  6116. this.y *= scalar;
  6117. return this;
  6118. },
  6119. divide: function ( v ) {
  6120. this.x /= v.x;
  6121. this.y /= v.y;
  6122. return this;
  6123. },
  6124. divideScalar: function ( scalar ) {
  6125. return this.multiplyScalar( 1 / scalar );
  6126. },
  6127. applyMatrix3: function ( m ) {
  6128. var x = this.x, y = this.y;
  6129. var e = m.elements;
  6130. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  6131. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  6132. return this;
  6133. },
  6134. min: function ( v ) {
  6135. this.x = Math.min( this.x, v.x );
  6136. this.y = Math.min( this.y, v.y );
  6137. return this;
  6138. },
  6139. max: function ( v ) {
  6140. this.x = Math.max( this.x, v.x );
  6141. this.y = Math.max( this.y, v.y );
  6142. return this;
  6143. },
  6144. clamp: function ( min, max ) {
  6145. // assumes min < max, componentwise
  6146. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6147. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6148. return this;
  6149. },
  6150. clampScalar: function ( minVal, maxVal ) {
  6151. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6152. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6153. return this;
  6154. },
  6155. clampLength: function ( min, max ) {
  6156. var length = this.length();
  6157. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6158. },
  6159. floor: function () {
  6160. this.x = Math.floor( this.x );
  6161. this.y = Math.floor( this.y );
  6162. return this;
  6163. },
  6164. ceil: function () {
  6165. this.x = Math.ceil( this.x );
  6166. this.y = Math.ceil( this.y );
  6167. return this;
  6168. },
  6169. round: function () {
  6170. this.x = Math.round( this.x );
  6171. this.y = Math.round( this.y );
  6172. return this;
  6173. },
  6174. roundToZero: function () {
  6175. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6176. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6177. return this;
  6178. },
  6179. negate: function () {
  6180. this.x = - this.x;
  6181. this.y = - this.y;
  6182. return this;
  6183. },
  6184. dot: function ( v ) {
  6185. return this.x * v.x + this.y * v.y;
  6186. },
  6187. cross: function ( v ) {
  6188. return this.x * v.y - this.y * v.x;
  6189. },
  6190. lengthSq: function () {
  6191. return this.x * this.x + this.y * this.y;
  6192. },
  6193. length: function () {
  6194. return Math.sqrt( this.x * this.x + this.y * this.y );
  6195. },
  6196. manhattanLength: function () {
  6197. return Math.abs( this.x ) + Math.abs( this.y );
  6198. },
  6199. normalize: function () {
  6200. return this.divideScalar( this.length() || 1 );
  6201. },
  6202. angle: function () {
  6203. // computes the angle in radians with respect to the positive x-axis
  6204. var angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  6205. return angle;
  6206. },
  6207. distanceTo: function ( v ) {
  6208. return Math.sqrt( this.distanceToSquared( v ) );
  6209. },
  6210. distanceToSquared: function ( v ) {
  6211. var dx = this.x - v.x, dy = this.y - v.y;
  6212. return dx * dx + dy * dy;
  6213. },
  6214. manhattanDistanceTo: function ( v ) {
  6215. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  6216. },
  6217. setLength: function ( length ) {
  6218. return this.normalize().multiplyScalar( length );
  6219. },
  6220. lerp: function ( v, alpha ) {
  6221. this.x += ( v.x - this.x ) * alpha;
  6222. this.y += ( v.y - this.y ) * alpha;
  6223. return this;
  6224. },
  6225. lerpVectors: function ( v1, v2, alpha ) {
  6226. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6227. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6228. return this;
  6229. },
  6230. equals: function ( v ) {
  6231. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  6232. },
  6233. fromArray: function ( array, offset ) {
  6234. if ( offset === undefined ) { offset = 0; }
  6235. this.x = array[ offset ];
  6236. this.y = array[ offset + 1 ];
  6237. return this;
  6238. },
  6239. toArray: function ( array, offset ) {
  6240. if ( array === undefined ) { array = []; }
  6241. if ( offset === undefined ) { offset = 0; }
  6242. array[ offset ] = this.x;
  6243. array[ offset + 1 ] = this.y;
  6244. return array;
  6245. },
  6246. fromBufferAttribute: function ( attribute, index, offset ) {
  6247. if ( offset !== undefined ) {
  6248. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  6249. }
  6250. this.x = attribute.getX( index );
  6251. this.y = attribute.getY( index );
  6252. return this;
  6253. },
  6254. rotateAround: function ( center, angle ) {
  6255. var c = Math.cos( angle ), s = Math.sin( angle );
  6256. var x = this.x - center.x;
  6257. var y = this.y - center.y;
  6258. this.x = x * c - y * s + center.x;
  6259. this.y = x * s + y * c + center.y;
  6260. return this;
  6261. },
  6262. random: function () {
  6263. this.x = Math.random();
  6264. this.y = Math.random();
  6265. return this;
  6266. }
  6267. } );
  6268. function Matrix3() {
  6269. this.elements = [
  6270. 1, 0, 0,
  6271. 0, 1, 0,
  6272. 0, 0, 1
  6273. ];
  6274. if ( arguments.length > 0 ) {
  6275. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6276. }
  6277. }
  6278. Object.assign( Matrix3.prototype, {
  6279. isMatrix3: true,
  6280. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6281. var te = this.elements;
  6282. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6283. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6284. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6285. return this;
  6286. },
  6287. identity: function () {
  6288. this.set(
  6289. 1, 0, 0,
  6290. 0, 1, 0,
  6291. 0, 0, 1
  6292. );
  6293. return this;
  6294. },
  6295. clone: function () {
  6296. return new this.constructor().fromArray( this.elements );
  6297. },
  6298. copy: function ( m ) {
  6299. var te = this.elements;
  6300. var me = m.elements;
  6301. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6302. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6303. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6304. return this;
  6305. },
  6306. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6307. xAxis.setFromMatrix3Column( this, 0 );
  6308. yAxis.setFromMatrix3Column( this, 1 );
  6309. zAxis.setFromMatrix3Column( this, 2 );
  6310. return this;
  6311. },
  6312. setFromMatrix4: function ( m ) {
  6313. var me = m.elements;
  6314. this.set(
  6315. me[ 0 ], me[ 4 ], me[ 8 ],
  6316. me[ 1 ], me[ 5 ], me[ 9 ],
  6317. me[ 2 ], me[ 6 ], me[ 10 ]
  6318. );
  6319. return this;
  6320. },
  6321. multiply: function ( m ) {
  6322. return this.multiplyMatrices( this, m );
  6323. },
  6324. premultiply: function ( m ) {
  6325. return this.multiplyMatrices( m, this );
  6326. },
  6327. multiplyMatrices: function ( a, b ) {
  6328. var ae = a.elements;
  6329. var be = b.elements;
  6330. var te = this.elements;
  6331. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6332. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6333. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6334. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6335. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6336. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6337. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6338. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6339. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6340. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6341. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6342. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6343. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6344. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6345. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6346. return this;
  6347. },
  6348. multiplyScalar: function ( s ) {
  6349. var te = this.elements;
  6350. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6351. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6352. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6353. return this;
  6354. },
  6355. determinant: function () {
  6356. var te = this.elements;
  6357. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6358. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6359. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6360. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6361. },
  6362. getInverse: function ( matrix, throwOnDegenerate ) {
  6363. if ( throwOnDegenerate !== undefined ) {
  6364. console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." );
  6365. }
  6366. var me = matrix.elements,
  6367. te = this.elements,
  6368. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6369. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6370. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6371. t11 = n33 * n22 - n32 * n23,
  6372. t12 = n32 * n13 - n33 * n12,
  6373. t13 = n23 * n12 - n22 * n13,
  6374. det = n11 * t11 + n21 * t12 + n31 * t13;
  6375. if ( det === 0 ) { return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); }
  6376. var detInv = 1 / det;
  6377. te[ 0 ] = t11 * detInv;
  6378. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6379. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6380. te[ 3 ] = t12 * detInv;
  6381. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6382. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6383. te[ 6 ] = t13 * detInv;
  6384. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6385. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6386. return this;
  6387. },
  6388. transpose: function () {
  6389. var tmp;
  6390. var m = this.elements;
  6391. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6392. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6393. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6394. return this;
  6395. },
  6396. getNormalMatrix: function ( matrix4 ) {
  6397. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6398. },
  6399. transposeIntoArray: function ( r ) {
  6400. var m = this.elements;
  6401. r[ 0 ] = m[ 0 ];
  6402. r[ 1 ] = m[ 3 ];
  6403. r[ 2 ] = m[ 6 ];
  6404. r[ 3 ] = m[ 1 ];
  6405. r[ 4 ] = m[ 4 ];
  6406. r[ 5 ] = m[ 7 ];
  6407. r[ 6 ] = m[ 2 ];
  6408. r[ 7 ] = m[ 5 ];
  6409. r[ 8 ] = m[ 8 ];
  6410. return this;
  6411. },
  6412. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6413. var c = Math.cos( rotation );
  6414. var s = Math.sin( rotation );
  6415. this.set(
  6416. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6417. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6418. 0, 0, 1
  6419. );
  6420. },
  6421. scale: function ( sx, sy ) {
  6422. var te = this.elements;
  6423. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6424. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6425. return this;
  6426. },
  6427. rotate: function ( theta ) {
  6428. var c = Math.cos( theta );
  6429. var s = Math.sin( theta );
  6430. var te = this.elements;
  6431. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6432. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6433. te[ 0 ] = c * a11 + s * a21;
  6434. te[ 3 ] = c * a12 + s * a22;
  6435. te[ 6 ] = c * a13 + s * a23;
  6436. te[ 1 ] = - s * a11 + c * a21;
  6437. te[ 4 ] = - s * a12 + c * a22;
  6438. te[ 7 ] = - s * a13 + c * a23;
  6439. return this;
  6440. },
  6441. translate: function ( tx, ty ) {
  6442. var te = this.elements;
  6443. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6444. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6445. return this;
  6446. },
  6447. equals: function ( matrix ) {
  6448. var te = this.elements;
  6449. var me = matrix.elements;
  6450. for ( var i = 0; i < 9; i ++ ) {
  6451. if ( te[ i ] !== me[ i ] ) { return false; }
  6452. }
  6453. return true;
  6454. },
  6455. fromArray: function ( array, offset ) {
  6456. if ( offset === undefined ) { offset = 0; }
  6457. for ( var i = 0; i < 9; i ++ ) {
  6458. this.elements[ i ] = array[ i + offset ];
  6459. }
  6460. return this;
  6461. },
  6462. toArray: function ( array, offset ) {
  6463. if ( array === undefined ) { array = []; }
  6464. if ( offset === undefined ) { offset = 0; }
  6465. var te = this.elements;
  6466. array[ offset ] = te[ 0 ];
  6467. array[ offset + 1 ] = te[ 1 ];
  6468. array[ offset + 2 ] = te[ 2 ];
  6469. array[ offset + 3 ] = te[ 3 ];
  6470. array[ offset + 4 ] = te[ 4 ];
  6471. array[ offset + 5 ] = te[ 5 ];
  6472. array[ offset + 6 ] = te[ 6 ];
  6473. array[ offset + 7 ] = te[ 7 ];
  6474. array[ offset + 8 ] = te[ 8 ];
  6475. return array;
  6476. }
  6477. } );
  6478. var _canvas;
  6479. var ImageUtils = {
  6480. getDataURL: function ( image ) {
  6481. if ( /^data:/i.test( image.src ) ) {
  6482. return image.src;
  6483. }
  6484. if ( typeof HTMLCanvasElement == 'undefined' ) {
  6485. return image.src;
  6486. }
  6487. var canvas;
  6488. if ( image instanceof HTMLCanvasElement ) {
  6489. canvas = image;
  6490. } else {
  6491. if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); }
  6492. _canvas.width = image.width;
  6493. _canvas.height = image.height;
  6494. var context = _canvas.getContext( '2d' );
  6495. if ( image instanceof ImageData ) {
  6496. context.putImageData( image, 0, 0 );
  6497. } else {
  6498. context.drawImage( image, 0, 0, image.width, image.height );
  6499. }
  6500. canvas = _canvas;
  6501. }
  6502. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6503. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6504. } else {
  6505. return canvas.toDataURL( 'image/png' );
  6506. }
  6507. }
  6508. };
  6509. var textureId = 0;
  6510. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6511. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6512. this.uuid = MathUtils.generateUUID();
  6513. this.name = '';
  6514. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6515. this.mipmaps = [];
  6516. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6517. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6518. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6519. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6520. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  6521. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6522. this.format = format !== undefined ? format : RGBAFormat;
  6523. this.internalFormat = null;
  6524. this.type = type !== undefined ? type : UnsignedByteType;
  6525. this.offset = new Vector2( 0, 0 );
  6526. this.repeat = new Vector2( 1, 1 );
  6527. this.center = new Vector2( 0, 0 );
  6528. this.rotation = 0;
  6529. this.matrixAutoUpdate = true;
  6530. this.matrix = new Matrix3();
  6531. this.generateMipmaps = true;
  6532. this.premultiplyAlpha = false;
  6533. this.flipY = true;
  6534. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6535. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6536. //
  6537. // Also changing the encoding after already used by a Material will not automatically make the Material
  6538. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6539. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6540. this.version = 0;
  6541. this.onUpdate = null;
  6542. }
  6543. Texture.DEFAULT_IMAGE = undefined;
  6544. Texture.DEFAULT_MAPPING = UVMapping;
  6545. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6546. constructor: Texture,
  6547. isTexture: true,
  6548. updateMatrix: function () {
  6549. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  6550. },
  6551. clone: function () {
  6552. return new this.constructor().copy( this );
  6553. },
  6554. copy: function ( source ) {
  6555. this.name = source.name;
  6556. this.image = source.image;
  6557. this.mipmaps = source.mipmaps.slice( 0 );
  6558. this.mapping = source.mapping;
  6559. this.wrapS = source.wrapS;
  6560. this.wrapT = source.wrapT;
  6561. this.magFilter = source.magFilter;
  6562. this.minFilter = source.minFilter;
  6563. this.anisotropy = source.anisotropy;
  6564. this.format = source.format;
  6565. this.internalFormat = source.internalFormat;
  6566. this.type = source.type;
  6567. this.offset.copy( source.offset );
  6568. this.repeat.copy( source.repeat );
  6569. this.center.copy( source.center );
  6570. this.rotation = source.rotation;
  6571. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6572. this.matrix.copy( source.matrix );
  6573. this.generateMipmaps = source.generateMipmaps;
  6574. this.premultiplyAlpha = source.premultiplyAlpha;
  6575. this.flipY = source.flipY;
  6576. this.unpackAlignment = source.unpackAlignment;
  6577. this.encoding = source.encoding;
  6578. return this;
  6579. },
  6580. toJSON: function ( meta ) {
  6581. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6582. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6583. return meta.textures[ this.uuid ];
  6584. }
  6585. var output = {
  6586. metadata: {
  6587. version: 4.5,
  6588. type: 'Texture',
  6589. generator: 'Texture.toJSON'
  6590. },
  6591. uuid: this.uuid,
  6592. name: this.name,
  6593. mapping: this.mapping,
  6594. repeat: [ this.repeat.x, this.repeat.y ],
  6595. offset: [ this.offset.x, this.offset.y ],
  6596. center: [ this.center.x, this.center.y ],
  6597. rotation: this.rotation,
  6598. wrap: [ this.wrapS, this.wrapT ],
  6599. format: this.format,
  6600. type: this.type,
  6601. encoding: this.encoding,
  6602. minFilter: this.minFilter,
  6603. magFilter: this.magFilter,
  6604. anisotropy: this.anisotropy,
  6605. flipY: this.flipY,
  6606. premultiplyAlpha: this.premultiplyAlpha,
  6607. unpackAlignment: this.unpackAlignment
  6608. };
  6609. if ( this.image !== undefined ) {
  6610. // TODO: Move to THREE.Image
  6611. var image = this.image;
  6612. if ( image.uuid === undefined ) {
  6613. image.uuid = MathUtils.generateUUID(); // UGH
  6614. }
  6615. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6616. var url;
  6617. if ( Array.isArray( image ) ) {
  6618. // process array of images e.g. CubeTexture
  6619. url = [];
  6620. for ( var i = 0, l = image.length; i < l; i ++ ) {
  6621. url.push( ImageUtils.getDataURL( image[ i ] ) );
  6622. }
  6623. } else {
  6624. // process single image
  6625. url = ImageUtils.getDataURL( image );
  6626. }
  6627. meta.images[ image.uuid ] = {
  6628. uuid: image.uuid,
  6629. url: url
  6630. };
  6631. }
  6632. output.image = image.uuid;
  6633. }
  6634. if ( ! isRootObject ) {
  6635. meta.textures[ this.uuid ] = output;
  6636. }
  6637. return output;
  6638. },
  6639. dispose: function () {
  6640. this.dispatchEvent( { type: 'dispose' } );
  6641. },
  6642. transformUv: function ( uv ) {
  6643. if ( this.mapping !== UVMapping ) { return uv; }
  6644. uv.applyMatrix3( this.matrix );
  6645. if ( uv.x < 0 || uv.x > 1 ) {
  6646. switch ( this.wrapS ) {
  6647. case RepeatWrapping:
  6648. uv.x = uv.x - Math.floor( uv.x );
  6649. break;
  6650. case ClampToEdgeWrapping:
  6651. uv.x = uv.x < 0 ? 0 : 1;
  6652. break;
  6653. case MirroredRepeatWrapping:
  6654. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6655. uv.x = Math.ceil( uv.x ) - uv.x;
  6656. } else {
  6657. uv.x = uv.x - Math.floor( uv.x );
  6658. }
  6659. break;
  6660. }
  6661. }
  6662. if ( uv.y < 0 || uv.y > 1 ) {
  6663. switch ( this.wrapT ) {
  6664. case RepeatWrapping:
  6665. uv.y = uv.y - Math.floor( uv.y );
  6666. break;
  6667. case ClampToEdgeWrapping:
  6668. uv.y = uv.y < 0 ? 0 : 1;
  6669. break;
  6670. case MirroredRepeatWrapping:
  6671. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6672. uv.y = Math.ceil( uv.y ) - uv.y;
  6673. } else {
  6674. uv.y = uv.y - Math.floor( uv.y );
  6675. }
  6676. break;
  6677. }
  6678. }
  6679. if ( this.flipY ) {
  6680. uv.y = 1 - uv.y;
  6681. }
  6682. return uv;
  6683. }
  6684. } );
  6685. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6686. set: function ( value ) {
  6687. if ( value === true ) { this.version ++; }
  6688. }
  6689. } );
  6690. function Vector4( x, y, z, w ) {
  6691. if ( x === void 0 ) x = 0;
  6692. if ( y === void 0 ) y = 0;
  6693. if ( z === void 0 ) z = 0;
  6694. if ( w === void 0 ) w = 1;
  6695. this.x = x;
  6696. this.y = y;
  6697. this.z = z;
  6698. this.w = w;
  6699. }
  6700. Object.defineProperties( Vector4.prototype, {
  6701. "width": {
  6702. get: function () {
  6703. return this.z;
  6704. },
  6705. set: function ( value ) {
  6706. this.z = value;
  6707. }
  6708. },
  6709. "height": {
  6710. get: function () {
  6711. return this.w;
  6712. },
  6713. set: function ( value ) {
  6714. this.w = value;
  6715. }
  6716. }
  6717. } );
  6718. Object.assign( Vector4.prototype, {
  6719. isVector4: true,
  6720. set: function ( x, y, z, w ) {
  6721. this.x = x;
  6722. this.y = y;
  6723. this.z = z;
  6724. this.w = w;
  6725. return this;
  6726. },
  6727. setScalar: function ( scalar ) {
  6728. this.x = scalar;
  6729. this.y = scalar;
  6730. this.z = scalar;
  6731. this.w = scalar;
  6732. return this;
  6733. },
  6734. setX: function ( x ) {
  6735. this.x = x;
  6736. return this;
  6737. },
  6738. setY: function ( y ) {
  6739. this.y = y;
  6740. return this;
  6741. },
  6742. setZ: function ( z ) {
  6743. this.z = z;
  6744. return this;
  6745. },
  6746. setW: function ( w ) {
  6747. this.w = w;
  6748. return this;
  6749. },
  6750. setComponent: function ( index, value ) {
  6751. switch ( index ) {
  6752. case 0: this.x = value; break;
  6753. case 1: this.y = value; break;
  6754. case 2: this.z = value; break;
  6755. case 3: this.w = value; break;
  6756. default: throw new Error( 'index is out of range: ' + index );
  6757. }
  6758. return this;
  6759. },
  6760. getComponent: function ( index ) {
  6761. switch ( index ) {
  6762. case 0: return this.x;
  6763. case 1: return this.y;
  6764. case 2: return this.z;
  6765. case 3: return this.w;
  6766. default: throw new Error( 'index is out of range: ' + index );
  6767. }
  6768. },
  6769. clone: function () {
  6770. return new this.constructor( this.x, this.y, this.z, this.w );
  6771. },
  6772. copy: function ( v ) {
  6773. this.x = v.x;
  6774. this.y = v.y;
  6775. this.z = v.z;
  6776. this.w = ( v.w !== undefined ) ? v.w : 1;
  6777. return this;
  6778. },
  6779. add: function ( v, w ) {
  6780. if ( w !== undefined ) {
  6781. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6782. return this.addVectors( v, w );
  6783. }
  6784. this.x += v.x;
  6785. this.y += v.y;
  6786. this.z += v.z;
  6787. this.w += v.w;
  6788. return this;
  6789. },
  6790. addScalar: function ( s ) {
  6791. this.x += s;
  6792. this.y += s;
  6793. this.z += s;
  6794. this.w += s;
  6795. return this;
  6796. },
  6797. addVectors: function ( a, b ) {
  6798. this.x = a.x + b.x;
  6799. this.y = a.y + b.y;
  6800. this.z = a.z + b.z;
  6801. this.w = a.w + b.w;
  6802. return this;
  6803. },
  6804. addScaledVector: function ( v, s ) {
  6805. this.x += v.x * s;
  6806. this.y += v.y * s;
  6807. this.z += v.z * s;
  6808. this.w += v.w * s;
  6809. return this;
  6810. },
  6811. sub: function ( v, w ) {
  6812. if ( w !== undefined ) {
  6813. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6814. return this.subVectors( v, w );
  6815. }
  6816. this.x -= v.x;
  6817. this.y -= v.y;
  6818. this.z -= v.z;
  6819. this.w -= v.w;
  6820. return this;
  6821. },
  6822. subScalar: function ( s ) {
  6823. this.x -= s;
  6824. this.y -= s;
  6825. this.z -= s;
  6826. this.w -= s;
  6827. return this;
  6828. },
  6829. subVectors: function ( a, b ) {
  6830. this.x = a.x - b.x;
  6831. this.y = a.y - b.y;
  6832. this.z = a.z - b.z;
  6833. this.w = a.w - b.w;
  6834. return this;
  6835. },
  6836. multiplyScalar: function ( scalar ) {
  6837. this.x *= scalar;
  6838. this.y *= scalar;
  6839. this.z *= scalar;
  6840. this.w *= scalar;
  6841. return this;
  6842. },
  6843. applyMatrix4: function ( m ) {
  6844. var x = this.x, y = this.y, z = this.z, w = this.w;
  6845. var e = m.elements;
  6846. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6847. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6848. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6849. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6850. return this;
  6851. },
  6852. divideScalar: function ( scalar ) {
  6853. return this.multiplyScalar( 1 / scalar );
  6854. },
  6855. setAxisAngleFromQuaternion: function ( q ) {
  6856. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6857. // q is assumed to be normalized
  6858. this.w = 2 * Math.acos( q.w );
  6859. var s = Math.sqrt( 1 - q.w * q.w );
  6860. if ( s < 0.0001 ) {
  6861. this.x = 1;
  6862. this.y = 0;
  6863. this.z = 0;
  6864. } else {
  6865. this.x = q.x / s;
  6866. this.y = q.y / s;
  6867. this.z = q.z / s;
  6868. }
  6869. return this;
  6870. },
  6871. setAxisAngleFromRotationMatrix: function ( m ) {
  6872. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6873. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6874. var angle, x, y, z; // variables for result
  6875. var epsilon = 0.01, // margin to allow for rounding errors
  6876. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6877. te = m.elements,
  6878. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6879. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6880. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6881. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6882. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6883. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6884. // singularity found
  6885. // first check for identity matrix which must have +1 for all terms
  6886. // in leading diagonal and zero in other terms
  6887. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6888. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6889. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6890. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6891. // this singularity is identity matrix so angle = 0
  6892. this.set( 1, 0, 0, 0 );
  6893. return this; // zero angle, arbitrary axis
  6894. }
  6895. // otherwise this singularity is angle = 180
  6896. angle = Math.PI;
  6897. var xx = ( m11 + 1 ) / 2;
  6898. var yy = ( m22 + 1 ) / 2;
  6899. var zz = ( m33 + 1 ) / 2;
  6900. var xy = ( m12 + m21 ) / 4;
  6901. var xz = ( m13 + m31 ) / 4;
  6902. var yz = ( m23 + m32 ) / 4;
  6903. if ( ( xx > yy ) && ( xx > zz ) ) {
  6904. // m11 is the largest diagonal term
  6905. if ( xx < epsilon ) {
  6906. x = 0;
  6907. y = 0.707106781;
  6908. z = 0.707106781;
  6909. } else {
  6910. x = Math.sqrt( xx );
  6911. y = xy / x;
  6912. z = xz / x;
  6913. }
  6914. } else if ( yy > zz ) {
  6915. // m22 is the largest diagonal term
  6916. if ( yy < epsilon ) {
  6917. x = 0.707106781;
  6918. y = 0;
  6919. z = 0.707106781;
  6920. } else {
  6921. y = Math.sqrt( yy );
  6922. x = xy / y;
  6923. z = yz / y;
  6924. }
  6925. } else {
  6926. // m33 is the largest diagonal term so base result on this
  6927. if ( zz < epsilon ) {
  6928. x = 0.707106781;
  6929. y = 0.707106781;
  6930. z = 0;
  6931. } else {
  6932. z = Math.sqrt( zz );
  6933. x = xz / z;
  6934. y = yz / z;
  6935. }
  6936. }
  6937. this.set( x, y, z, angle );
  6938. return this; // return 180 deg rotation
  6939. }
  6940. // as we have reached here there are no singularities so we can handle normally
  6941. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6942. ( m13 - m31 ) * ( m13 - m31 ) +
  6943. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6944. if ( Math.abs( s ) < 0.001 ) { s = 1; }
  6945. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6946. // caught by singularity test above, but I've left it in just in case
  6947. this.x = ( m32 - m23 ) / s;
  6948. this.y = ( m13 - m31 ) / s;
  6949. this.z = ( m21 - m12 ) / s;
  6950. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6951. return this;
  6952. },
  6953. min: function ( v ) {
  6954. this.x = Math.min( this.x, v.x );
  6955. this.y = Math.min( this.y, v.y );
  6956. this.z = Math.min( this.z, v.z );
  6957. this.w = Math.min( this.w, v.w );
  6958. return this;
  6959. },
  6960. max: function ( v ) {
  6961. this.x = Math.max( this.x, v.x );
  6962. this.y = Math.max( this.y, v.y );
  6963. this.z = Math.max( this.z, v.z );
  6964. this.w = Math.max( this.w, v.w );
  6965. return this;
  6966. },
  6967. clamp: function ( min, max ) {
  6968. // assumes min < max, componentwise
  6969. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6970. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6971. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6972. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  6973. return this;
  6974. },
  6975. clampScalar: function ( minVal, maxVal ) {
  6976. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6977. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6978. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  6979. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  6980. return this;
  6981. },
  6982. clampLength: function ( min, max ) {
  6983. var length = this.length();
  6984. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6985. },
  6986. floor: function () {
  6987. this.x = Math.floor( this.x );
  6988. this.y = Math.floor( this.y );
  6989. this.z = Math.floor( this.z );
  6990. this.w = Math.floor( this.w );
  6991. return this;
  6992. },
  6993. ceil: function () {
  6994. this.x = Math.ceil( this.x );
  6995. this.y = Math.ceil( this.y );
  6996. this.z = Math.ceil( this.z );
  6997. this.w = Math.ceil( this.w );
  6998. return this;
  6999. },
  7000. round: function () {
  7001. this.x = Math.round( this.x );
  7002. this.y = Math.round( this.y );
  7003. this.z = Math.round( this.z );
  7004. this.w = Math.round( this.w );
  7005. return this;
  7006. },
  7007. roundToZero: function () {
  7008. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7009. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7010. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7011. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7012. return this;
  7013. },
  7014. negate: function () {
  7015. this.x = - this.x;
  7016. this.y = - this.y;
  7017. this.z = - this.z;
  7018. this.w = - this.w;
  7019. return this;
  7020. },
  7021. dot: function ( v ) {
  7022. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7023. },
  7024. lengthSq: function () {
  7025. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7026. },
  7027. length: function () {
  7028. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7029. },
  7030. manhattanLength: function () {
  7031. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7032. },
  7033. normalize: function () {
  7034. return this.divideScalar( this.length() || 1 );
  7035. },
  7036. setLength: function ( length ) {
  7037. return this.normalize().multiplyScalar( length );
  7038. },
  7039. lerp: function ( v, alpha ) {
  7040. this.x += ( v.x - this.x ) * alpha;
  7041. this.y += ( v.y - this.y ) * alpha;
  7042. this.z += ( v.z - this.z ) * alpha;
  7043. this.w += ( v.w - this.w ) * alpha;
  7044. return this;
  7045. },
  7046. lerpVectors: function ( v1, v2, alpha ) {
  7047. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  7048. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  7049. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  7050. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  7051. return this;
  7052. },
  7053. equals: function ( v ) {
  7054. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7055. },
  7056. fromArray: function ( array, offset ) {
  7057. if ( offset === undefined ) { offset = 0; }
  7058. this.x = array[ offset ];
  7059. this.y = array[ offset + 1 ];
  7060. this.z = array[ offset + 2 ];
  7061. this.w = array[ offset + 3 ];
  7062. return this;
  7063. },
  7064. toArray: function ( array, offset ) {
  7065. if ( array === undefined ) { array = []; }
  7066. if ( offset === undefined ) { offset = 0; }
  7067. array[ offset ] = this.x;
  7068. array[ offset + 1 ] = this.y;
  7069. array[ offset + 2 ] = this.z;
  7070. array[ offset + 3 ] = this.w;
  7071. return array;
  7072. },
  7073. fromBufferAttribute: function ( attribute, index, offset ) {
  7074. if ( offset !== undefined ) {
  7075. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7076. }
  7077. this.x = attribute.getX( index );
  7078. this.y = attribute.getY( index );
  7079. this.z = attribute.getZ( index );
  7080. this.w = attribute.getW( index );
  7081. return this;
  7082. },
  7083. random: function () {
  7084. this.x = Math.random();
  7085. this.y = Math.random();
  7086. this.z = Math.random();
  7087. this.w = Math.random();
  7088. return this;
  7089. }
  7090. } );
  7091. /*
  7092. In options, we can specify:
  7093. * Texture parameters for an auto-generated target texture
  7094. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7095. */
  7096. function WebGLRenderTarget( width, height, options ) {
  7097. this.width = width;
  7098. this.height = height;
  7099. this.scissor = new Vector4( 0, 0, width, height );
  7100. this.scissorTest = false;
  7101. this.viewport = new Vector4( 0, 0, width, height );
  7102. options = options || {};
  7103. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7104. this.texture.image = {};
  7105. this.texture.image.width = width;
  7106. this.texture.image.height = height;
  7107. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7108. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7109. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7110. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7111. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7112. }
  7113. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7114. constructor: WebGLRenderTarget,
  7115. isWebGLRenderTarget: true,
  7116. setSize: function ( width, height ) {
  7117. if ( this.width !== width || this.height !== height ) {
  7118. this.width = width;
  7119. this.height = height;
  7120. this.texture.image.width = width;
  7121. this.texture.image.height = height;
  7122. this.dispose();
  7123. }
  7124. this.viewport.set( 0, 0, width, height );
  7125. this.scissor.set( 0, 0, width, height );
  7126. },
  7127. clone: function () {
  7128. return new this.constructor().copy( this );
  7129. },
  7130. copy: function ( source ) {
  7131. this.width = source.width;
  7132. this.height = source.height;
  7133. this.viewport.copy( source.viewport );
  7134. this.texture = source.texture.clone();
  7135. this.depthBuffer = source.depthBuffer;
  7136. this.stencilBuffer = source.stencilBuffer;
  7137. this.depthTexture = source.depthTexture;
  7138. return this;
  7139. },
  7140. dispose: function () {
  7141. this.dispatchEvent( { type: 'dispose' } );
  7142. }
  7143. } );
  7144. function WebGLMultisampleRenderTarget( width, height, options ) {
  7145. WebGLRenderTarget.call( this, width, height, options );
  7146. this.samples = 4;
  7147. }
  7148. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  7149. constructor: WebGLMultisampleRenderTarget,
  7150. isWebGLMultisampleRenderTarget: true,
  7151. copy: function ( source ) {
  7152. WebGLRenderTarget.prototype.copy.call( this, source );
  7153. this.samples = source.samples;
  7154. return this;
  7155. }
  7156. } );
  7157. function Quaternion( x, y, z, w ) {
  7158. if ( x === void 0 ) x = 0;
  7159. if ( y === void 0 ) y = 0;
  7160. if ( z === void 0 ) z = 0;
  7161. if ( w === void 0 ) w = 1;
  7162. this._x = x;
  7163. this._y = y;
  7164. this._z = z;
  7165. this._w = w;
  7166. }
  7167. Object.assign( Quaternion, {
  7168. slerp: function ( qa, qb, qm, t ) {
  7169. return qm.copy( qa ).slerp( qb, t );
  7170. },
  7171. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  7172. // fuzz-free, array-based Quaternion SLERP operation
  7173. var x0 = src0[ srcOffset0 + 0 ],
  7174. y0 = src0[ srcOffset0 + 1 ],
  7175. z0 = src0[ srcOffset0 + 2 ],
  7176. w0 = src0[ srcOffset0 + 3 ];
  7177. var x1 = src1[ srcOffset1 + 0 ],
  7178. y1 = src1[ srcOffset1 + 1 ],
  7179. z1 = src1[ srcOffset1 + 2 ],
  7180. w1 = src1[ srcOffset1 + 3 ];
  7181. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  7182. var s = 1 - t,
  7183. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  7184. dir = ( cos >= 0 ? 1 : - 1 ),
  7185. sqrSin = 1 - cos * cos;
  7186. // Skip the Slerp for tiny steps to avoid numeric problems:
  7187. if ( sqrSin > Number.EPSILON ) {
  7188. var sin = Math.sqrt( sqrSin ),
  7189. len = Math.atan2( sin, cos * dir );
  7190. s = Math.sin( s * len ) / sin;
  7191. t = Math.sin( t * len ) / sin;
  7192. }
  7193. var tDir = t * dir;
  7194. x0 = x0 * s + x1 * tDir;
  7195. y0 = y0 * s + y1 * tDir;
  7196. z0 = z0 * s + z1 * tDir;
  7197. w0 = w0 * s + w1 * tDir;
  7198. // Normalize in case we just did a lerp:
  7199. if ( s === 1 - t ) {
  7200. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  7201. x0 *= f;
  7202. y0 *= f;
  7203. z0 *= f;
  7204. w0 *= f;
  7205. }
  7206. }
  7207. dst[ dstOffset ] = x0;
  7208. dst[ dstOffset + 1 ] = y0;
  7209. dst[ dstOffset + 2 ] = z0;
  7210. dst[ dstOffset + 3 ] = w0;
  7211. },
  7212. multiplyQuaternionsFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  7213. var x0 = src0[ srcOffset0 ];
  7214. var y0 = src0[ srcOffset0 + 1 ];
  7215. var z0 = src0[ srcOffset0 + 2 ];
  7216. var w0 = src0[ srcOffset0 + 3 ];
  7217. var x1 = src1[ srcOffset1 ];
  7218. var y1 = src1[ srcOffset1 + 1 ];
  7219. var z1 = src1[ srcOffset1 + 2 ];
  7220. var w1 = src1[ srcOffset1 + 3 ];
  7221. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  7222. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  7223. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  7224. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  7225. return dst;
  7226. }
  7227. } );
  7228. Object.defineProperties( Quaternion.prototype, {
  7229. x: {
  7230. get: function () {
  7231. return this._x;
  7232. },
  7233. set: function ( value ) {
  7234. this._x = value;
  7235. this._onChangeCallback();
  7236. }
  7237. },
  7238. y: {
  7239. get: function () {
  7240. return this._y;
  7241. },
  7242. set: function ( value ) {
  7243. this._y = value;
  7244. this._onChangeCallback();
  7245. }
  7246. },
  7247. z: {
  7248. get: function () {
  7249. return this._z;
  7250. },
  7251. set: function ( value ) {
  7252. this._z = value;
  7253. this._onChangeCallback();
  7254. }
  7255. },
  7256. w: {
  7257. get: function () {
  7258. return this._w;
  7259. },
  7260. set: function ( value ) {
  7261. this._w = value;
  7262. this._onChangeCallback();
  7263. }
  7264. }
  7265. } );
  7266. Object.assign( Quaternion.prototype, {
  7267. isQuaternion: true,
  7268. set: function ( x, y, z, w ) {
  7269. this._x = x;
  7270. this._y = y;
  7271. this._z = z;
  7272. this._w = w;
  7273. this._onChangeCallback();
  7274. return this;
  7275. },
  7276. clone: function () {
  7277. return new this.constructor( this._x, this._y, this._z, this._w );
  7278. },
  7279. copy: function ( quaternion ) {
  7280. this._x = quaternion.x;
  7281. this._y = quaternion.y;
  7282. this._z = quaternion.z;
  7283. this._w = quaternion.w;
  7284. this._onChangeCallback();
  7285. return this;
  7286. },
  7287. setFromEuler: function ( euler, update ) {
  7288. if ( ! ( euler && euler.isEuler ) ) {
  7289. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  7290. }
  7291. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  7292. // http://www.mathworks.com/matlabcentral/fileexchange/
  7293. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  7294. // content/SpinCalc.m
  7295. var cos = Math.cos;
  7296. var sin = Math.sin;
  7297. var c1 = cos( x / 2 );
  7298. var c2 = cos( y / 2 );
  7299. var c3 = cos( z / 2 );
  7300. var s1 = sin( x / 2 );
  7301. var s2 = sin( y / 2 );
  7302. var s3 = sin( z / 2 );
  7303. switch ( order ) {
  7304. case 'XYZ':
  7305. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7306. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7307. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7308. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7309. break;
  7310. case 'YXZ':
  7311. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7312. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7313. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7314. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7315. break;
  7316. case 'ZXY':
  7317. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7318. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7319. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7320. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7321. break;
  7322. case 'ZYX':
  7323. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7324. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7325. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7326. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7327. break;
  7328. case 'YZX':
  7329. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7330. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7331. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7332. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7333. break;
  7334. case 'XZY':
  7335. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7336. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7337. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7338. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7339. break;
  7340. default:
  7341. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  7342. }
  7343. if ( update !== false ) { this._onChangeCallback(); }
  7344. return this;
  7345. },
  7346. setFromAxisAngle: function ( axis, angle ) {
  7347. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  7348. // assumes axis is normalized
  7349. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  7350. this._x = axis.x * s;
  7351. this._y = axis.y * s;
  7352. this._z = axis.z * s;
  7353. this._w = Math.cos( halfAngle );
  7354. this._onChangeCallback();
  7355. return this;
  7356. },
  7357. setFromRotationMatrix: function ( m ) {
  7358. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  7359. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7360. var te = m.elements,
  7361. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7362. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7363. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  7364. trace = m11 + m22 + m33;
  7365. if ( trace > 0 ) {
  7366. var s = 0.5 / Math.sqrt( trace + 1.0 );
  7367. this._w = 0.25 / s;
  7368. this._x = ( m32 - m23 ) * s;
  7369. this._y = ( m13 - m31 ) * s;
  7370. this._z = ( m21 - m12 ) * s;
  7371. } else if ( m11 > m22 && m11 > m33 ) {
  7372. var s$1 = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  7373. this._w = ( m32 - m23 ) / s$1;
  7374. this._x = 0.25 * s$1;
  7375. this._y = ( m12 + m21 ) / s$1;
  7376. this._z = ( m13 + m31 ) / s$1;
  7377. } else if ( m22 > m33 ) {
  7378. var s$2 = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  7379. this._w = ( m13 - m31 ) / s$2;
  7380. this._x = ( m12 + m21 ) / s$2;
  7381. this._y = 0.25 * s$2;
  7382. this._z = ( m23 + m32 ) / s$2;
  7383. } else {
  7384. var s$3 = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  7385. this._w = ( m21 - m12 ) / s$3;
  7386. this._x = ( m13 + m31 ) / s$3;
  7387. this._y = ( m23 + m32 ) / s$3;
  7388. this._z = 0.25 * s$3;
  7389. }
  7390. this._onChangeCallback();
  7391. return this;
  7392. },
  7393. setFromUnitVectors: function ( vFrom, vTo ) {
  7394. // assumes direction vectors vFrom and vTo are normalized
  7395. var EPS = 0.000001;
  7396. var r = vFrom.dot( vTo ) + 1;
  7397. if ( r < EPS ) {
  7398. r = 0;
  7399. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  7400. this._x = - vFrom.y;
  7401. this._y = vFrom.x;
  7402. this._z = 0;
  7403. this._w = r;
  7404. } else {
  7405. this._x = 0;
  7406. this._y = - vFrom.z;
  7407. this._z = vFrom.y;
  7408. this._w = r;
  7409. }
  7410. } else {
  7411. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  7412. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  7413. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  7414. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  7415. this._w = r;
  7416. }
  7417. return this.normalize();
  7418. },
  7419. angleTo: function ( q ) {
  7420. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  7421. },
  7422. rotateTowards: function ( q, step ) {
  7423. var angle = this.angleTo( q );
  7424. if ( angle === 0 ) { return this; }
  7425. var t = Math.min( 1, step / angle );
  7426. this.slerp( q, t );
  7427. return this;
  7428. },
  7429. identity: function () {
  7430. return this.set( 0, 0, 0, 1 );
  7431. },
  7432. inverse: function () {
  7433. // quaternion is assumed to have unit length
  7434. return this.conjugate();
  7435. },
  7436. conjugate: function () {
  7437. this._x *= - 1;
  7438. this._y *= - 1;
  7439. this._z *= - 1;
  7440. this._onChangeCallback();
  7441. return this;
  7442. },
  7443. dot: function ( v ) {
  7444. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  7445. },
  7446. lengthSq: function () {
  7447. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  7448. },
  7449. length: function () {
  7450. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  7451. },
  7452. normalize: function () {
  7453. var l = this.length();
  7454. if ( l === 0 ) {
  7455. this._x = 0;
  7456. this._y = 0;
  7457. this._z = 0;
  7458. this._w = 1;
  7459. } else {
  7460. l = 1 / l;
  7461. this._x = this._x * l;
  7462. this._y = this._y * l;
  7463. this._z = this._z * l;
  7464. this._w = this._w * l;
  7465. }
  7466. this._onChangeCallback();
  7467. return this;
  7468. },
  7469. multiply: function ( q, p ) {
  7470. if ( p !== undefined ) {
  7471. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  7472. return this.multiplyQuaternions( q, p );
  7473. }
  7474. return this.multiplyQuaternions( this, q );
  7475. },
  7476. premultiply: function ( q ) {
  7477. return this.multiplyQuaternions( q, this );
  7478. },
  7479. multiplyQuaternions: function ( a, b ) {
  7480. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  7481. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  7482. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  7483. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  7484. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  7485. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  7486. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  7487. this._onChangeCallback();
  7488. return this;
  7489. },
  7490. slerp: function ( qb, t ) {
  7491. if ( t === 0 ) { return this; }
  7492. if ( t === 1 ) { return this.copy( qb ); }
  7493. var x = this._x, y = this._y, z = this._z, w = this._w;
  7494. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  7495. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  7496. if ( cosHalfTheta < 0 ) {
  7497. this._w = - qb._w;
  7498. this._x = - qb._x;
  7499. this._y = - qb._y;
  7500. this._z = - qb._z;
  7501. cosHalfTheta = - cosHalfTheta;
  7502. } else {
  7503. this.copy( qb );
  7504. }
  7505. if ( cosHalfTheta >= 1.0 ) {
  7506. this._w = w;
  7507. this._x = x;
  7508. this._y = y;
  7509. this._z = z;
  7510. return this;
  7511. }
  7512. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  7513. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  7514. var s = 1 - t;
  7515. this._w = s * w + t * this._w;
  7516. this._x = s * x + t * this._x;
  7517. this._y = s * y + t * this._y;
  7518. this._z = s * z + t * this._z;
  7519. this.normalize();
  7520. this._onChangeCallback();
  7521. return this;
  7522. }
  7523. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  7524. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  7525. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  7526. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  7527. this._w = ( w * ratioA + this._w * ratioB );
  7528. this._x = ( x * ratioA + this._x * ratioB );
  7529. this._y = ( y * ratioA + this._y * ratioB );
  7530. this._z = ( z * ratioA + this._z * ratioB );
  7531. this._onChangeCallback();
  7532. return this;
  7533. },
  7534. equals: function ( quaternion ) {
  7535. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  7536. },
  7537. fromArray: function ( array, offset ) {
  7538. if ( offset === undefined ) { offset = 0; }
  7539. this._x = array[ offset ];
  7540. this._y = array[ offset + 1 ];
  7541. this._z = array[ offset + 2 ];
  7542. this._w = array[ offset + 3 ];
  7543. this._onChangeCallback();
  7544. return this;
  7545. },
  7546. toArray: function ( array, offset ) {
  7547. if ( array === undefined ) { array = []; }
  7548. if ( offset === undefined ) { offset = 0; }
  7549. array[ offset ] = this._x;
  7550. array[ offset + 1 ] = this._y;
  7551. array[ offset + 2 ] = this._z;
  7552. array[ offset + 3 ] = this._w;
  7553. return array;
  7554. },
  7555. fromBufferAttribute: function ( attribute, index ) {
  7556. this._x = attribute.getX( index );
  7557. this._y = attribute.getY( index );
  7558. this._z = attribute.getZ( index );
  7559. this._w = attribute.getW( index );
  7560. return this;
  7561. },
  7562. _onChange: function ( callback ) {
  7563. this._onChangeCallback = callback;
  7564. return this;
  7565. },
  7566. _onChangeCallback: function () {}
  7567. } );
  7568. var _vector = new Vector3();
  7569. var _quaternion = new Quaternion();
  7570. function Vector3( x, y, z ) {
  7571. if ( x === void 0 ) x = 0;
  7572. if ( y === void 0 ) y = 0;
  7573. if ( z === void 0 ) z = 0;
  7574. this.x = x;
  7575. this.y = y;
  7576. this.z = z;
  7577. }
  7578. Object.assign( Vector3.prototype, {
  7579. isVector3: true,
  7580. set: function ( x, y, z ) {
  7581. if ( z === undefined ) { z = this.z; } // sprite.scale.set(x,y)
  7582. this.x = x;
  7583. this.y = y;
  7584. this.z = z;
  7585. return this;
  7586. },
  7587. setScalar: function ( scalar ) {
  7588. this.x = scalar;
  7589. this.y = scalar;
  7590. this.z = scalar;
  7591. return this;
  7592. },
  7593. setX: function ( x ) {
  7594. this.x = x;
  7595. return this;
  7596. },
  7597. setY: function ( y ) {
  7598. this.y = y;
  7599. return this;
  7600. },
  7601. setZ: function ( z ) {
  7602. this.z = z;
  7603. return this;
  7604. },
  7605. setComponent: function ( index, value ) {
  7606. switch ( index ) {
  7607. case 0: this.x = value; break;
  7608. case 1: this.y = value; break;
  7609. case 2: this.z = value; break;
  7610. default: throw new Error( 'index is out of range: ' + index );
  7611. }
  7612. return this;
  7613. },
  7614. getComponent: function ( index ) {
  7615. switch ( index ) {
  7616. case 0: return this.x;
  7617. case 1: return this.y;
  7618. case 2: return this.z;
  7619. default: throw new Error( 'index is out of range: ' + index );
  7620. }
  7621. },
  7622. clone: function () {
  7623. return new this.constructor( this.x, this.y, this.z );
  7624. },
  7625. copy: function ( v ) {
  7626. this.x = v.x;
  7627. this.y = v.y;
  7628. this.z = v.z;
  7629. return this;
  7630. },
  7631. add: function ( v, w ) {
  7632. if ( w !== undefined ) {
  7633. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  7634. return this.addVectors( v, w );
  7635. }
  7636. this.x += v.x;
  7637. this.y += v.y;
  7638. this.z += v.z;
  7639. return this;
  7640. },
  7641. addScalar: function ( s ) {
  7642. this.x += s;
  7643. this.y += s;
  7644. this.z += s;
  7645. return this;
  7646. },
  7647. addVectors: function ( a, b ) {
  7648. this.x = a.x + b.x;
  7649. this.y = a.y + b.y;
  7650. this.z = a.z + b.z;
  7651. return this;
  7652. },
  7653. addScaledVector: function ( v, s ) {
  7654. this.x += v.x * s;
  7655. this.y += v.y * s;
  7656. this.z += v.z * s;
  7657. return this;
  7658. },
  7659. sub: function ( v, w ) {
  7660. if ( w !== undefined ) {
  7661. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  7662. return this.subVectors( v, w );
  7663. }
  7664. this.x -= v.x;
  7665. this.y -= v.y;
  7666. this.z -= v.z;
  7667. return this;
  7668. },
  7669. subScalar: function ( s ) {
  7670. this.x -= s;
  7671. this.y -= s;
  7672. this.z -= s;
  7673. return this;
  7674. },
  7675. subVectors: function ( a, b ) {
  7676. this.x = a.x - b.x;
  7677. this.y = a.y - b.y;
  7678. this.z = a.z - b.z;
  7679. return this;
  7680. },
  7681. multiply: function ( v, w ) {
  7682. if ( w !== undefined ) {
  7683. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  7684. return this.multiplyVectors( v, w );
  7685. }
  7686. this.x *= v.x;
  7687. this.y *= v.y;
  7688. this.z *= v.z;
  7689. return this;
  7690. },
  7691. multiplyScalar: function ( scalar ) {
  7692. this.x *= scalar;
  7693. this.y *= scalar;
  7694. this.z *= scalar;
  7695. return this;
  7696. },
  7697. multiplyVectors: function ( a, b ) {
  7698. this.x = a.x * b.x;
  7699. this.y = a.y * b.y;
  7700. this.z = a.z * b.z;
  7701. return this;
  7702. },
  7703. applyEuler: function ( euler ) {
  7704. if ( ! ( euler && euler.isEuler ) ) {
  7705. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  7706. }
  7707. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  7708. },
  7709. applyAxisAngle: function ( axis, angle ) {
  7710. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  7711. },
  7712. applyMatrix3: function ( m ) {
  7713. var x = this.x, y = this.y, z = this.z;
  7714. var e = m.elements;
  7715. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  7716. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  7717. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  7718. return this;
  7719. },
  7720. applyNormalMatrix: function ( m ) {
  7721. return this.applyMatrix3( m ).normalize();
  7722. },
  7723. applyMatrix4: function ( m ) {
  7724. var x = this.x, y = this.y, z = this.z;
  7725. var e = m.elements;
  7726. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  7727. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  7728. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  7729. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  7730. return this;
  7731. },
  7732. applyQuaternion: function ( q ) {
  7733. var x = this.x, y = this.y, z = this.z;
  7734. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  7735. // calculate quat * vector
  7736. var ix = qw * x + qy * z - qz * y;
  7737. var iy = qw * y + qz * x - qx * z;
  7738. var iz = qw * z + qx * y - qy * x;
  7739. var iw = - qx * x - qy * y - qz * z;
  7740. // calculate result * inverse quat
  7741. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  7742. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  7743. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  7744. return this;
  7745. },
  7746. project: function ( camera ) {
  7747. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  7748. },
  7749. unproject: function ( camera ) {
  7750. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  7751. },
  7752. transformDirection: function ( m ) {
  7753. // input: THREE.Matrix4 affine matrix
  7754. // vector interpreted as a direction
  7755. var x = this.x, y = this.y, z = this.z;
  7756. var e = m.elements;
  7757. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  7758. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  7759. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  7760. return this.normalize();
  7761. },
  7762. divide: function ( v ) {
  7763. this.x /= v.x;
  7764. this.y /= v.y;
  7765. this.z /= v.z;
  7766. return this;
  7767. },
  7768. divideScalar: function ( scalar ) {
  7769. return this.multiplyScalar( 1 / scalar );
  7770. },
  7771. min: function ( v ) {
  7772. this.x = Math.min( this.x, v.x );
  7773. this.y = Math.min( this.y, v.y );
  7774. this.z = Math.min( this.z, v.z );
  7775. return this;
  7776. },
  7777. max: function ( v ) {
  7778. this.x = Math.max( this.x, v.x );
  7779. this.y = Math.max( this.y, v.y );
  7780. this.z = Math.max( this.z, v.z );
  7781. return this;
  7782. },
  7783. clamp: function ( min, max ) {
  7784. // assumes min < max, componentwise
  7785. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7786. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7787. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7788. return this;
  7789. },
  7790. clampScalar: function ( minVal, maxVal ) {
  7791. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  7792. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  7793. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  7794. return this;
  7795. },
  7796. clampLength: function ( min, max ) {
  7797. var length = this.length();
  7798. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7799. },
  7800. floor: function () {
  7801. this.x = Math.floor( this.x );
  7802. this.y = Math.floor( this.y );
  7803. this.z = Math.floor( this.z );
  7804. return this;
  7805. },
  7806. ceil: function () {
  7807. this.x = Math.ceil( this.x );
  7808. this.y = Math.ceil( this.y );
  7809. this.z = Math.ceil( this.z );
  7810. return this;
  7811. },
  7812. round: function () {
  7813. this.x = Math.round( this.x );
  7814. this.y = Math.round( this.y );
  7815. this.z = Math.round( this.z );
  7816. return this;
  7817. },
  7818. roundToZero: function () {
  7819. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7820. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7821. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7822. return this;
  7823. },
  7824. negate: function () {
  7825. this.x = - this.x;
  7826. this.y = - this.y;
  7827. this.z = - this.z;
  7828. return this;
  7829. },
  7830. dot: function ( v ) {
  7831. return this.x * v.x + this.y * v.y + this.z * v.z;
  7832. },
  7833. // TODO lengthSquared?
  7834. lengthSq: function () {
  7835. return this.x * this.x + this.y * this.y + this.z * this.z;
  7836. },
  7837. length: function () {
  7838. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  7839. },
  7840. manhattanLength: function () {
  7841. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  7842. },
  7843. normalize: function () {
  7844. return this.divideScalar( this.length() || 1 );
  7845. },
  7846. setLength: function ( length ) {
  7847. return this.normalize().multiplyScalar( length );
  7848. },
  7849. lerp: function ( v, alpha ) {
  7850. this.x += ( v.x - this.x ) * alpha;
  7851. this.y += ( v.y - this.y ) * alpha;
  7852. this.z += ( v.z - this.z ) * alpha;
  7853. return this;
  7854. },
  7855. lerpVectors: function ( v1, v2, alpha ) {
  7856. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  7857. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  7858. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  7859. return this;
  7860. },
  7861. cross: function ( v, w ) {
  7862. if ( w !== undefined ) {
  7863. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  7864. return this.crossVectors( v, w );
  7865. }
  7866. return this.crossVectors( this, v );
  7867. },
  7868. crossVectors: function ( a, b ) {
  7869. var ax = a.x, ay = a.y, az = a.z;
  7870. var bx = b.x, by = b.y, bz = b.z;
  7871. this.x = ay * bz - az * by;
  7872. this.y = az * bx - ax * bz;
  7873. this.z = ax * by - ay * bx;
  7874. return this;
  7875. },
  7876. projectOnVector: function ( v ) {
  7877. var denominator = v.lengthSq();
  7878. if ( denominator === 0 ) { return this.set( 0, 0, 0 ); }
  7879. var scalar = v.dot( this ) / denominator;
  7880. return this.copy( v ).multiplyScalar( scalar );
  7881. },
  7882. projectOnPlane: function ( planeNormal ) {
  7883. _vector.copy( this ).projectOnVector( planeNormal );
  7884. return this.sub( _vector );
  7885. },
  7886. reflect: function ( normal ) {
  7887. // reflect incident vector off plane orthogonal to normal
  7888. // normal is assumed to have unit length
  7889. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  7890. },
  7891. angleTo: function ( v ) {
  7892. var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  7893. if ( denominator === 0 ) { return Math.PI / 2; }
  7894. var theta = this.dot( v ) / denominator;
  7895. // clamp, to handle numerical problems
  7896. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  7897. },
  7898. distanceTo: function ( v ) {
  7899. return Math.sqrt( this.distanceToSquared( v ) );
  7900. },
  7901. distanceToSquared: function ( v ) {
  7902. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  7903. return dx * dx + dy * dy + dz * dz;
  7904. },
  7905. manhattanDistanceTo: function ( v ) {
  7906. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  7907. },
  7908. setFromSpherical: function ( s ) {
  7909. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  7910. },
  7911. setFromSphericalCoords: function ( radius, phi, theta ) {
  7912. var sinPhiRadius = Math.sin( phi ) * radius;
  7913. this.x = sinPhiRadius * Math.sin( theta );
  7914. this.y = Math.cos( phi ) * radius;
  7915. this.z = sinPhiRadius * Math.cos( theta );
  7916. return this;
  7917. },
  7918. setFromCylindrical: function ( c ) {
  7919. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  7920. },
  7921. setFromCylindricalCoords: function ( radius, theta, y ) {
  7922. this.x = radius * Math.sin( theta );
  7923. this.y = y;
  7924. this.z = radius * Math.cos( theta );
  7925. return this;
  7926. },
  7927. setFromMatrixPosition: function ( m ) {
  7928. var e = m.elements;
  7929. this.x = e[ 12 ];
  7930. this.y = e[ 13 ];
  7931. this.z = e[ 14 ];
  7932. return this;
  7933. },
  7934. setFromMatrixScale: function ( m ) {
  7935. var sx = this.setFromMatrixColumn( m, 0 ).length();
  7936. var sy = this.setFromMatrixColumn( m, 1 ).length();
  7937. var sz = this.setFromMatrixColumn( m, 2 ).length();
  7938. this.x = sx;
  7939. this.y = sy;
  7940. this.z = sz;
  7941. return this;
  7942. },
  7943. setFromMatrixColumn: function ( m, index ) {
  7944. return this.fromArray( m.elements, index * 4 );
  7945. },
  7946. setFromMatrix3Column: function ( m, index ) {
  7947. return this.fromArray( m.elements, index * 3 );
  7948. },
  7949. equals: function ( v ) {
  7950. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  7951. },
  7952. fromArray: function ( array, offset ) {
  7953. if ( offset === undefined ) { offset = 0; }
  7954. this.x = array[ offset ];
  7955. this.y = array[ offset + 1 ];
  7956. this.z = array[ offset + 2 ];
  7957. return this;
  7958. },
  7959. toArray: function ( array, offset ) {
  7960. if ( array === undefined ) { array = []; }
  7961. if ( offset === undefined ) { offset = 0; }
  7962. array[ offset ] = this.x;
  7963. array[ offset + 1 ] = this.y;
  7964. array[ offset + 2 ] = this.z;
  7965. return array;
  7966. },
  7967. fromBufferAttribute: function ( attribute, index, offset ) {
  7968. if ( offset !== undefined ) {
  7969. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  7970. }
  7971. this.x = attribute.getX( index );
  7972. this.y = attribute.getY( index );
  7973. this.z = attribute.getZ( index );
  7974. return this;
  7975. },
  7976. random: function () {
  7977. this.x = Math.random();
  7978. this.y = Math.random();
  7979. this.z = Math.random();
  7980. return this;
  7981. }
  7982. } );
  7983. var _v1 = new Vector3();
  7984. var _m1 = new Matrix4();
  7985. var _zero = new Vector3( 0, 0, 0 );
  7986. var _one = new Vector3( 1, 1, 1 );
  7987. var _x = new Vector3();
  7988. var _y = new Vector3();
  7989. var _z = new Vector3();
  7990. function Matrix4() {
  7991. this.elements = [
  7992. 1, 0, 0, 0,
  7993. 0, 1, 0, 0,
  7994. 0, 0, 1, 0,
  7995. 0, 0, 0, 1
  7996. ];
  7997. if ( arguments.length > 0 ) {
  7998. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  7999. }
  8000. }
  8001. Object.assign( Matrix4.prototype, {
  8002. isMatrix4: true,
  8003. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8004. var te = this.elements;
  8005. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8006. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8007. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8008. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8009. return this;
  8010. },
  8011. identity: function () {
  8012. this.set(
  8013. 1, 0, 0, 0,
  8014. 0, 1, 0, 0,
  8015. 0, 0, 1, 0,
  8016. 0, 0, 0, 1
  8017. );
  8018. return this;
  8019. },
  8020. clone: function () {
  8021. return new Matrix4().fromArray( this.elements );
  8022. },
  8023. copy: function ( m ) {
  8024. var te = this.elements;
  8025. var me = m.elements;
  8026. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8027. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8028. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8029. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8030. return this;
  8031. },
  8032. copyPosition: function ( m ) {
  8033. var te = this.elements, me = m.elements;
  8034. te[ 12 ] = me[ 12 ];
  8035. te[ 13 ] = me[ 13 ];
  8036. te[ 14 ] = me[ 14 ];
  8037. return this;
  8038. },
  8039. extractBasis: function ( xAxis, yAxis, zAxis ) {
  8040. xAxis.setFromMatrixColumn( this, 0 );
  8041. yAxis.setFromMatrixColumn( this, 1 );
  8042. zAxis.setFromMatrixColumn( this, 2 );
  8043. return this;
  8044. },
  8045. makeBasis: function ( xAxis, yAxis, zAxis ) {
  8046. this.set(
  8047. xAxis.x, yAxis.x, zAxis.x, 0,
  8048. xAxis.y, yAxis.y, zAxis.y, 0,
  8049. xAxis.z, yAxis.z, zAxis.z, 0,
  8050. 0, 0, 0, 1
  8051. );
  8052. return this;
  8053. },
  8054. extractRotation: function ( m ) {
  8055. // this method does not support reflection matrices
  8056. var te = this.elements;
  8057. var me = m.elements;
  8058. var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
  8059. var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
  8060. var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();
  8061. te[ 0 ] = me[ 0 ] * scaleX;
  8062. te[ 1 ] = me[ 1 ] * scaleX;
  8063. te[ 2 ] = me[ 2 ] * scaleX;
  8064. te[ 3 ] = 0;
  8065. te[ 4 ] = me[ 4 ] * scaleY;
  8066. te[ 5 ] = me[ 5 ] * scaleY;
  8067. te[ 6 ] = me[ 6 ] * scaleY;
  8068. te[ 7 ] = 0;
  8069. te[ 8 ] = me[ 8 ] * scaleZ;
  8070. te[ 9 ] = me[ 9 ] * scaleZ;
  8071. te[ 10 ] = me[ 10 ] * scaleZ;
  8072. te[ 11 ] = 0;
  8073. te[ 12 ] = 0;
  8074. te[ 13 ] = 0;
  8075. te[ 14 ] = 0;
  8076. te[ 15 ] = 1;
  8077. return this;
  8078. },
  8079. makeRotationFromEuler: function ( euler ) {
  8080. if ( ! ( euler && euler.isEuler ) ) {
  8081. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  8082. }
  8083. var te = this.elements;
  8084. var x = euler.x, y = euler.y, z = euler.z;
  8085. var a = Math.cos( x ), b = Math.sin( x );
  8086. var c = Math.cos( y ), d = Math.sin( y );
  8087. var e = Math.cos( z ), f = Math.sin( z );
  8088. if ( euler.order === 'XYZ' ) {
  8089. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  8090. te[ 0 ] = c * e;
  8091. te[ 4 ] = - c * f;
  8092. te[ 8 ] = d;
  8093. te[ 1 ] = af + be * d;
  8094. te[ 5 ] = ae - bf * d;
  8095. te[ 9 ] = - b * c;
  8096. te[ 2 ] = bf - ae * d;
  8097. te[ 6 ] = be + af * d;
  8098. te[ 10 ] = a * c;
  8099. } else if ( euler.order === 'YXZ' ) {
  8100. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  8101. te[ 0 ] = ce + df * b;
  8102. te[ 4 ] = de * b - cf;
  8103. te[ 8 ] = a * d;
  8104. te[ 1 ] = a * f;
  8105. te[ 5 ] = a * e;
  8106. te[ 9 ] = - b;
  8107. te[ 2 ] = cf * b - de;
  8108. te[ 6 ] = df + ce * b;
  8109. te[ 10 ] = a * c;
  8110. } else if ( euler.order === 'ZXY' ) {
  8111. var ce$1 = c * e, cf$1 = c * f, de$1 = d * e, df$1 = d * f;
  8112. te[ 0 ] = ce$1 - df$1 * b;
  8113. te[ 4 ] = - a * f;
  8114. te[ 8 ] = de$1 + cf$1 * b;
  8115. te[ 1 ] = cf$1 + de$1 * b;
  8116. te[ 5 ] = a * e;
  8117. te[ 9 ] = df$1 - ce$1 * b;
  8118. te[ 2 ] = - a * d;
  8119. te[ 6 ] = b;
  8120. te[ 10 ] = a * c;
  8121. } else if ( euler.order === 'ZYX' ) {
  8122. var ae$1 = a * e, af$1 = a * f, be$1 = b * e, bf$1 = b * f;
  8123. te[ 0 ] = c * e;
  8124. te[ 4 ] = be$1 * d - af$1;
  8125. te[ 8 ] = ae$1 * d + bf$1;
  8126. te[ 1 ] = c * f;
  8127. te[ 5 ] = bf$1 * d + ae$1;
  8128. te[ 9 ] = af$1 * d - be$1;
  8129. te[ 2 ] = - d;
  8130. te[ 6 ] = b * c;
  8131. te[ 10 ] = a * c;
  8132. } else if ( euler.order === 'YZX' ) {
  8133. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8134. te[ 0 ] = c * e;
  8135. te[ 4 ] = bd - ac * f;
  8136. te[ 8 ] = bc * f + ad;
  8137. te[ 1 ] = f;
  8138. te[ 5 ] = a * e;
  8139. te[ 9 ] = - b * e;
  8140. te[ 2 ] = - d * e;
  8141. te[ 6 ] = ad * f + bc;
  8142. te[ 10 ] = ac - bd * f;
  8143. } else if ( euler.order === 'XZY' ) {
  8144. var ac$1 = a * c, ad$1 = a * d, bc$1 = b * c, bd$1 = b * d;
  8145. te[ 0 ] = c * e;
  8146. te[ 4 ] = - f;
  8147. te[ 8 ] = d * e;
  8148. te[ 1 ] = ac$1 * f + bd$1;
  8149. te[ 5 ] = a * e;
  8150. te[ 9 ] = ad$1 * f - bc$1;
  8151. te[ 2 ] = bc$1 * f - ad$1;
  8152. te[ 6 ] = b * e;
  8153. te[ 10 ] = bd$1 * f + ac$1;
  8154. }
  8155. // bottom row
  8156. te[ 3 ] = 0;
  8157. te[ 7 ] = 0;
  8158. te[ 11 ] = 0;
  8159. // last column
  8160. te[ 12 ] = 0;
  8161. te[ 13 ] = 0;
  8162. te[ 14 ] = 0;
  8163. te[ 15 ] = 1;
  8164. return this;
  8165. },
  8166. makeRotationFromQuaternion: function ( q ) {
  8167. return this.compose( _zero, q, _one );
  8168. },
  8169. lookAt: function ( eye, target, up ) {
  8170. var te = this.elements;
  8171. _z.subVectors( eye, target );
  8172. if ( _z.lengthSq() === 0 ) {
  8173. // eye and target are in the same position
  8174. _z.z = 1;
  8175. }
  8176. _z.normalize();
  8177. _x.crossVectors( up, _z );
  8178. if ( _x.lengthSq() === 0 ) {
  8179. // up and z are parallel
  8180. if ( Math.abs( up.z ) === 1 ) {
  8181. _z.x += 0.0001;
  8182. } else {
  8183. _z.z += 0.0001;
  8184. }
  8185. _z.normalize();
  8186. _x.crossVectors( up, _z );
  8187. }
  8188. _x.normalize();
  8189. _y.crossVectors( _z, _x );
  8190. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8191. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8192. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8193. return this;
  8194. },
  8195. multiply: function ( m, n ) {
  8196. if ( n !== undefined ) {
  8197. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  8198. return this.multiplyMatrices( m, n );
  8199. }
  8200. return this.multiplyMatrices( this, m );
  8201. },
  8202. premultiply: function ( m ) {
  8203. return this.multiplyMatrices( m, this );
  8204. },
  8205. multiplyMatrices: function ( a, b ) {
  8206. var ae = a.elements;
  8207. var be = b.elements;
  8208. var te = this.elements;
  8209. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8210. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8211. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8212. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8213. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8214. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8215. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8216. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8217. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8218. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8219. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8220. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8221. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8222. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8223. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8224. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8225. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8226. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8227. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8228. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8229. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8230. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8231. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8232. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8233. return this;
  8234. },
  8235. multiplyScalar: function ( s ) {
  8236. var te = this.elements;
  8237. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8238. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8239. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8240. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8241. return this;
  8242. },
  8243. determinant: function () {
  8244. var te = this.elements;
  8245. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8246. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8247. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8248. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8249. //TODO: make this more efficient
  8250. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  8251. return (
  8252. n41 * (
  8253. + n14 * n23 * n32
  8254. - n13 * n24 * n32
  8255. - n14 * n22 * n33
  8256. + n12 * n24 * n33
  8257. + n13 * n22 * n34
  8258. - n12 * n23 * n34
  8259. ) +
  8260. n42 * (
  8261. + n11 * n23 * n34
  8262. - n11 * n24 * n33
  8263. + n14 * n21 * n33
  8264. - n13 * n21 * n34
  8265. + n13 * n24 * n31
  8266. - n14 * n23 * n31
  8267. ) +
  8268. n43 * (
  8269. + n11 * n24 * n32
  8270. - n11 * n22 * n34
  8271. - n14 * n21 * n32
  8272. + n12 * n21 * n34
  8273. + n14 * n22 * n31
  8274. - n12 * n24 * n31
  8275. ) +
  8276. n44 * (
  8277. - n13 * n22 * n31
  8278. - n11 * n23 * n32
  8279. + n11 * n22 * n33
  8280. + n13 * n21 * n32
  8281. - n12 * n21 * n33
  8282. + n12 * n23 * n31
  8283. )
  8284. );
  8285. },
  8286. transpose: function () {
  8287. var te = this.elements;
  8288. var tmp;
  8289. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8290. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8291. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8292. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8293. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8294. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8295. return this;
  8296. },
  8297. setPosition: function ( x, y, z ) {
  8298. var te = this.elements;
  8299. if ( x.isVector3 ) {
  8300. te[ 12 ] = x.x;
  8301. te[ 13 ] = x.y;
  8302. te[ 14 ] = x.z;
  8303. } else {
  8304. te[ 12 ] = x;
  8305. te[ 13 ] = y;
  8306. te[ 14 ] = z;
  8307. }
  8308. return this;
  8309. },
  8310. getInverse: function ( m, throwOnDegenerate ) {
  8311. if ( throwOnDegenerate !== undefined ) {
  8312. console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." );
  8313. }
  8314. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  8315. var te = this.elements,
  8316. me = m.elements,
  8317. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  8318. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  8319. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  8320. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  8321. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  8322. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  8323. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  8324. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  8325. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  8326. if ( det === 0 ) { return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); }
  8327. var detInv = 1 / det;
  8328. te[ 0 ] = t11 * detInv;
  8329. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  8330. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  8331. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  8332. te[ 4 ] = t12 * detInv;
  8333. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  8334. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  8335. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  8336. te[ 8 ] = t13 * detInv;
  8337. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  8338. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  8339. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  8340. te[ 12 ] = t14 * detInv;
  8341. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  8342. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  8343. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  8344. return this;
  8345. },
  8346. scale: function ( v ) {
  8347. var te = this.elements;
  8348. var x = v.x, y = v.y, z = v.z;
  8349. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8350. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8351. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8352. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8353. return this;
  8354. },
  8355. getMaxScaleOnAxis: function () {
  8356. var te = this.elements;
  8357. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8358. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8359. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8360. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8361. },
  8362. makeTranslation: function ( x, y, z ) {
  8363. this.set(
  8364. 1, 0, 0, x,
  8365. 0, 1, 0, y,
  8366. 0, 0, 1, z,
  8367. 0, 0, 0, 1
  8368. );
  8369. return this;
  8370. },
  8371. makeRotationX: function ( theta ) {
  8372. var c = Math.cos( theta ), s = Math.sin( theta );
  8373. this.set(
  8374. 1, 0, 0, 0,
  8375. 0, c, - s, 0,
  8376. 0, s, c, 0,
  8377. 0, 0, 0, 1
  8378. );
  8379. return this;
  8380. },
  8381. makeRotationY: function ( theta ) {
  8382. var c = Math.cos( theta ), s = Math.sin( theta );
  8383. this.set(
  8384. c, 0, s, 0,
  8385. 0, 1, 0, 0,
  8386. - s, 0, c, 0,
  8387. 0, 0, 0, 1
  8388. );
  8389. return this;
  8390. },
  8391. makeRotationZ: function ( theta ) {
  8392. var c = Math.cos( theta ), s = Math.sin( theta );
  8393. this.set(
  8394. c, - s, 0, 0,
  8395. s, c, 0, 0,
  8396. 0, 0, 1, 0,
  8397. 0, 0, 0, 1
  8398. );
  8399. return this;
  8400. },
  8401. makeRotationAxis: function ( axis, angle ) {
  8402. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8403. var c = Math.cos( angle );
  8404. var s = Math.sin( angle );
  8405. var t = 1 - c;
  8406. var x = axis.x, y = axis.y, z = axis.z;
  8407. var tx = t * x, ty = t * y;
  8408. this.set(
  8409. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8410. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8411. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8412. 0, 0, 0, 1
  8413. );
  8414. return this;
  8415. },
  8416. makeScale: function ( x, y, z ) {
  8417. this.set(
  8418. x, 0, 0, 0,
  8419. 0, y, 0, 0,
  8420. 0, 0, z, 0,
  8421. 0, 0, 0, 1
  8422. );
  8423. return this;
  8424. },
  8425. makeShear: function ( x, y, z ) {
  8426. this.set(
  8427. 1, y, z, 0,
  8428. x, 1, z, 0,
  8429. x, y, 1, 0,
  8430. 0, 0, 0, 1
  8431. );
  8432. return this;
  8433. },
  8434. compose: function ( position, quaternion, scale ) {
  8435. var te = this.elements;
  8436. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8437. var x2 = x + x, y2 = y + y, z2 = z + z;
  8438. var xx = x * x2, xy = x * y2, xz = x * z2;
  8439. var yy = y * y2, yz = y * z2, zz = z * z2;
  8440. var wx = w * x2, wy = w * y2, wz = w * z2;
  8441. var sx = scale.x, sy = scale.y, sz = scale.z;
  8442. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8443. te[ 1 ] = ( xy + wz ) * sx;
  8444. te[ 2 ] = ( xz - wy ) * sx;
  8445. te[ 3 ] = 0;
  8446. te[ 4 ] = ( xy - wz ) * sy;
  8447. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8448. te[ 6 ] = ( yz + wx ) * sy;
  8449. te[ 7 ] = 0;
  8450. te[ 8 ] = ( xz + wy ) * sz;
  8451. te[ 9 ] = ( yz - wx ) * sz;
  8452. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8453. te[ 11 ] = 0;
  8454. te[ 12 ] = position.x;
  8455. te[ 13 ] = position.y;
  8456. te[ 14 ] = position.z;
  8457. te[ 15 ] = 1;
  8458. return this;
  8459. },
  8460. decompose: function ( position, quaternion, scale ) {
  8461. var te = this.elements;
  8462. var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8463. var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8464. var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8465. // if determine is negative, we need to invert one scale
  8466. var det = this.determinant();
  8467. if ( det < 0 ) { sx = - sx; }
  8468. position.x = te[ 12 ];
  8469. position.y = te[ 13 ];
  8470. position.z = te[ 14 ];
  8471. // scale the rotation part
  8472. _m1.copy( this );
  8473. var invSX = 1 / sx;
  8474. var invSY = 1 / sy;
  8475. var invSZ = 1 / sz;
  8476. _m1.elements[ 0 ] *= invSX;
  8477. _m1.elements[ 1 ] *= invSX;
  8478. _m1.elements[ 2 ] *= invSX;
  8479. _m1.elements[ 4 ] *= invSY;
  8480. _m1.elements[ 5 ] *= invSY;
  8481. _m1.elements[ 6 ] *= invSY;
  8482. _m1.elements[ 8 ] *= invSZ;
  8483. _m1.elements[ 9 ] *= invSZ;
  8484. _m1.elements[ 10 ] *= invSZ;
  8485. quaternion.setFromRotationMatrix( _m1 );
  8486. scale.x = sx;
  8487. scale.y = sy;
  8488. scale.z = sz;
  8489. return this;
  8490. },
  8491. makePerspective: function ( left, right, top, bottom, near, far ) {
  8492. if ( far === undefined ) {
  8493. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  8494. }
  8495. var te = this.elements;
  8496. var x = 2 * near / ( right - left );
  8497. var y = 2 * near / ( top - bottom );
  8498. var a = ( right + left ) / ( right - left );
  8499. var b = ( top + bottom ) / ( top - bottom );
  8500. var c = - ( far + near ) / ( far - near );
  8501. var d = - 2 * far * near / ( far - near );
  8502. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8503. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8504. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8505. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  8506. return this;
  8507. },
  8508. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  8509. var te = this.elements;
  8510. var w = 1.0 / ( right - left );
  8511. var h = 1.0 / ( top - bottom );
  8512. var p = 1.0 / ( far - near );
  8513. var x = ( right + left ) * w;
  8514. var y = ( top + bottom ) * h;
  8515. var z = ( far + near ) * p;
  8516. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  8517. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  8518. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  8519. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8520. return this;
  8521. },
  8522. equals: function ( matrix ) {
  8523. var te = this.elements;
  8524. var me = matrix.elements;
  8525. for ( var i = 0; i < 16; i ++ ) {
  8526. if ( te[ i ] !== me[ i ] ) { return false; }
  8527. }
  8528. return true;
  8529. },
  8530. fromArray: function ( array, offset ) {
  8531. if ( offset === undefined ) { offset = 0; }
  8532. for ( var i = 0; i < 16; i ++ ) {
  8533. this.elements[ i ] = array[ i + offset ];
  8534. }
  8535. return this;
  8536. },
  8537. toArray: function ( array, offset ) {
  8538. if ( array === undefined ) { array = []; }
  8539. if ( offset === undefined ) { offset = 0; }
  8540. var te = this.elements;
  8541. array[ offset ] = te[ 0 ];
  8542. array[ offset + 1 ] = te[ 1 ];
  8543. array[ offset + 2 ] = te[ 2 ];
  8544. array[ offset + 3 ] = te[ 3 ];
  8545. array[ offset + 4 ] = te[ 4 ];
  8546. array[ offset + 5 ] = te[ 5 ];
  8547. array[ offset + 6 ] = te[ 6 ];
  8548. array[ offset + 7 ] = te[ 7 ];
  8549. array[ offset + 8 ] = te[ 8 ];
  8550. array[ offset + 9 ] = te[ 9 ];
  8551. array[ offset + 10 ] = te[ 10 ];
  8552. array[ offset + 11 ] = te[ 11 ];
  8553. array[ offset + 12 ] = te[ 12 ];
  8554. array[ offset + 13 ] = te[ 13 ];
  8555. array[ offset + 14 ] = te[ 14 ];
  8556. array[ offset + 15 ] = te[ 15 ];
  8557. return array;
  8558. }
  8559. } );
  8560. var _matrix = new Matrix4();
  8561. var _quaternion$1 = new Quaternion();
  8562. function Euler( x, y, z, order ) {
  8563. if ( x === void 0 ) x = 0;
  8564. if ( y === void 0 ) y = 0;
  8565. if ( z === void 0 ) z = 0;
  8566. if ( order === void 0 ) order = Euler.DefaultOrder;
  8567. this._x = x;
  8568. this._y = y;
  8569. this._z = z;
  8570. this._order = order;
  8571. }
  8572. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  8573. Euler.DefaultOrder = 'XYZ';
  8574. Object.defineProperties( Euler.prototype, {
  8575. x: {
  8576. get: function () {
  8577. return this._x;
  8578. },
  8579. set: function ( value ) {
  8580. this._x = value;
  8581. this._onChangeCallback();
  8582. }
  8583. },
  8584. y: {
  8585. get: function () {
  8586. return this._y;
  8587. },
  8588. set: function ( value ) {
  8589. this._y = value;
  8590. this._onChangeCallback();
  8591. }
  8592. },
  8593. z: {
  8594. get: function () {
  8595. return this._z;
  8596. },
  8597. set: function ( value ) {
  8598. this._z = value;
  8599. this._onChangeCallback();
  8600. }
  8601. },
  8602. order: {
  8603. get: function () {
  8604. return this._order;
  8605. },
  8606. set: function ( value ) {
  8607. this._order = value;
  8608. this._onChangeCallback();
  8609. }
  8610. }
  8611. } );
  8612. Object.assign( Euler.prototype, {
  8613. isEuler: true,
  8614. set: function ( x, y, z, order ) {
  8615. this._x = x;
  8616. this._y = y;
  8617. this._z = z;
  8618. this._order = order || this._order;
  8619. this._onChangeCallback();
  8620. return this;
  8621. },
  8622. clone: function () {
  8623. return new this.constructor( this._x, this._y, this._z, this._order );
  8624. },
  8625. copy: function ( euler ) {
  8626. this._x = euler._x;
  8627. this._y = euler._y;
  8628. this._z = euler._z;
  8629. this._order = euler._order;
  8630. this._onChangeCallback();
  8631. return this;
  8632. },
  8633. setFromRotationMatrix: function ( m, order, update ) {
  8634. var clamp = MathUtils.clamp;
  8635. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8636. var te = m.elements;
  8637. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8638. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8639. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8640. order = order || this._order;
  8641. switch ( order ) {
  8642. case 'XYZ':
  8643. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  8644. if ( Math.abs( m13 ) < 0.9999999 ) {
  8645. this._x = Math.atan2( - m23, m33 );
  8646. this._z = Math.atan2( - m12, m11 );
  8647. } else {
  8648. this._x = Math.atan2( m32, m22 );
  8649. this._z = 0;
  8650. }
  8651. break;
  8652. case 'YXZ':
  8653. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  8654. if ( Math.abs( m23 ) < 0.9999999 ) {
  8655. this._y = Math.atan2( m13, m33 );
  8656. this._z = Math.atan2( m21, m22 );
  8657. } else {
  8658. this._y = Math.atan2( - m31, m11 );
  8659. this._z = 0;
  8660. }
  8661. break;
  8662. case 'ZXY':
  8663. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  8664. if ( Math.abs( m32 ) < 0.9999999 ) {
  8665. this._y = Math.atan2( - m31, m33 );
  8666. this._z = Math.atan2( - m12, m22 );
  8667. } else {
  8668. this._y = 0;
  8669. this._z = Math.atan2( m21, m11 );
  8670. }
  8671. break;
  8672. case 'ZYX':
  8673. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  8674. if ( Math.abs( m31 ) < 0.9999999 ) {
  8675. this._x = Math.atan2( m32, m33 );
  8676. this._z = Math.atan2( m21, m11 );
  8677. } else {
  8678. this._x = 0;
  8679. this._z = Math.atan2( - m12, m22 );
  8680. }
  8681. break;
  8682. case 'YZX':
  8683. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  8684. if ( Math.abs( m21 ) < 0.9999999 ) {
  8685. this._x = Math.atan2( - m23, m22 );
  8686. this._y = Math.atan2( - m31, m11 );
  8687. } else {
  8688. this._x = 0;
  8689. this._y = Math.atan2( m13, m33 );
  8690. }
  8691. break;
  8692. case 'XZY':
  8693. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  8694. if ( Math.abs( m12 ) < 0.9999999 ) {
  8695. this._x = Math.atan2( m32, m22 );
  8696. this._y = Math.atan2( m13, m11 );
  8697. } else {
  8698. this._x = Math.atan2( - m23, m33 );
  8699. this._y = 0;
  8700. }
  8701. break;
  8702. default:
  8703. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8704. }
  8705. this._order = order;
  8706. if ( update !== false ) { this._onChangeCallback(); }
  8707. return this;
  8708. },
  8709. setFromQuaternion: function ( q, order, update ) {
  8710. _matrix.makeRotationFromQuaternion( q );
  8711. return this.setFromRotationMatrix( _matrix, order, update );
  8712. },
  8713. setFromVector3: function ( v, order ) {
  8714. return this.set( v.x, v.y, v.z, order || this._order );
  8715. },
  8716. reorder: function ( newOrder ) {
  8717. // WARNING: this discards revolution information -bhouston
  8718. _quaternion$1.setFromEuler( this );
  8719. return this.setFromQuaternion( _quaternion$1, newOrder );
  8720. },
  8721. equals: function ( euler ) {
  8722. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8723. },
  8724. fromArray: function ( array ) {
  8725. this._x = array[ 0 ];
  8726. this._y = array[ 1 ];
  8727. this._z = array[ 2 ];
  8728. if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; }
  8729. this._onChangeCallback();
  8730. return this;
  8731. },
  8732. toArray: function ( array, offset ) {
  8733. if ( array === undefined ) { array = []; }
  8734. if ( offset === undefined ) { offset = 0; }
  8735. array[ offset ] = this._x;
  8736. array[ offset + 1 ] = this._y;
  8737. array[ offset + 2 ] = this._z;
  8738. array[ offset + 3 ] = this._order;
  8739. return array;
  8740. },
  8741. toVector3: function ( optionalResult ) {
  8742. if ( optionalResult ) {
  8743. return optionalResult.set( this._x, this._y, this._z );
  8744. } else {
  8745. return new Vector3( this._x, this._y, this._z );
  8746. }
  8747. },
  8748. _onChange: function ( callback ) {
  8749. this._onChangeCallback = callback;
  8750. return this;
  8751. },
  8752. _onChangeCallback: function () {}
  8753. } );
  8754. function Layers() {
  8755. this.mask = 1 | 0;
  8756. }
  8757. Object.assign( Layers.prototype, {
  8758. set: function ( channel ) {
  8759. this.mask = 1 << channel | 0;
  8760. },
  8761. enable: function ( channel ) {
  8762. this.mask |= 1 << channel | 0;
  8763. },
  8764. enableAll: function () {
  8765. this.mask = 0xffffffff | 0;
  8766. },
  8767. toggle: function ( channel ) {
  8768. this.mask ^= 1 << channel | 0;
  8769. },
  8770. disable: function ( channel ) {
  8771. this.mask &= ~ ( 1 << channel | 0 );
  8772. },
  8773. disableAll: function () {
  8774. this.mask = 0;
  8775. },
  8776. test: function ( layers ) {
  8777. return ( this.mask & layers.mask ) !== 0;
  8778. }
  8779. } );
  8780. var _object3DId = 0;
  8781. var _v1$1 = new Vector3();
  8782. var _q1 = new Quaternion();
  8783. var _m1$1 = new Matrix4();
  8784. var _target = new Vector3();
  8785. var _position = new Vector3();
  8786. var _scale = new Vector3();
  8787. var _quaternion$2 = new Quaternion();
  8788. var _xAxis = new Vector3( 1, 0, 0 );
  8789. var _yAxis = new Vector3( 0, 1, 0 );
  8790. var _zAxis = new Vector3( 0, 0, 1 );
  8791. var _addedEvent = { type: 'added' };
  8792. var _removedEvent = { type: 'removed' };
  8793. function Object3D() {
  8794. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  8795. this.uuid = MathUtils.generateUUID();
  8796. this.name = '';
  8797. this.type = 'Object3D';
  8798. this.parent = null;
  8799. this.children = [];
  8800. this.up = Object3D.DefaultUp.clone();
  8801. var position = new Vector3();
  8802. var rotation = new Euler();
  8803. var quaternion = new Quaternion();
  8804. var scale = new Vector3( 1, 1, 1 );
  8805. function onRotationChange() {
  8806. quaternion.setFromEuler( rotation, false );
  8807. }
  8808. function onQuaternionChange() {
  8809. rotation.setFromQuaternion( quaternion, undefined, false );
  8810. }
  8811. rotation._onChange( onRotationChange );
  8812. quaternion._onChange( onQuaternionChange );
  8813. Object.defineProperties( this, {
  8814. position: {
  8815. configurable: true,
  8816. enumerable: true,
  8817. value: position
  8818. },
  8819. rotation: {
  8820. configurable: true,
  8821. enumerable: true,
  8822. value: rotation
  8823. },
  8824. quaternion: {
  8825. configurable: true,
  8826. enumerable: true,
  8827. value: quaternion
  8828. },
  8829. scale: {
  8830. configurable: true,
  8831. enumerable: true,
  8832. value: scale
  8833. },
  8834. modelViewMatrix: {
  8835. value: new Matrix4()
  8836. },
  8837. normalMatrix: {
  8838. value: new Matrix3()
  8839. }
  8840. } );
  8841. this.matrix = new Matrix4();
  8842. this.matrixWorld = new Matrix4();
  8843. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  8844. this.matrixWorldNeedsUpdate = false;
  8845. this.layers = new Layers();
  8846. this.visible = true;
  8847. this.castShadow = false;
  8848. this.receiveShadow = false;
  8849. this.frustumCulled = true;
  8850. this.renderOrder = 0;
  8851. this.userData = {};
  8852. }
  8853. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  8854. Object3D.DefaultMatrixAutoUpdate = true;
  8855. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  8856. constructor: Object3D,
  8857. isObject3D: true,
  8858. onBeforeRender: function () {},
  8859. onAfterRender: function () {},
  8860. applyMatrix4: function ( matrix ) {
  8861. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  8862. this.matrix.premultiply( matrix );
  8863. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8864. },
  8865. applyQuaternion: function ( q ) {
  8866. this.quaternion.premultiply( q );
  8867. return this;
  8868. },
  8869. setRotationFromAxisAngle: function ( axis, angle ) {
  8870. // assumes axis is normalized
  8871. this.quaternion.setFromAxisAngle( axis, angle );
  8872. },
  8873. setRotationFromEuler: function ( euler ) {
  8874. this.quaternion.setFromEuler( euler, true );
  8875. },
  8876. setRotationFromMatrix: function ( m ) {
  8877. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8878. this.quaternion.setFromRotationMatrix( m );
  8879. },
  8880. setRotationFromQuaternion: function ( q ) {
  8881. // assumes q is normalized
  8882. this.quaternion.copy( q );
  8883. },
  8884. rotateOnAxis: function ( axis, angle ) {
  8885. // rotate object on axis in object space
  8886. // axis is assumed to be normalized
  8887. _q1.setFromAxisAngle( axis, angle );
  8888. this.quaternion.multiply( _q1 );
  8889. return this;
  8890. },
  8891. rotateOnWorldAxis: function ( axis, angle ) {
  8892. // rotate object on axis in world space
  8893. // axis is assumed to be normalized
  8894. // method assumes no rotated parent
  8895. _q1.setFromAxisAngle( axis, angle );
  8896. this.quaternion.premultiply( _q1 );
  8897. return this;
  8898. },
  8899. rotateX: function ( angle ) {
  8900. return this.rotateOnAxis( _xAxis, angle );
  8901. },
  8902. rotateY: function ( angle ) {
  8903. return this.rotateOnAxis( _yAxis, angle );
  8904. },
  8905. rotateZ: function ( angle ) {
  8906. return this.rotateOnAxis( _zAxis, angle );
  8907. },
  8908. translateOnAxis: function ( axis, distance ) {
  8909. // translate object by distance along axis in object space
  8910. // axis is assumed to be normalized
  8911. _v1$1.copy( axis ).applyQuaternion( this.quaternion );
  8912. this.position.add( _v1$1.multiplyScalar( distance ) );
  8913. return this;
  8914. },
  8915. translateX: function ( distance ) {
  8916. return this.translateOnAxis( _xAxis, distance );
  8917. },
  8918. translateY: function ( distance ) {
  8919. return this.translateOnAxis( _yAxis, distance );
  8920. },
  8921. translateZ: function ( distance ) {
  8922. return this.translateOnAxis( _zAxis, distance );
  8923. },
  8924. localToWorld: function ( vector ) {
  8925. return vector.applyMatrix4( this.matrixWorld );
  8926. },
  8927. worldToLocal: function ( vector ) {
  8928. return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );
  8929. },
  8930. lookAt: function ( x, y, z ) {
  8931. // This method does not support objects having non-uniformly-scaled parent(s)
  8932. if ( x.isVector3 ) {
  8933. _target.copy( x );
  8934. } else {
  8935. _target.set( x, y, z );
  8936. }
  8937. var parent = this.parent;
  8938. this.updateWorldMatrix( true, false );
  8939. _position.setFromMatrixPosition( this.matrixWorld );
  8940. if ( this.isCamera || this.isLight ) {
  8941. _m1$1.lookAt( _position, _target, this.up );
  8942. } else {
  8943. _m1$1.lookAt( _target, _position, this.up );
  8944. }
  8945. this.quaternion.setFromRotationMatrix( _m1$1 );
  8946. if ( parent ) {
  8947. _m1$1.extractRotation( parent.matrixWorld );
  8948. _q1.setFromRotationMatrix( _m1$1 );
  8949. this.quaternion.premultiply( _q1.inverse() );
  8950. }
  8951. },
  8952. add: function ( object ) {
  8953. if ( arguments.length > 1 ) {
  8954. for ( var i = 0; i < arguments.length; i ++ ) {
  8955. this.add( arguments[ i ] );
  8956. }
  8957. return this;
  8958. }
  8959. if ( object === this ) {
  8960. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8961. return this;
  8962. }
  8963. if ( ( object && object.isObject3D ) ) {
  8964. if ( object.parent !== null ) {
  8965. object.parent.remove( object );
  8966. }
  8967. object.parent = this;
  8968. this.children.push( object );
  8969. object.dispatchEvent( _addedEvent );
  8970. } else {
  8971. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8972. }
  8973. return this;
  8974. },
  8975. remove: function ( object ) {
  8976. if ( arguments.length > 1 ) {
  8977. for ( var i = 0; i < arguments.length; i ++ ) {
  8978. this.remove( arguments[ i ] );
  8979. }
  8980. return this;
  8981. }
  8982. var index = this.children.indexOf( object );
  8983. if ( index !== - 1 ) {
  8984. object.parent = null;
  8985. this.children.splice( index, 1 );
  8986. object.dispatchEvent( _removedEvent );
  8987. }
  8988. return this;
  8989. },
  8990. attach: function ( object ) {
  8991. // adds object as a child of this, while maintaining the object's world transform
  8992. this.updateWorldMatrix( true, false );
  8993. _m1$1.getInverse( this.matrixWorld );
  8994. if ( object.parent !== null ) {
  8995. object.parent.updateWorldMatrix( true, false );
  8996. _m1$1.multiply( object.parent.matrixWorld );
  8997. }
  8998. object.applyMatrix4( _m1$1 );
  8999. object.updateWorldMatrix( false, false );
  9000. this.add( object );
  9001. return this;
  9002. },
  9003. getObjectById: function ( id ) {
  9004. return this.getObjectByProperty( 'id', id );
  9005. },
  9006. getObjectByName: function ( name ) {
  9007. return this.getObjectByProperty( 'name', name );
  9008. },
  9009. getObjectByProperty: function ( name, value ) {
  9010. if ( this[ name ] === value ) { return this; }
  9011. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9012. var child = this.children[ i ];
  9013. var object = child.getObjectByProperty( name, value );
  9014. if ( object !== undefined ) {
  9015. return object;
  9016. }
  9017. }
  9018. return undefined;
  9019. },
  9020. getWorldPosition: function ( target ) {
  9021. if ( target === undefined ) {
  9022. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9023. target = new Vector3();
  9024. }
  9025. this.updateMatrixWorld( true );
  9026. return target.setFromMatrixPosition( this.matrixWorld );
  9027. },
  9028. getWorldQuaternion: function ( target ) {
  9029. if ( target === undefined ) {
  9030. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9031. target = new Quaternion();
  9032. }
  9033. this.updateMatrixWorld( true );
  9034. this.matrixWorld.decompose( _position, target, _scale );
  9035. return target;
  9036. },
  9037. getWorldScale: function ( target ) {
  9038. if ( target === undefined ) {
  9039. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9040. target = new Vector3();
  9041. }
  9042. this.updateMatrixWorld( true );
  9043. this.matrixWorld.decompose( _position, _quaternion$2, target );
  9044. return target;
  9045. },
  9046. getWorldDirection: function ( target ) {
  9047. if ( target === undefined ) {
  9048. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9049. target = new Vector3();
  9050. }
  9051. this.updateMatrixWorld( true );
  9052. var e = this.matrixWorld.elements;
  9053. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9054. },
  9055. raycast: function () {},
  9056. traverse: function ( callback ) {
  9057. callback( this );
  9058. var children = this.children;
  9059. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9060. children[ i ].traverse( callback );
  9061. }
  9062. },
  9063. traverseVisible: function ( callback ) {
  9064. if ( this.visible === false ) { return; }
  9065. callback( this );
  9066. var children = this.children;
  9067. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9068. children[ i ].traverseVisible( callback );
  9069. }
  9070. },
  9071. traverseAncestors: function ( callback ) {
  9072. var parent = this.parent;
  9073. if ( parent !== null ) {
  9074. callback( parent );
  9075. parent.traverseAncestors( callback );
  9076. }
  9077. },
  9078. updateMatrix: function () {
  9079. this.matrix.compose( this.position, this.quaternion, this.scale );
  9080. this.matrixWorldNeedsUpdate = true;
  9081. },
  9082. updateMatrixWorld: function ( force ) {
  9083. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9084. if ( this.matrixWorldNeedsUpdate || force ) {
  9085. if ( this.parent === null ) {
  9086. this.matrixWorld.copy( this.matrix );
  9087. } else {
  9088. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9089. }
  9090. this.matrixWorldNeedsUpdate = false;
  9091. force = true;
  9092. }
  9093. // update children
  9094. var children = this.children;
  9095. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9096. children[ i ].updateMatrixWorld( force );
  9097. }
  9098. },
  9099. updateWorldMatrix: function ( updateParents, updateChildren ) {
  9100. var parent = this.parent;
  9101. if ( updateParents === true && parent !== null ) {
  9102. parent.updateWorldMatrix( true, false );
  9103. }
  9104. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9105. if ( this.parent === null ) {
  9106. this.matrixWorld.copy( this.matrix );
  9107. } else {
  9108. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9109. }
  9110. // update children
  9111. if ( updateChildren === true ) {
  9112. var children = this.children;
  9113. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9114. children[ i ].updateWorldMatrix( false, true );
  9115. }
  9116. }
  9117. },
  9118. toJSON: function ( meta ) {
  9119. // meta is a string when called from JSON.stringify
  9120. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9121. var output = {};
  9122. // meta is a hash used to collect geometries, materials.
  9123. // not providing it implies that this is the root object
  9124. // being serialized.
  9125. if ( isRootObject ) {
  9126. // initialize meta obj
  9127. meta = {
  9128. geometries: {},
  9129. materials: {},
  9130. textures: {},
  9131. images: {},
  9132. shapes: {}
  9133. };
  9134. output.metadata = {
  9135. version: 4.5,
  9136. type: 'Object',
  9137. generator: 'Object3D.toJSON'
  9138. };
  9139. }
  9140. // standard Object3D serialization
  9141. var object = {};
  9142. object.uuid = this.uuid;
  9143. object.type = this.type;
  9144. if ( this.name !== '' ) { object.name = this.name; }
  9145. if ( this.castShadow === true ) { object.castShadow = true; }
  9146. if ( this.receiveShadow === true ) { object.receiveShadow = true; }
  9147. if ( this.visible === false ) { object.visible = false; }
  9148. if ( this.frustumCulled === false ) { object.frustumCulled = false; }
  9149. if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; }
  9150. if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; }
  9151. object.layers = this.layers.mask;
  9152. object.matrix = this.matrix.toArray();
  9153. if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; }
  9154. // object specific properties
  9155. if ( this.isInstancedMesh ) {
  9156. object.type = 'InstancedMesh';
  9157. object.count = this.count;
  9158. object.instanceMatrix = this.instanceMatrix.toJSON();
  9159. }
  9160. //
  9161. function serialize( library, element ) {
  9162. if ( library[ element.uuid ] === undefined ) {
  9163. library[ element.uuid ] = element.toJSON( meta );
  9164. }
  9165. return element.uuid;
  9166. }
  9167. if ( this.isMesh || this.isLine || this.isPoints ) {
  9168. object.geometry = serialize( meta.geometries, this.geometry );
  9169. var parameters = this.geometry.parameters;
  9170. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9171. var shapes = parameters.shapes;
  9172. if ( Array.isArray( shapes ) ) {
  9173. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9174. var shape = shapes[ i ];
  9175. serialize( meta.shapes, shape );
  9176. }
  9177. } else {
  9178. serialize( meta.shapes, shapes );
  9179. }
  9180. }
  9181. }
  9182. if ( this.material !== undefined ) {
  9183. if ( Array.isArray( this.material ) ) {
  9184. var uuids = [];
  9185. for ( var i$1 = 0, l$1 = this.material.length; i$1 < l$1; i$1 ++ ) {
  9186. uuids.push( serialize( meta.materials, this.material[ i$1 ] ) );
  9187. }
  9188. object.material = uuids;
  9189. } else {
  9190. object.material = serialize( meta.materials, this.material );
  9191. }
  9192. }
  9193. //
  9194. if ( this.children.length > 0 ) {
  9195. object.children = [];
  9196. for ( var i$2 = 0; i$2 < this.children.length; i$2 ++ ) {
  9197. object.children.push( this.children[ i$2 ].toJSON( meta ).object );
  9198. }
  9199. }
  9200. if ( isRootObject ) {
  9201. var geometries = extractFromCache( meta.geometries );
  9202. var materials = extractFromCache( meta.materials );
  9203. var textures = extractFromCache( meta.textures );
  9204. var images = extractFromCache( meta.images );
  9205. var shapes$1 = extractFromCache( meta.shapes );
  9206. if ( geometries.length > 0 ) { output.geometries = geometries; }
  9207. if ( materials.length > 0 ) { output.materials = materials; }
  9208. if ( textures.length > 0 ) { output.textures = textures; }
  9209. if ( images.length > 0 ) { output.images = images; }
  9210. if ( shapes$1.length > 0 ) { output.shapes = shapes$1; }
  9211. }
  9212. output.object = object;
  9213. return output;
  9214. // extract data from the cache hash
  9215. // remove metadata on each item
  9216. // and return as array
  9217. function extractFromCache( cache ) {
  9218. var values = [];
  9219. for ( var key in cache ) {
  9220. var data = cache[ key ];
  9221. delete data.metadata;
  9222. values.push( data );
  9223. }
  9224. return values;
  9225. }
  9226. },
  9227. clone: function ( recursive ) {
  9228. return new this.constructor().copy( this, recursive );
  9229. },
  9230. copy: function ( source, recursive ) {
  9231. if ( recursive === undefined ) { recursive = true; }
  9232. this.name = source.name;
  9233. this.up.copy( source.up );
  9234. this.position.copy( source.position );
  9235. this.rotation.order = source.rotation.order;
  9236. this.quaternion.copy( source.quaternion );
  9237. this.scale.copy( source.scale );
  9238. this.matrix.copy( source.matrix );
  9239. this.matrixWorld.copy( source.matrixWorld );
  9240. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9241. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9242. this.layers.mask = source.layers.mask;
  9243. this.visible = source.visible;
  9244. this.castShadow = source.castShadow;
  9245. this.receiveShadow = source.receiveShadow;
  9246. this.frustumCulled = source.frustumCulled;
  9247. this.renderOrder = source.renderOrder;
  9248. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9249. if ( recursive === true ) {
  9250. for ( var i = 0; i < source.children.length; i ++ ) {
  9251. var child = source.children[ i ];
  9252. this.add( child.clone() );
  9253. }
  9254. }
  9255. return this;
  9256. }
  9257. } );
  9258. function Scene() {
  9259. Object3D.call( this );
  9260. this.type = 'Scene';
  9261. this.background = null;
  9262. this.environment = null;
  9263. this.fog = null;
  9264. this.overrideMaterial = null;
  9265. this.autoUpdate = true; // checked by the renderer
  9266. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  9267. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  9268. }
  9269. }
  9270. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9271. constructor: Scene,
  9272. isScene: true,
  9273. copy: function ( source, recursive ) {
  9274. Object3D.prototype.copy.call( this, source, recursive );
  9275. if ( source.background !== null ) { this.background = source.background.clone(); }
  9276. if ( source.environment !== null ) { this.environment = source.environment.clone(); }
  9277. if ( source.fog !== null ) { this.fog = source.fog.clone(); }
  9278. if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); }
  9279. this.autoUpdate = source.autoUpdate;
  9280. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9281. return this;
  9282. },
  9283. toJSON: function ( meta ) {
  9284. var data = Object3D.prototype.toJSON.call( this, meta );
  9285. if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); }
  9286. if ( this.environment !== null ) { data.object.environment = this.environment.toJSON( meta ); }
  9287. if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); }
  9288. return data;
  9289. },
  9290. dispose: function () {
  9291. this.dispatchEvent( { type: 'dispose' } );
  9292. }
  9293. } );
  9294. var _points = [
  9295. new Vector3(),
  9296. new Vector3(),
  9297. new Vector3(),
  9298. new Vector3(),
  9299. new Vector3(),
  9300. new Vector3(),
  9301. new Vector3(),
  9302. new Vector3()
  9303. ];
  9304. var _vector$1 = new Vector3();
  9305. var _box = new Box3();
  9306. // triangle centered vertices
  9307. var _v0 = new Vector3();
  9308. var _v1$2 = new Vector3();
  9309. var _v2 = new Vector3();
  9310. // triangle edge vectors
  9311. var _f0 = new Vector3();
  9312. var _f1 = new Vector3();
  9313. var _f2 = new Vector3();
  9314. var _center = new Vector3();
  9315. var _extents = new Vector3();
  9316. var _triangleNormal = new Vector3();
  9317. var _testAxis = new Vector3();
  9318. function Box3( min, max ) {
  9319. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9320. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9321. }
  9322. Object.assign( Box3.prototype, {
  9323. isBox3: true,
  9324. set: function ( min, max ) {
  9325. this.min.copy( min );
  9326. this.max.copy( max );
  9327. return this;
  9328. },
  9329. setFromArray: function ( array ) {
  9330. var minX = + Infinity;
  9331. var minY = + Infinity;
  9332. var minZ = + Infinity;
  9333. var maxX = - Infinity;
  9334. var maxY = - Infinity;
  9335. var maxZ = - Infinity;
  9336. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9337. var x = array[ i ];
  9338. var y = array[ i + 1 ];
  9339. var z = array[ i + 2 ];
  9340. if ( x < minX ) { minX = x; }
  9341. if ( y < minY ) { minY = y; }
  9342. if ( z < minZ ) { minZ = z; }
  9343. if ( x > maxX ) { maxX = x; }
  9344. if ( y > maxY ) { maxY = y; }
  9345. if ( z > maxZ ) { maxZ = z; }
  9346. }
  9347. this.min.set( minX, minY, minZ );
  9348. this.max.set( maxX, maxY, maxZ );
  9349. return this;
  9350. },
  9351. setFromBufferAttribute: function ( attribute ) {
  9352. var minX = + Infinity;
  9353. var minY = + Infinity;
  9354. var minZ = + Infinity;
  9355. var maxX = - Infinity;
  9356. var maxY = - Infinity;
  9357. var maxZ = - Infinity;
  9358. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9359. var x = attribute.getX( i );
  9360. var y = attribute.getY( i );
  9361. var z = attribute.getZ( i );
  9362. if ( x < minX ) { minX = x; }
  9363. if ( y < minY ) { minY = y; }
  9364. if ( z < minZ ) { minZ = z; }
  9365. if ( x > maxX ) { maxX = x; }
  9366. if ( y > maxY ) { maxY = y; }
  9367. if ( z > maxZ ) { maxZ = z; }
  9368. }
  9369. this.min.set( minX, minY, minZ );
  9370. this.max.set( maxX, maxY, maxZ );
  9371. return this;
  9372. },
  9373. setFromPoints: function ( points ) {
  9374. this.makeEmpty();
  9375. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9376. this.expandByPoint( points[ i ] );
  9377. }
  9378. return this;
  9379. },
  9380. setFromCenterAndSize: function ( center, size ) {
  9381. var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  9382. this.min.copy( center ).sub( halfSize );
  9383. this.max.copy( center ).add( halfSize );
  9384. return this;
  9385. },
  9386. setFromObject: function ( object ) {
  9387. this.makeEmpty();
  9388. return this.expandByObject( object );
  9389. },
  9390. clone: function () {
  9391. return new this.constructor().copy( this );
  9392. },
  9393. copy: function ( box ) {
  9394. this.min.copy( box.min );
  9395. this.max.copy( box.max );
  9396. return this;
  9397. },
  9398. makeEmpty: function () {
  9399. this.min.x = this.min.y = this.min.z = + Infinity;
  9400. this.max.x = this.max.y = this.max.z = - Infinity;
  9401. return this;
  9402. },
  9403. isEmpty: function () {
  9404. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9405. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9406. },
  9407. getCenter: function ( target ) {
  9408. if ( target === undefined ) {
  9409. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  9410. target = new Vector3();
  9411. }
  9412. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9413. },
  9414. getSize: function ( target ) {
  9415. if ( target === undefined ) {
  9416. console.warn( 'THREE.Box3: .getSize() target is now required' );
  9417. target = new Vector3();
  9418. }
  9419. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  9420. },
  9421. expandByPoint: function ( point ) {
  9422. this.min.min( point );
  9423. this.max.max( point );
  9424. return this;
  9425. },
  9426. expandByVector: function ( vector ) {
  9427. this.min.sub( vector );
  9428. this.max.add( vector );
  9429. return this;
  9430. },
  9431. expandByScalar: function ( scalar ) {
  9432. this.min.addScalar( - scalar );
  9433. this.max.addScalar( scalar );
  9434. return this;
  9435. },
  9436. expandByObject: function ( object ) {
  9437. // Computes the world-axis-aligned bounding box of an object (including its children),
  9438. // accounting for both the object's, and children's, world transforms
  9439. object.updateWorldMatrix( false, false );
  9440. var geometry = object.geometry;
  9441. if ( geometry !== undefined ) {
  9442. if ( geometry.boundingBox === null ) {
  9443. geometry.computeBoundingBox();
  9444. }
  9445. _box.copy( geometry.boundingBox );
  9446. _box.applyMatrix4( object.matrixWorld );
  9447. this.union( _box );
  9448. }
  9449. var children = object.children;
  9450. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9451. this.expandByObject( children[ i ] );
  9452. }
  9453. return this;
  9454. },
  9455. containsPoint: function ( point ) {
  9456. return point.x < this.min.x || point.x > this.max.x ||
  9457. point.y < this.min.y || point.y > this.max.y ||
  9458. point.z < this.min.z || point.z > this.max.z ? false : true;
  9459. },
  9460. containsBox: function ( box ) {
  9461. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9462. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9463. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9464. },
  9465. getParameter: function ( point, target ) {
  9466. // This can potentially have a divide by zero if the box
  9467. // has a size dimension of 0.
  9468. if ( target === undefined ) {
  9469. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  9470. target = new Vector3();
  9471. }
  9472. return target.set(
  9473. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9474. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9475. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9476. );
  9477. },
  9478. intersectsBox: function ( box ) {
  9479. // using 6 splitting planes to rule out intersections.
  9480. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9481. box.max.y < this.min.y || box.min.y > this.max.y ||
  9482. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9483. },
  9484. intersectsSphere: function ( sphere ) {
  9485. // Find the point on the AABB closest to the sphere center.
  9486. this.clampPoint( sphere.center, _vector$1 );
  9487. // If that point is inside the sphere, the AABB and sphere intersect.
  9488. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9489. },
  9490. intersectsPlane: function ( plane ) {
  9491. // We compute the minimum and maximum dot product values. If those values
  9492. // are on the same side (back or front) of the plane, then there is no intersection.
  9493. var min, max;
  9494. if ( plane.normal.x > 0 ) {
  9495. min = plane.normal.x * this.min.x;
  9496. max = plane.normal.x * this.max.x;
  9497. } else {
  9498. min = plane.normal.x * this.max.x;
  9499. max = plane.normal.x * this.min.x;
  9500. }
  9501. if ( plane.normal.y > 0 ) {
  9502. min += plane.normal.y * this.min.y;
  9503. max += plane.normal.y * this.max.y;
  9504. } else {
  9505. min += plane.normal.y * this.max.y;
  9506. max += plane.normal.y * this.min.y;
  9507. }
  9508. if ( plane.normal.z > 0 ) {
  9509. min += plane.normal.z * this.min.z;
  9510. max += plane.normal.z * this.max.z;
  9511. } else {
  9512. min += plane.normal.z * this.max.z;
  9513. max += plane.normal.z * this.min.z;
  9514. }
  9515. return ( min <= - plane.constant && max >= - plane.constant );
  9516. },
  9517. intersectsTriangle: function ( triangle ) {
  9518. if ( this.isEmpty() ) {
  9519. return false;
  9520. }
  9521. // compute box center and extents
  9522. this.getCenter( _center );
  9523. _extents.subVectors( this.max, _center );
  9524. // translate triangle to aabb origin
  9525. _v0.subVectors( triangle.a, _center );
  9526. _v1$2.subVectors( triangle.b, _center );
  9527. _v2.subVectors( triangle.c, _center );
  9528. // compute edge vectors for triangle
  9529. _f0.subVectors( _v1$2, _v0 );
  9530. _f1.subVectors( _v2, _v1$2 );
  9531. _f2.subVectors( _v0, _v2 );
  9532. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  9533. // 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
  9534. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  9535. var axes = [
  9536. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  9537. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  9538. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  9539. ];
  9540. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9541. return false;
  9542. }
  9543. // test 3 face normals from the aabb
  9544. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  9545. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9546. return false;
  9547. }
  9548. // finally testing the face normal of the triangle
  9549. // use already existing triangle edge vectors here
  9550. _triangleNormal.crossVectors( _f0, _f1 );
  9551. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  9552. return satForAxes( axes, _v0, _v1$2, _v2, _extents );
  9553. },
  9554. clampPoint: function ( point, target ) {
  9555. if ( target === undefined ) {
  9556. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  9557. target = new Vector3();
  9558. }
  9559. return target.copy( point ).clamp( this.min, this.max );
  9560. },
  9561. distanceToPoint: function ( point ) {
  9562. var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  9563. return clampedPoint.sub( point ).length();
  9564. },
  9565. getBoundingSphere: function ( target ) {
  9566. if ( target === undefined ) {
  9567. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  9568. //target = new Sphere(); // removed to avoid cyclic dependency
  9569. }
  9570. this.getCenter( target.center );
  9571. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  9572. return target;
  9573. },
  9574. intersect: function ( box ) {
  9575. this.min.max( box.min );
  9576. this.max.min( box.max );
  9577. // 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.
  9578. if ( this.isEmpty() ) { this.makeEmpty(); }
  9579. return this;
  9580. },
  9581. union: function ( box ) {
  9582. this.min.min( box.min );
  9583. this.max.max( box.max );
  9584. return this;
  9585. },
  9586. applyMatrix4: function ( matrix ) {
  9587. // transform of empty box is an empty box.
  9588. if ( this.isEmpty() ) { return this; }
  9589. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9590. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9591. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9592. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9593. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9594. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9595. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9596. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9597. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9598. this.setFromPoints( _points );
  9599. return this;
  9600. },
  9601. translate: function ( offset ) {
  9602. this.min.add( offset );
  9603. this.max.add( offset );
  9604. return this;
  9605. },
  9606. equals: function ( box ) {
  9607. return box.min.equals( this.min ) && box.max.equals( this.max );
  9608. }
  9609. } );
  9610. function satForAxes( axes, v0, v1, v2, extents ) {
  9611. for ( var i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  9612. _testAxis.fromArray( axes, i );
  9613. // project the aabb onto the seperating axis
  9614. var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  9615. // project all 3 vertices of the triangle onto the seperating axis
  9616. var p0 = v0.dot( _testAxis );
  9617. var p1 = v1.dot( _testAxis );
  9618. var p2 = v2.dot( _testAxis );
  9619. // actual test, basically see if either of the most extreme of the triangle points intersects r
  9620. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  9621. // points of the projected triangle are outside the projected half-length of the aabb
  9622. // the axis is seperating and we can exit
  9623. return false;
  9624. }
  9625. }
  9626. return true;
  9627. }
  9628. var _box$1 = new Box3();
  9629. function Sphere( center, radius ) {
  9630. this.center = ( center !== undefined ) ? center : new Vector3();
  9631. this.radius = ( radius !== undefined ) ? radius : - 1;
  9632. }
  9633. Object.assign( Sphere.prototype, {
  9634. set: function ( center, radius ) {
  9635. this.center.copy( center );
  9636. this.radius = radius;
  9637. return this;
  9638. },
  9639. setFromPoints: function ( points, optionalCenter ) {
  9640. var center = this.center;
  9641. if ( optionalCenter !== undefined ) {
  9642. center.copy( optionalCenter );
  9643. } else {
  9644. _box$1.setFromPoints( points ).getCenter( center );
  9645. }
  9646. var maxRadiusSq = 0;
  9647. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9648. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9649. }
  9650. this.radius = Math.sqrt( maxRadiusSq );
  9651. return this;
  9652. },
  9653. clone: function () {
  9654. return new this.constructor().copy( this );
  9655. },
  9656. copy: function ( sphere ) {
  9657. this.center.copy( sphere.center );
  9658. this.radius = sphere.radius;
  9659. return this;
  9660. },
  9661. isEmpty: function () {
  9662. return ( this.radius < 0 );
  9663. },
  9664. makeEmpty: function () {
  9665. this.center.set( 0, 0, 0 );
  9666. this.radius = - 1;
  9667. return this;
  9668. },
  9669. containsPoint: function ( point ) {
  9670. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9671. },
  9672. distanceToPoint: function ( point ) {
  9673. return ( point.distanceTo( this.center ) - this.radius );
  9674. },
  9675. intersectsSphere: function ( sphere ) {
  9676. var radiusSum = this.radius + sphere.radius;
  9677. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9678. },
  9679. intersectsBox: function ( box ) {
  9680. return box.intersectsSphere( this );
  9681. },
  9682. intersectsPlane: function ( plane ) {
  9683. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  9684. },
  9685. clampPoint: function ( point, target ) {
  9686. var deltaLengthSq = this.center.distanceToSquared( point );
  9687. if ( target === undefined ) {
  9688. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  9689. target = new Vector3();
  9690. }
  9691. target.copy( point );
  9692. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9693. target.sub( this.center ).normalize();
  9694. target.multiplyScalar( this.radius ).add( this.center );
  9695. }
  9696. return target;
  9697. },
  9698. getBoundingBox: function ( target ) {
  9699. if ( target === undefined ) {
  9700. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  9701. target = new Box3();
  9702. }
  9703. if ( this.isEmpty() ) {
  9704. // Empty sphere produces empty bounding box
  9705. target.makeEmpty();
  9706. return target;
  9707. }
  9708. target.set( this.center, this.center );
  9709. target.expandByScalar( this.radius );
  9710. return target;
  9711. },
  9712. applyMatrix4: function ( matrix ) {
  9713. this.center.applyMatrix4( matrix );
  9714. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9715. return this;
  9716. },
  9717. translate: function ( offset ) {
  9718. this.center.add( offset );
  9719. return this;
  9720. },
  9721. equals: function ( sphere ) {
  9722. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9723. }
  9724. } );
  9725. var _vector$2 = new Vector3();
  9726. var _segCenter = new Vector3();
  9727. var _segDir = new Vector3();
  9728. var _diff = new Vector3();
  9729. var _edge1 = new Vector3();
  9730. var _edge2 = new Vector3();
  9731. var _normal = new Vector3();
  9732. function Ray( origin, direction ) {
  9733. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  9734. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  9735. }
  9736. Object.assign( Ray.prototype, {
  9737. set: function ( origin, direction ) {
  9738. this.origin.copy( origin );
  9739. this.direction.copy( direction );
  9740. return this;
  9741. },
  9742. clone: function () {
  9743. return new this.constructor().copy( this );
  9744. },
  9745. copy: function ( ray ) {
  9746. this.origin.copy( ray.origin );
  9747. this.direction.copy( ray.direction );
  9748. return this;
  9749. },
  9750. at: function ( t, target ) {
  9751. if ( target === undefined ) {
  9752. console.warn( 'THREE.Ray: .at() target is now required' );
  9753. target = new Vector3();
  9754. }
  9755. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9756. },
  9757. lookAt: function ( v ) {
  9758. this.direction.copy( v ).sub( this.origin ).normalize();
  9759. return this;
  9760. },
  9761. recast: function ( t ) {
  9762. this.origin.copy( this.at( t, _vector$2 ) );
  9763. return this;
  9764. },
  9765. closestPointToPoint: function ( point, target ) {
  9766. if ( target === undefined ) {
  9767. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  9768. target = new Vector3();
  9769. }
  9770. target.subVectors( point, this.origin );
  9771. var directionDistance = target.dot( this.direction );
  9772. if ( directionDistance < 0 ) {
  9773. return target.copy( this.origin );
  9774. }
  9775. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9776. },
  9777. distanceToPoint: function ( point ) {
  9778. return Math.sqrt( this.distanceSqToPoint( point ) );
  9779. },
  9780. distanceSqToPoint: function ( point ) {
  9781. var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  9782. // point behind the ray
  9783. if ( directionDistance < 0 ) {
  9784. return this.origin.distanceToSquared( point );
  9785. }
  9786. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9787. return _vector$2.distanceToSquared( point );
  9788. },
  9789. distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9790. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9791. // It returns the min distance between the ray and the segment
  9792. // defined by v0 and v1
  9793. // It can also set two optional targets :
  9794. // - The closest point on the ray
  9795. // - The closest point on the segment
  9796. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9797. _segDir.copy( v1 ).sub( v0 ).normalize();
  9798. _diff.copy( this.origin ).sub( _segCenter );
  9799. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9800. var a01 = - this.direction.dot( _segDir );
  9801. var b0 = _diff.dot( this.direction );
  9802. var b1 = - _diff.dot( _segDir );
  9803. var c = _diff.lengthSq();
  9804. var det = Math.abs( 1 - a01 * a01 );
  9805. var s0, s1, sqrDist, extDet;
  9806. if ( det > 0 ) {
  9807. // The ray and segment are not parallel.
  9808. s0 = a01 * b1 - b0;
  9809. s1 = a01 * b0 - b1;
  9810. extDet = segExtent * det;
  9811. if ( s0 >= 0 ) {
  9812. if ( s1 >= - extDet ) {
  9813. if ( s1 <= extDet ) {
  9814. // region 0
  9815. // Minimum at interior points of ray and segment.
  9816. var invDet = 1 / det;
  9817. s0 *= invDet;
  9818. s1 *= invDet;
  9819. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9820. } else {
  9821. // region 1
  9822. s1 = segExtent;
  9823. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9824. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9825. }
  9826. } else {
  9827. // region 5
  9828. s1 = - segExtent;
  9829. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9830. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9831. }
  9832. } else {
  9833. if ( s1 <= - extDet ) {
  9834. // region 4
  9835. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9836. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9837. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9838. } else if ( s1 <= extDet ) {
  9839. // region 3
  9840. s0 = 0;
  9841. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9842. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9843. } else {
  9844. // region 2
  9845. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9846. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9847. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9848. }
  9849. }
  9850. } else {
  9851. // Ray and segment are parallel.
  9852. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9853. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9854. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9855. }
  9856. if ( optionalPointOnRay ) {
  9857. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9858. }
  9859. if ( optionalPointOnSegment ) {
  9860. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  9861. }
  9862. return sqrDist;
  9863. },
  9864. intersectSphere: function ( sphere, target ) {
  9865. _vector$2.subVectors( sphere.center, this.origin );
  9866. var tca = _vector$2.dot( this.direction );
  9867. var d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  9868. var radius2 = sphere.radius * sphere.radius;
  9869. if ( d2 > radius2 ) { return null; }
  9870. var thc = Math.sqrt( radius2 - d2 );
  9871. // t0 = first intersect point - entrance on front of sphere
  9872. var t0 = tca - thc;
  9873. // t1 = second intersect point - exit point on back of sphere
  9874. var t1 = tca + thc;
  9875. // test to see if both t0 and t1 are behind the ray - if so, return null
  9876. if ( t0 < 0 && t1 < 0 ) { return null; }
  9877. // test to see if t0 is behind the ray:
  9878. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9879. // in order to always return an intersect point that is in front of the ray.
  9880. if ( t0 < 0 ) { return this.at( t1, target ); }
  9881. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9882. return this.at( t0, target );
  9883. },
  9884. intersectsSphere: function ( sphere ) {
  9885. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  9886. },
  9887. distanceToPlane: function ( plane ) {
  9888. var denominator = plane.normal.dot( this.direction );
  9889. if ( denominator === 0 ) {
  9890. // line is coplanar, return origin
  9891. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9892. return 0;
  9893. }
  9894. // Null is preferable to undefined since undefined means.... it is undefined
  9895. return null;
  9896. }
  9897. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9898. // Return if the ray never intersects the plane
  9899. return t >= 0 ? t : null;
  9900. },
  9901. intersectPlane: function ( plane, target ) {
  9902. var t = this.distanceToPlane( plane );
  9903. if ( t === null ) {
  9904. return null;
  9905. }
  9906. return this.at( t, target );
  9907. },
  9908. intersectsPlane: function ( plane ) {
  9909. // check if the ray lies on the plane first
  9910. var distToPoint = plane.distanceToPoint( this.origin );
  9911. if ( distToPoint === 0 ) {
  9912. return true;
  9913. }
  9914. var denominator = plane.normal.dot( this.direction );
  9915. if ( denominator * distToPoint < 0 ) {
  9916. return true;
  9917. }
  9918. // ray origin is behind the plane (and is pointing behind it)
  9919. return false;
  9920. },
  9921. intersectBox: function ( box, target ) {
  9922. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9923. var invdirx = 1 / this.direction.x,
  9924. invdiry = 1 / this.direction.y,
  9925. invdirz = 1 / this.direction.z;
  9926. var origin = this.origin;
  9927. if ( invdirx >= 0 ) {
  9928. tmin = ( box.min.x - origin.x ) * invdirx;
  9929. tmax = ( box.max.x - origin.x ) * invdirx;
  9930. } else {
  9931. tmin = ( box.max.x - origin.x ) * invdirx;
  9932. tmax = ( box.min.x - origin.x ) * invdirx;
  9933. }
  9934. if ( invdiry >= 0 ) {
  9935. tymin = ( box.min.y - origin.y ) * invdiry;
  9936. tymax = ( box.max.y - origin.y ) * invdiry;
  9937. } else {
  9938. tymin = ( box.max.y - origin.y ) * invdiry;
  9939. tymax = ( box.min.y - origin.y ) * invdiry;
  9940. }
  9941. if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; }
  9942. // These lines also handle the case where tmin or tmax is NaN
  9943. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9944. if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; }
  9945. if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; }
  9946. if ( invdirz >= 0 ) {
  9947. tzmin = ( box.min.z - origin.z ) * invdirz;
  9948. tzmax = ( box.max.z - origin.z ) * invdirz;
  9949. } else {
  9950. tzmin = ( box.max.z - origin.z ) * invdirz;
  9951. tzmax = ( box.min.z - origin.z ) * invdirz;
  9952. }
  9953. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; }
  9954. if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; }
  9955. if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; }
  9956. //return point closest to the ray (positive side)
  9957. if ( tmax < 0 ) { return null; }
  9958. return this.at( tmin >= 0 ? tmin : tmax, target );
  9959. },
  9960. intersectsBox: function ( box ) {
  9961. return this.intersectBox( box, _vector$2 ) !== null;
  9962. },
  9963. intersectTriangle: function ( a, b, c, backfaceCulling, target ) {
  9964. // Compute the offset origin, edges, and normal.
  9965. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9966. _edge1.subVectors( b, a );
  9967. _edge2.subVectors( c, a );
  9968. _normal.crossVectors( _edge1, _edge2 );
  9969. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9970. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9971. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9972. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9973. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9974. var DdN = this.direction.dot( _normal );
  9975. var sign;
  9976. if ( DdN > 0 ) {
  9977. if ( backfaceCulling ) { return null; }
  9978. sign = 1;
  9979. } else if ( DdN < 0 ) {
  9980. sign = - 1;
  9981. DdN = - DdN;
  9982. } else {
  9983. return null;
  9984. }
  9985. _diff.subVectors( this.origin, a );
  9986. var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  9987. // b1 < 0, no intersection
  9988. if ( DdQxE2 < 0 ) {
  9989. return null;
  9990. }
  9991. var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  9992. // b2 < 0, no intersection
  9993. if ( DdE1xQ < 0 ) {
  9994. return null;
  9995. }
  9996. // b1+b2 > 1, no intersection
  9997. if ( DdQxE2 + DdE1xQ > DdN ) {
  9998. return null;
  9999. }
  10000. // Line intersects triangle, check if ray does.
  10001. var QdN = - sign * _diff.dot( _normal );
  10002. // t < 0, no intersection
  10003. if ( QdN < 0 ) {
  10004. return null;
  10005. }
  10006. // Ray intersects triangle.
  10007. return this.at( QdN / DdN, target );
  10008. },
  10009. applyMatrix4: function ( matrix4 ) {
  10010. this.origin.applyMatrix4( matrix4 );
  10011. this.direction.transformDirection( matrix4 );
  10012. return this;
  10013. },
  10014. equals: function ( ray ) {
  10015. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10016. }
  10017. } );
  10018. var _vector1 = new Vector3();
  10019. var _vector2 = new Vector3();
  10020. var _normalMatrix = new Matrix3();
  10021. function Plane( normal, constant ) {
  10022. // normal is assumed to be normalized
  10023. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  10024. this.constant = ( constant !== undefined ) ? constant : 0;
  10025. }
  10026. Object.assign( Plane.prototype, {
  10027. isPlane: true,
  10028. set: function ( normal, constant ) {
  10029. this.normal.copy( normal );
  10030. this.constant = constant;
  10031. return this;
  10032. },
  10033. setComponents: function ( x, y, z, w ) {
  10034. this.normal.set( x, y, z );
  10035. this.constant = w;
  10036. return this;
  10037. },
  10038. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  10039. this.normal.copy( normal );
  10040. this.constant = - point.dot( this.normal );
  10041. return this;
  10042. },
  10043. setFromCoplanarPoints: function ( a, b, c ) {
  10044. var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  10045. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  10046. this.setFromNormalAndCoplanarPoint( normal, a );
  10047. return this;
  10048. },
  10049. clone: function () {
  10050. return new this.constructor().copy( this );
  10051. },
  10052. copy: function ( plane ) {
  10053. this.normal.copy( plane.normal );
  10054. this.constant = plane.constant;
  10055. return this;
  10056. },
  10057. normalize: function () {
  10058. // Note: will lead to a divide by zero if the plane is invalid.
  10059. var inverseNormalLength = 1.0 / this.normal.length();
  10060. this.normal.multiplyScalar( inverseNormalLength );
  10061. this.constant *= inverseNormalLength;
  10062. return this;
  10063. },
  10064. negate: function () {
  10065. this.constant *= - 1;
  10066. this.normal.negate();
  10067. return this;
  10068. },
  10069. distanceToPoint: function ( point ) {
  10070. return this.normal.dot( point ) + this.constant;
  10071. },
  10072. distanceToSphere: function ( sphere ) {
  10073. return this.distanceToPoint( sphere.center ) - sphere.radius;
  10074. },
  10075. projectPoint: function ( point, target ) {
  10076. if ( target === undefined ) {
  10077. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  10078. target = new Vector3();
  10079. }
  10080. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  10081. },
  10082. intersectLine: function ( line, target ) {
  10083. if ( target === undefined ) {
  10084. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  10085. target = new Vector3();
  10086. }
  10087. var direction = line.delta( _vector1 );
  10088. var denominator = this.normal.dot( direction );
  10089. if ( denominator === 0 ) {
  10090. // line is coplanar, return origin
  10091. if ( this.distanceToPoint( line.start ) === 0 ) {
  10092. return target.copy( line.start );
  10093. }
  10094. // Unsure if this is the correct method to handle this case.
  10095. return undefined;
  10096. }
  10097. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  10098. if ( t < 0 || t > 1 ) {
  10099. return undefined;
  10100. }
  10101. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  10102. },
  10103. intersectsLine: function ( line ) {
  10104. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10105. var startSign = this.distanceToPoint( line.start );
  10106. var endSign = this.distanceToPoint( line.end );
  10107. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  10108. },
  10109. intersectsBox: function ( box ) {
  10110. return box.intersectsPlane( this );
  10111. },
  10112. intersectsSphere: function ( sphere ) {
  10113. return sphere.intersectsPlane( this );
  10114. },
  10115. coplanarPoint: function ( target ) {
  10116. if ( target === undefined ) {
  10117. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  10118. target = new Vector3();
  10119. }
  10120. return target.copy( this.normal ).multiplyScalar( - this.constant );
  10121. },
  10122. applyMatrix4: function ( matrix, optionalNormalMatrix ) {
  10123. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  10124. var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  10125. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  10126. this.constant = - referencePoint.dot( normal );
  10127. return this;
  10128. },
  10129. translate: function ( offset ) {
  10130. this.constant -= offset.dot( this.normal );
  10131. return this;
  10132. },
  10133. equals: function ( plane ) {
  10134. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  10135. }
  10136. } );
  10137. var _v0$1 = new Vector3();
  10138. var _v1$3 = new Vector3();
  10139. var _v2$1 = new Vector3();
  10140. var _v3 = new Vector3();
  10141. var _vab = new Vector3();
  10142. var _vac = new Vector3();
  10143. var _vbc = new Vector3();
  10144. var _vap = new Vector3();
  10145. var _vbp = new Vector3();
  10146. var _vcp = new Vector3();
  10147. function Triangle( a, b, c ) {
  10148. this.a = ( a !== undefined ) ? a : new Vector3();
  10149. this.b = ( b !== undefined ) ? b : new Vector3();
  10150. this.c = ( c !== undefined ) ? c : new Vector3();
  10151. }
  10152. Object.assign( Triangle, {
  10153. getNormal: function ( a, b, c, target ) {
  10154. if ( target === undefined ) {
  10155. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  10156. target = new Vector3();
  10157. }
  10158. target.subVectors( c, b );
  10159. _v0$1.subVectors( a, b );
  10160. target.cross( _v0$1 );
  10161. var targetLengthSq = target.lengthSq();
  10162. if ( targetLengthSq > 0 ) {
  10163. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  10164. }
  10165. return target.set( 0, 0, 0 );
  10166. },
  10167. // static/instance method to calculate barycentric coordinates
  10168. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10169. getBarycoord: function ( point, a, b, c, target ) {
  10170. _v0$1.subVectors( c, a );
  10171. _v1$3.subVectors( b, a );
  10172. _v2$1.subVectors( point, a );
  10173. var dot00 = _v0$1.dot( _v0$1 );
  10174. var dot01 = _v0$1.dot( _v1$3 );
  10175. var dot02 = _v0$1.dot( _v2$1 );
  10176. var dot11 = _v1$3.dot( _v1$3 );
  10177. var dot12 = _v1$3.dot( _v2$1 );
  10178. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10179. if ( target === undefined ) {
  10180. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  10181. target = new Vector3();
  10182. }
  10183. // collinear or singular triangle
  10184. if ( denom === 0 ) {
  10185. // arbitrary location outside of triangle?
  10186. // not sure if this is the best idea, maybe should be returning undefined
  10187. return target.set( - 2, - 1, - 1 );
  10188. }
  10189. var invDenom = 1 / denom;
  10190. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10191. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10192. // barycentric coordinates must always sum to 1
  10193. return target.set( 1 - u - v, v, u );
  10194. },
  10195. containsPoint: function ( point, a, b, c ) {
  10196. Triangle.getBarycoord( point, a, b, c, _v3 );
  10197. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  10198. },
  10199. getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  10200. this.getBarycoord( point, p1, p2, p3, _v3 );
  10201. target.set( 0, 0 );
  10202. target.addScaledVector( uv1, _v3.x );
  10203. target.addScaledVector( uv2, _v3.y );
  10204. target.addScaledVector( uv3, _v3.z );
  10205. return target;
  10206. },
  10207. isFrontFacing: function ( a, b, c, direction ) {
  10208. _v0$1.subVectors( c, b );
  10209. _v1$3.subVectors( a, b );
  10210. // strictly front facing
  10211. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  10212. }
  10213. } );
  10214. Object.assign( Triangle.prototype, {
  10215. set: function ( a, b, c ) {
  10216. this.a.copy( a );
  10217. this.b.copy( b );
  10218. this.c.copy( c );
  10219. return this;
  10220. },
  10221. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10222. this.a.copy( points[ i0 ] );
  10223. this.b.copy( points[ i1 ] );
  10224. this.c.copy( points[ i2 ] );
  10225. return this;
  10226. },
  10227. clone: function () {
  10228. return new this.constructor().copy( this );
  10229. },
  10230. copy: function ( triangle ) {
  10231. this.a.copy( triangle.a );
  10232. this.b.copy( triangle.b );
  10233. this.c.copy( triangle.c );
  10234. return this;
  10235. },
  10236. getArea: function () {
  10237. _v0$1.subVectors( this.c, this.b );
  10238. _v1$3.subVectors( this.a, this.b );
  10239. return _v0$1.cross( _v1$3 ).length() * 0.5;
  10240. },
  10241. getMidpoint: function ( target ) {
  10242. if ( target === undefined ) {
  10243. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  10244. target = new Vector3();
  10245. }
  10246. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10247. },
  10248. getNormal: function ( target ) {
  10249. return Triangle.getNormal( this.a, this.b, this.c, target );
  10250. },
  10251. getPlane: function ( target ) {
  10252. if ( target === undefined ) {
  10253. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  10254. target = new Plane();
  10255. }
  10256. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  10257. },
  10258. getBarycoord: function ( point, target ) {
  10259. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  10260. },
  10261. getUV: function ( point, uv1, uv2, uv3, target ) {
  10262. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  10263. },
  10264. containsPoint: function ( point ) {
  10265. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10266. },
  10267. isFrontFacing: function ( direction ) {
  10268. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  10269. },
  10270. intersectsBox: function ( box ) {
  10271. return box.intersectsTriangle( this );
  10272. },
  10273. closestPointToPoint: function ( p, target ) {
  10274. if ( target === undefined ) {
  10275. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  10276. target = new Vector3();
  10277. }
  10278. var a = this.a, b = this.b, c = this.c;
  10279. var v, w;
  10280. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  10281. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  10282. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  10283. // basically, we're distinguishing which of the voronoi regions of the triangle
  10284. // the point lies in with the minimum amount of redundant computation.
  10285. _vab.subVectors( b, a );
  10286. _vac.subVectors( c, a );
  10287. _vap.subVectors( p, a );
  10288. var d1 = _vab.dot( _vap );
  10289. var d2 = _vac.dot( _vap );
  10290. if ( d1 <= 0 && d2 <= 0 ) {
  10291. // vertex region of A; barycentric coords (1, 0, 0)
  10292. return target.copy( a );
  10293. }
  10294. _vbp.subVectors( p, b );
  10295. var d3 = _vab.dot( _vbp );
  10296. var d4 = _vac.dot( _vbp );
  10297. if ( d3 >= 0 && d4 <= d3 ) {
  10298. // vertex region of B; barycentric coords (0, 1, 0)
  10299. return target.copy( b );
  10300. }
  10301. var vc = d1 * d4 - d3 * d2;
  10302. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  10303. v = d1 / ( d1 - d3 );
  10304. // edge region of AB; barycentric coords (1-v, v, 0)
  10305. return target.copy( a ).addScaledVector( _vab, v );
  10306. }
  10307. _vcp.subVectors( p, c );
  10308. var d5 = _vab.dot( _vcp );
  10309. var d6 = _vac.dot( _vcp );
  10310. if ( d6 >= 0 && d5 <= d6 ) {
  10311. // vertex region of C; barycentric coords (0, 0, 1)
  10312. return target.copy( c );
  10313. }
  10314. var vb = d5 * d2 - d1 * d6;
  10315. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  10316. w = d2 / ( d2 - d6 );
  10317. // edge region of AC; barycentric coords (1-w, 0, w)
  10318. return target.copy( a ).addScaledVector( _vac, w );
  10319. }
  10320. var va = d3 * d6 - d5 * d4;
  10321. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  10322. _vbc.subVectors( c, b );
  10323. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  10324. // edge region of BC; barycentric coords (0, 1-w, w)
  10325. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  10326. }
  10327. // face region
  10328. var denom = 1 / ( va + vb + vc );
  10329. // u = va * denom
  10330. v = vb * denom;
  10331. w = vc * denom;
  10332. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  10333. },
  10334. equals: function ( triangle ) {
  10335. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  10336. }
  10337. } );
  10338. var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10339. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10340. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10341. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10342. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10343. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10344. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10345. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10346. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10347. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10348. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10349. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10350. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10351. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10352. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10353. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10354. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10355. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10356. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10357. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10358. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10359. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10360. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10361. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10362. var _hslA = { h: 0, s: 0, l: 0 };
  10363. var _hslB = { h: 0, s: 0, l: 0 };
  10364. function Color( r, g, b ) {
  10365. if ( g === undefined && b === undefined ) {
  10366. // r is THREE.Color, hex or string
  10367. return this.set( r );
  10368. }
  10369. return this.setRGB( r, g, b );
  10370. }
  10371. function hue2rgb( p, q, t ) {
  10372. if ( t < 0 ) { t += 1; }
  10373. if ( t > 1 ) { t -= 1; }
  10374. if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; }
  10375. if ( t < 1 / 2 ) { return q; }
  10376. if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); }
  10377. return p;
  10378. }
  10379. function SRGBToLinear( c ) {
  10380. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  10381. }
  10382. function LinearToSRGB( c ) {
  10383. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  10384. }
  10385. Object.assign( Color.prototype, {
  10386. isColor: true,
  10387. r: 1, g: 1, b: 1,
  10388. set: function ( value ) {
  10389. if ( value && value.isColor ) {
  10390. this.copy( value );
  10391. } else if ( typeof value === 'number' ) {
  10392. this.setHex( value );
  10393. } else if ( typeof value === 'string' ) {
  10394. this.setStyle( value );
  10395. }
  10396. return this;
  10397. },
  10398. setScalar: function ( scalar ) {
  10399. this.r = scalar;
  10400. this.g = scalar;
  10401. this.b = scalar;
  10402. return this;
  10403. },
  10404. setHex: function ( hex ) {
  10405. hex = Math.floor( hex );
  10406. this.r = ( hex >> 16 & 255 ) / 255;
  10407. this.g = ( hex >> 8 & 255 ) / 255;
  10408. this.b = ( hex & 255 ) / 255;
  10409. return this;
  10410. },
  10411. setRGB: function ( r, g, b ) {
  10412. this.r = r;
  10413. this.g = g;
  10414. this.b = b;
  10415. return this;
  10416. },
  10417. setHSL: function ( h, s, l ) {
  10418. // h,s,l ranges are in 0.0 - 1.0
  10419. h = MathUtils.euclideanModulo( h, 1 );
  10420. s = MathUtils.clamp( s, 0, 1 );
  10421. l = MathUtils.clamp( l, 0, 1 );
  10422. if ( s === 0 ) {
  10423. this.r = this.g = this.b = l;
  10424. } else {
  10425. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10426. var q = ( 2 * l ) - p;
  10427. this.r = hue2rgb( q, p, h + 1 / 3 );
  10428. this.g = hue2rgb( q, p, h );
  10429. this.b = hue2rgb( q, p, h - 1 / 3 );
  10430. }
  10431. return this;
  10432. },
  10433. setStyle: function ( style ) {
  10434. function handleAlpha( string ) {
  10435. if ( string === undefined ) { return; }
  10436. if ( parseFloat( string ) < 1 ) {
  10437. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  10438. }
  10439. }
  10440. var m;
  10441. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  10442. // rgb / hsl
  10443. var color;
  10444. var name = m[ 1 ];
  10445. var components = m[ 2 ];
  10446. switch ( name ) {
  10447. case 'rgb':
  10448. case 'rgba':
  10449. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10450. // rgb(255,0,0) rgba(255,0,0,0.5)
  10451. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  10452. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  10453. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  10454. handleAlpha( color[ 5 ] );
  10455. return this;
  10456. }
  10457. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10458. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10459. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  10460. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  10461. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  10462. handleAlpha( color[ 5 ] );
  10463. return this;
  10464. }
  10465. break;
  10466. case 'hsl':
  10467. case 'hsla':
  10468. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10469. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10470. var h = parseFloat( color[ 1 ] ) / 360;
  10471. var s = parseInt( color[ 2 ], 10 ) / 100;
  10472. var l = parseInt( color[ 3 ], 10 ) / 100;
  10473. handleAlpha( color[ 5 ] );
  10474. return this.setHSL( h, s, l );
  10475. }
  10476. break;
  10477. }
  10478. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  10479. // hex color
  10480. var hex = m[ 1 ];
  10481. var size = hex.length;
  10482. if ( size === 3 ) {
  10483. // #ff0
  10484. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  10485. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  10486. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  10487. return this;
  10488. } else if ( size === 6 ) {
  10489. // #ff0000
  10490. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  10491. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  10492. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  10493. return this;
  10494. }
  10495. }
  10496. if ( style && style.length > 0 ) {
  10497. return this.setColorName( style );
  10498. }
  10499. return this;
  10500. },
  10501. setColorName: function ( style ) {
  10502. // color keywords
  10503. var hex = _colorKeywords[ style ];
  10504. if ( hex !== undefined ) {
  10505. // red
  10506. this.setHex( hex );
  10507. } else {
  10508. // unknown color
  10509. console.warn( 'THREE.Color: Unknown color ' + style );
  10510. }
  10511. return this;
  10512. },
  10513. clone: function () {
  10514. return new this.constructor( this.r, this.g, this.b );
  10515. },
  10516. copy: function ( color ) {
  10517. this.r = color.r;
  10518. this.g = color.g;
  10519. this.b = color.b;
  10520. return this;
  10521. },
  10522. copyGammaToLinear: function ( color, gammaFactor ) {
  10523. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10524. this.r = Math.pow( color.r, gammaFactor );
  10525. this.g = Math.pow( color.g, gammaFactor );
  10526. this.b = Math.pow( color.b, gammaFactor );
  10527. return this;
  10528. },
  10529. copyLinearToGamma: function ( color, gammaFactor ) {
  10530. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10531. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  10532. this.r = Math.pow( color.r, safeInverse );
  10533. this.g = Math.pow( color.g, safeInverse );
  10534. this.b = Math.pow( color.b, safeInverse );
  10535. return this;
  10536. },
  10537. convertGammaToLinear: function ( gammaFactor ) {
  10538. this.copyGammaToLinear( this, gammaFactor );
  10539. return this;
  10540. },
  10541. convertLinearToGamma: function ( gammaFactor ) {
  10542. this.copyLinearToGamma( this, gammaFactor );
  10543. return this;
  10544. },
  10545. copySRGBToLinear: function ( color ) {
  10546. this.r = SRGBToLinear( color.r );
  10547. this.g = SRGBToLinear( color.g );
  10548. this.b = SRGBToLinear( color.b );
  10549. return this;
  10550. },
  10551. copyLinearToSRGB: function ( color ) {
  10552. this.r = LinearToSRGB( color.r );
  10553. this.g = LinearToSRGB( color.g );
  10554. this.b = LinearToSRGB( color.b );
  10555. return this;
  10556. },
  10557. convertSRGBToLinear: function () {
  10558. this.copySRGBToLinear( this );
  10559. return this;
  10560. },
  10561. convertLinearToSRGB: function () {
  10562. this.copyLinearToSRGB( this );
  10563. return this;
  10564. },
  10565. getHex: function () {
  10566. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  10567. },
  10568. getHexString: function () {
  10569. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  10570. },
  10571. getHSL: function ( target ) {
  10572. // h,s,l ranges are in 0.0 - 1.0
  10573. if ( target === undefined ) {
  10574. console.warn( 'THREE.Color: .getHSL() target is now required' );
  10575. target = { h: 0, s: 0, l: 0 };
  10576. }
  10577. var r = this.r, g = this.g, b = this.b;
  10578. var max = Math.max( r, g, b );
  10579. var min = Math.min( r, g, b );
  10580. var hue, saturation;
  10581. var lightness = ( min + max ) / 2.0;
  10582. if ( min === max ) {
  10583. hue = 0;
  10584. saturation = 0;
  10585. } else {
  10586. var delta = max - min;
  10587. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10588. switch ( max ) {
  10589. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10590. case g: hue = ( b - r ) / delta + 2; break;
  10591. case b: hue = ( r - g ) / delta + 4; break;
  10592. }
  10593. hue /= 6;
  10594. }
  10595. target.h = hue;
  10596. target.s = saturation;
  10597. target.l = lightness;
  10598. return target;
  10599. },
  10600. getStyle: function () {
  10601. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  10602. },
  10603. offsetHSL: function ( h, s, l ) {
  10604. this.getHSL( _hslA );
  10605. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  10606. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  10607. return this;
  10608. },
  10609. add: function ( color ) {
  10610. this.r += color.r;
  10611. this.g += color.g;
  10612. this.b += color.b;
  10613. return this;
  10614. },
  10615. addColors: function ( color1, color2 ) {
  10616. this.r = color1.r + color2.r;
  10617. this.g = color1.g + color2.g;
  10618. this.b = color1.b + color2.b;
  10619. return this;
  10620. },
  10621. addScalar: function ( s ) {
  10622. this.r += s;
  10623. this.g += s;
  10624. this.b += s;
  10625. return this;
  10626. },
  10627. sub: function ( color ) {
  10628. this.r = Math.max( 0, this.r - color.r );
  10629. this.g = Math.max( 0, this.g - color.g );
  10630. this.b = Math.max( 0, this.b - color.b );
  10631. return this;
  10632. },
  10633. multiply: function ( color ) {
  10634. this.r *= color.r;
  10635. this.g *= color.g;
  10636. this.b *= color.b;
  10637. return this;
  10638. },
  10639. multiplyScalar: function ( s ) {
  10640. this.r *= s;
  10641. this.g *= s;
  10642. this.b *= s;
  10643. return this;
  10644. },
  10645. lerp: function ( color, alpha ) {
  10646. this.r += ( color.r - this.r ) * alpha;
  10647. this.g += ( color.g - this.g ) * alpha;
  10648. this.b += ( color.b - this.b ) * alpha;
  10649. return this;
  10650. },
  10651. lerpHSL: function ( color, alpha ) {
  10652. this.getHSL( _hslA );
  10653. color.getHSL( _hslB );
  10654. var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  10655. var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  10656. var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  10657. this.setHSL( h, s, l );
  10658. return this;
  10659. },
  10660. equals: function ( c ) {
  10661. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  10662. },
  10663. fromArray: function ( array, offset ) {
  10664. if ( offset === undefined ) { offset = 0; }
  10665. this.r = array[ offset ];
  10666. this.g = array[ offset + 1 ];
  10667. this.b = array[ offset + 2 ];
  10668. return this;
  10669. },
  10670. toArray: function ( array, offset ) {
  10671. if ( array === undefined ) { array = []; }
  10672. if ( offset === undefined ) { offset = 0; }
  10673. array[ offset ] = this.r;
  10674. array[ offset + 1 ] = this.g;
  10675. array[ offset + 2 ] = this.b;
  10676. return array;
  10677. },
  10678. fromBufferAttribute: function ( attribute, index ) {
  10679. this.r = attribute.getX( index );
  10680. this.g = attribute.getY( index );
  10681. this.b = attribute.getZ( index );
  10682. if ( attribute.normalized === true ) {
  10683. // assuming Uint8Array
  10684. this.r /= 255;
  10685. this.g /= 255;
  10686. this.b /= 255;
  10687. }
  10688. return this;
  10689. },
  10690. toJSON: function () {
  10691. return this.getHex();
  10692. }
  10693. } );
  10694. Color.NAMES = _colorKeywords;
  10695. function Face3( a, b, c, normal, color, materialIndex ) {
  10696. this.a = a;
  10697. this.b = b;
  10698. this.c = c;
  10699. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  10700. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  10701. this.color = ( color && color.isColor ) ? color : new Color();
  10702. this.vertexColors = Array.isArray( color ) ? color : [];
  10703. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  10704. }
  10705. Object.assign( Face3.prototype, {
  10706. clone: function () {
  10707. return new this.constructor().copy( this );
  10708. },
  10709. copy: function ( source ) {
  10710. this.a = source.a;
  10711. this.b = source.b;
  10712. this.c = source.c;
  10713. this.normal.copy( source.normal );
  10714. this.color.copy( source.color );
  10715. this.materialIndex = source.materialIndex;
  10716. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  10717. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  10718. }
  10719. for ( var i$1 = 0, il$1 = source.vertexColors.length; i$1 < il$1; i$1 ++ ) {
  10720. this.vertexColors[ i$1 ] = source.vertexColors[ i$1 ].clone();
  10721. }
  10722. return this;
  10723. }
  10724. } );
  10725. var materialId = 0;
  10726. function Material() {
  10727. Object.defineProperty( this, 'id', { value: materialId ++ } );
  10728. this.uuid = MathUtils.generateUUID();
  10729. this.name = '';
  10730. this.type = 'Material';
  10731. this.fog = true;
  10732. this.blending = NormalBlending;
  10733. this.side = FrontSide;
  10734. this.flatShading = false;
  10735. this.vertexColors = false;
  10736. this.opacity = 1;
  10737. this.transparent = false;
  10738. this.blendSrc = SrcAlphaFactor;
  10739. this.blendDst = OneMinusSrcAlphaFactor;
  10740. this.blendEquation = AddEquation;
  10741. this.blendSrcAlpha = null;
  10742. this.blendDstAlpha = null;
  10743. this.blendEquationAlpha = null;
  10744. this.depthFunc = LessEqualDepth;
  10745. this.depthTest = true;
  10746. this.depthWrite = true;
  10747. this.stencilWriteMask = 0xff;
  10748. this.stencilFunc = AlwaysStencilFunc;
  10749. this.stencilRef = 0;
  10750. this.stencilFuncMask = 0xff;
  10751. this.stencilFail = KeepStencilOp;
  10752. this.stencilZFail = KeepStencilOp;
  10753. this.stencilZPass = KeepStencilOp;
  10754. this.stencilWrite = false;
  10755. this.clippingPlanes = null;
  10756. this.clipIntersection = false;
  10757. this.clipShadows = false;
  10758. this.shadowSide = null;
  10759. this.colorWrite = true;
  10760. this.precision = null; // override the renderer's default precision for this material
  10761. this.polygonOffset = false;
  10762. this.polygonOffsetFactor = 0;
  10763. this.polygonOffsetUnits = 0;
  10764. this.dithering = false;
  10765. this.alphaTest = 0;
  10766. this.premultipliedAlpha = false;
  10767. this.visible = true;
  10768. this.toneMapped = true;
  10769. this.userData = {};
  10770. this.version = 0;
  10771. }
  10772. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10773. constructor: Material,
  10774. isMaterial: true,
  10775. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  10776. customProgramCacheKey: function () {
  10777. return this.onBeforeCompile.toString();
  10778. },
  10779. setValues: function ( values ) {
  10780. if ( values === undefined ) { return; }
  10781. for ( var key in values ) {
  10782. var newValue = values[ key ];
  10783. if ( newValue === undefined ) {
  10784. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  10785. continue;
  10786. }
  10787. // for backward compatability if shading is set in the constructor
  10788. if ( key === 'shading' ) {
  10789. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  10790. this.flatShading = ( newValue === FlatShading ) ? true : false;
  10791. continue;
  10792. }
  10793. var currentValue = this[ key ];
  10794. if ( currentValue === undefined ) {
  10795. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  10796. continue;
  10797. }
  10798. if ( currentValue && currentValue.isColor ) {
  10799. currentValue.set( newValue );
  10800. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10801. currentValue.copy( newValue );
  10802. } else {
  10803. this[ key ] = newValue;
  10804. }
  10805. }
  10806. },
  10807. toJSON: function ( meta ) {
  10808. var isRoot = ( meta === undefined || typeof meta === 'string' );
  10809. if ( isRoot ) {
  10810. meta = {
  10811. textures: {},
  10812. images: {}
  10813. };
  10814. }
  10815. var data = {
  10816. metadata: {
  10817. version: 4.5,
  10818. type: 'Material',
  10819. generator: 'Material.toJSON'
  10820. }
  10821. };
  10822. // standard Material serialization
  10823. data.uuid = this.uuid;
  10824. data.type = this.type;
  10825. if ( this.name !== '' ) { data.name = this.name; }
  10826. if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); }
  10827. if ( this.roughness !== undefined ) { data.roughness = this.roughness; }
  10828. if ( this.metalness !== undefined ) { data.metalness = this.metalness; }
  10829. if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); }
  10830. if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); }
  10831. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; }
  10832. if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); }
  10833. if ( this.shininess !== undefined ) { data.shininess = this.shininess; }
  10834. if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; }
  10835. if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; }
  10836. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10837. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10838. }
  10839. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10840. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10841. }
  10842. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10843. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10844. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10845. }
  10846. if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; }
  10847. if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; }
  10848. if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; }
  10849. if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; }
  10850. if ( this.aoMap && this.aoMap.isTexture ) {
  10851. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10852. data.aoMapIntensity = this.aoMapIntensity;
  10853. }
  10854. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10855. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10856. data.bumpScale = this.bumpScale;
  10857. }
  10858. if ( this.normalMap && this.normalMap.isTexture ) {
  10859. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10860. data.normalMapType = this.normalMapType;
  10861. data.normalScale = this.normalScale.toArray();
  10862. }
  10863. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10864. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10865. data.displacementScale = this.displacementScale;
  10866. data.displacementBias = this.displacementBias;
  10867. }
  10868. if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; }
  10869. if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; }
  10870. if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; }
  10871. if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; }
  10872. if ( this.envMap && this.envMap.isTexture ) {
  10873. data.envMap = this.envMap.toJSON( meta ).uuid;
  10874. data.reflectivity = this.reflectivity; // Scale behind envMap
  10875. data.refractionRatio = this.refractionRatio;
  10876. if ( this.combine !== undefined ) { data.combine = this.combine; }
  10877. if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; }
  10878. }
  10879. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10880. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10881. }
  10882. if ( this.size !== undefined ) { data.size = this.size; }
  10883. if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; }
  10884. if ( this.blending !== NormalBlending ) { data.blending = this.blending; }
  10885. if ( this.flatShading === true ) { data.flatShading = this.flatShading; }
  10886. if ( this.side !== FrontSide ) { data.side = this.side; }
  10887. if ( this.vertexColors ) { data.vertexColors = true; }
  10888. if ( this.opacity < 1 ) { data.opacity = this.opacity; }
  10889. if ( this.transparent === true ) { data.transparent = this.transparent; }
  10890. data.depthFunc = this.depthFunc;
  10891. data.depthTest = this.depthTest;
  10892. data.depthWrite = this.depthWrite;
  10893. data.stencilWrite = this.stencilWrite;
  10894. data.stencilWriteMask = this.stencilWriteMask;
  10895. data.stencilFunc = this.stencilFunc;
  10896. data.stencilRef = this.stencilRef;
  10897. data.stencilFuncMask = this.stencilFuncMask;
  10898. data.stencilFail = this.stencilFail;
  10899. data.stencilZFail = this.stencilZFail;
  10900. data.stencilZPass = this.stencilZPass;
  10901. // rotation (SpriteMaterial)
  10902. if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; }
  10903. if ( this.polygonOffset === true ) { data.polygonOffset = true; }
  10904. if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; }
  10905. if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; }
  10906. if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; }
  10907. if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; }
  10908. if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; }
  10909. if ( this.scale !== undefined ) { data.scale = this.scale; }
  10910. if ( this.dithering === true ) { data.dithering = true; }
  10911. if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; }
  10912. if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; }
  10913. if ( this.wireframe === true ) { data.wireframe = this.wireframe; }
  10914. if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; }
  10915. if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; }
  10916. if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; }
  10917. if ( this.morphTargets === true ) { data.morphTargets = true; }
  10918. if ( this.morphNormals === true ) { data.morphNormals = true; }
  10919. if ( this.skinning === true ) { data.skinning = true; }
  10920. if ( this.visible === false ) { data.visible = false; }
  10921. if ( this.toneMapped === false ) { data.toneMapped = false; }
  10922. if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; }
  10923. // TODO: Copied from Object3D.toJSON
  10924. function extractFromCache( cache ) {
  10925. var values = [];
  10926. for ( var key in cache ) {
  10927. var data = cache[ key ];
  10928. delete data.metadata;
  10929. values.push( data );
  10930. }
  10931. return values;
  10932. }
  10933. if ( isRoot ) {
  10934. var textures = extractFromCache( meta.textures );
  10935. var images = extractFromCache( meta.images );
  10936. if ( textures.length > 0 ) { data.textures = textures; }
  10937. if ( images.length > 0 ) { data.images = images; }
  10938. }
  10939. return data;
  10940. },
  10941. clone: function () {
  10942. return new this.constructor().copy( this );
  10943. },
  10944. copy: function ( source ) {
  10945. this.name = source.name;
  10946. this.fog = source.fog;
  10947. this.blending = source.blending;
  10948. this.side = source.side;
  10949. this.flatShading = source.flatShading;
  10950. this.vertexColors = source.vertexColors;
  10951. this.opacity = source.opacity;
  10952. this.transparent = source.transparent;
  10953. this.blendSrc = source.blendSrc;
  10954. this.blendDst = source.blendDst;
  10955. this.blendEquation = source.blendEquation;
  10956. this.blendSrcAlpha = source.blendSrcAlpha;
  10957. this.blendDstAlpha = source.blendDstAlpha;
  10958. this.blendEquationAlpha = source.blendEquationAlpha;
  10959. this.depthFunc = source.depthFunc;
  10960. this.depthTest = source.depthTest;
  10961. this.depthWrite = source.depthWrite;
  10962. this.stencilWriteMask = source.stencilWriteMask;
  10963. this.stencilFunc = source.stencilFunc;
  10964. this.stencilRef = source.stencilRef;
  10965. this.stencilFuncMask = source.stencilFuncMask;
  10966. this.stencilFail = source.stencilFail;
  10967. this.stencilZFail = source.stencilZFail;
  10968. this.stencilZPass = source.stencilZPass;
  10969. this.stencilWrite = source.stencilWrite;
  10970. var srcPlanes = source.clippingPlanes;
  10971. var dstPlanes = null;
  10972. if ( srcPlanes !== null ) {
  10973. var n = srcPlanes.length;
  10974. dstPlanes = new Array( n );
  10975. for ( var i = 0; i !== n; ++ i ) {
  10976. dstPlanes[ i ] = srcPlanes[ i ].clone();
  10977. }
  10978. }
  10979. this.clippingPlanes = dstPlanes;
  10980. this.clipIntersection = source.clipIntersection;
  10981. this.clipShadows = source.clipShadows;
  10982. this.shadowSide = source.shadowSide;
  10983. this.colorWrite = source.colorWrite;
  10984. this.precision = source.precision;
  10985. this.polygonOffset = source.polygonOffset;
  10986. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10987. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10988. this.dithering = source.dithering;
  10989. this.alphaTest = source.alphaTest;
  10990. this.premultipliedAlpha = source.premultipliedAlpha;
  10991. this.visible = source.visible;
  10992. this.toneMapped = source.toneMapped;
  10993. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10994. return this;
  10995. },
  10996. dispose: function () {
  10997. this.dispatchEvent( { type: 'dispose' } );
  10998. }
  10999. } );
  11000. Object.defineProperty( Material.prototype, 'needsUpdate', {
  11001. set: function ( value ) {
  11002. if ( value === true ) { this.version ++; }
  11003. }
  11004. } );
  11005. /**
  11006. * parameters = {
  11007. * color: <hex>,
  11008. * opacity: <float>,
  11009. * map: new THREE.Texture( <Image> ),
  11010. *
  11011. * lightMap: new THREE.Texture( <Image> ),
  11012. * lightMapIntensity: <float>
  11013. *
  11014. * aoMap: new THREE.Texture( <Image> ),
  11015. * aoMapIntensity: <float>
  11016. *
  11017. * specularMap: new THREE.Texture( <Image> ),
  11018. *
  11019. * alphaMap: new THREE.Texture( <Image> ),
  11020. *
  11021. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  11022. * combine: THREE.Multiply,
  11023. * reflectivity: <float>,
  11024. * refractionRatio: <float>,
  11025. *
  11026. * depthTest: <bool>,
  11027. * depthWrite: <bool>,
  11028. *
  11029. * wireframe: <boolean>,
  11030. * wireframeLinewidth: <float>,
  11031. *
  11032. * skinning: <bool>,
  11033. * morphTargets: <bool>
  11034. * }
  11035. */
  11036. function MeshBasicMaterial( parameters ) {
  11037. Material.call( this );
  11038. this.type = 'MeshBasicMaterial';
  11039. this.color = new Color( 0xffffff ); // emissive
  11040. this.map = null;
  11041. this.lightMap = null;
  11042. this.lightMapIntensity = 1.0;
  11043. this.aoMap = null;
  11044. this.aoMapIntensity = 1.0;
  11045. this.specularMap = null;
  11046. this.alphaMap = null;
  11047. this.envMap = null;
  11048. this.combine = MultiplyOperation;
  11049. this.reflectivity = 1;
  11050. this.refractionRatio = 0.98;
  11051. this.wireframe = false;
  11052. this.wireframeLinewidth = 1;
  11053. this.wireframeLinecap = 'round';
  11054. this.wireframeLinejoin = 'round';
  11055. this.skinning = false;
  11056. this.morphTargets = false;
  11057. this.setValues( parameters );
  11058. }
  11059. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11060. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11061. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11062. MeshBasicMaterial.prototype.copy = function ( source ) {
  11063. Material.prototype.copy.call( this, source );
  11064. this.color.copy( source.color );
  11065. this.map = source.map;
  11066. this.lightMap = source.lightMap;
  11067. this.lightMapIntensity = source.lightMapIntensity;
  11068. this.aoMap = source.aoMap;
  11069. this.aoMapIntensity = source.aoMapIntensity;
  11070. this.specularMap = source.specularMap;
  11071. this.alphaMap = source.alphaMap;
  11072. this.envMap = source.envMap;
  11073. this.combine = source.combine;
  11074. this.reflectivity = source.reflectivity;
  11075. this.refractionRatio = source.refractionRatio;
  11076. this.wireframe = source.wireframe;
  11077. this.wireframeLinewidth = source.wireframeLinewidth;
  11078. this.wireframeLinecap = source.wireframeLinecap;
  11079. this.wireframeLinejoin = source.wireframeLinejoin;
  11080. this.skinning = source.skinning;
  11081. this.morphTargets = source.morphTargets;
  11082. return this;
  11083. };
  11084. var _vector$3 = new Vector3();
  11085. var _vector2$1 = new Vector2();
  11086. function BufferAttribute( array, itemSize, normalized ) {
  11087. if ( Array.isArray( array ) ) {
  11088. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11089. }
  11090. this.name = '';
  11091. this.array = array;
  11092. this.itemSize = itemSize;
  11093. this.count = array !== undefined ? array.length / itemSize : 0;
  11094. this.normalized = normalized === true;
  11095. this.usage = StaticDrawUsage;
  11096. this.updateRange = { offset: 0, count: - 1 };
  11097. this.version = 0;
  11098. }
  11099. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  11100. set: function ( value ) {
  11101. if ( value === true ) { this.version ++; }
  11102. }
  11103. } );
  11104. Object.assign( BufferAttribute.prototype, {
  11105. isBufferAttribute: true,
  11106. onUploadCallback: function () {},
  11107. setUsage: function ( value ) {
  11108. this.usage = value;
  11109. return this;
  11110. },
  11111. copy: function ( source ) {
  11112. this.name = source.name;
  11113. this.array = new source.array.constructor( source.array );
  11114. this.itemSize = source.itemSize;
  11115. this.count = source.count;
  11116. this.normalized = source.normalized;
  11117. this.usage = source.usage;
  11118. return this;
  11119. },
  11120. copyAt: function ( index1, attribute, index2 ) {
  11121. index1 *= this.itemSize;
  11122. index2 *= attribute.itemSize;
  11123. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11124. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11125. }
  11126. return this;
  11127. },
  11128. copyArray: function ( array ) {
  11129. this.array.set( array );
  11130. return this;
  11131. },
  11132. copyColorsArray: function ( colors ) {
  11133. var array = this.array;
  11134. var offset = 0;
  11135. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11136. var color = colors[ i ];
  11137. if ( color === undefined ) {
  11138. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11139. color = new Color();
  11140. }
  11141. array[ offset ++ ] = color.r;
  11142. array[ offset ++ ] = color.g;
  11143. array[ offset ++ ] = color.b;
  11144. }
  11145. return this;
  11146. },
  11147. copyVector2sArray: function ( vectors ) {
  11148. var array = this.array;
  11149. var offset = 0;
  11150. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11151. var vector = vectors[ i ];
  11152. if ( vector === undefined ) {
  11153. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11154. vector = new Vector2();
  11155. }
  11156. array[ offset ++ ] = vector.x;
  11157. array[ offset ++ ] = vector.y;
  11158. }
  11159. return this;
  11160. },
  11161. copyVector3sArray: function ( vectors ) {
  11162. var array = this.array;
  11163. var offset = 0;
  11164. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11165. var vector = vectors[ i ];
  11166. if ( vector === undefined ) {
  11167. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11168. vector = new Vector3();
  11169. }
  11170. array[ offset ++ ] = vector.x;
  11171. array[ offset ++ ] = vector.y;
  11172. array[ offset ++ ] = vector.z;
  11173. }
  11174. return this;
  11175. },
  11176. copyVector4sArray: function ( vectors ) {
  11177. var array = this.array;
  11178. var offset = 0;
  11179. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11180. var vector = vectors[ i ];
  11181. if ( vector === undefined ) {
  11182. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11183. vector = new Vector4();
  11184. }
  11185. array[ offset ++ ] = vector.x;
  11186. array[ offset ++ ] = vector.y;
  11187. array[ offset ++ ] = vector.z;
  11188. array[ offset ++ ] = vector.w;
  11189. }
  11190. return this;
  11191. },
  11192. applyMatrix3: function ( m ) {
  11193. if ( this.itemSize === 2 ) {
  11194. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11195. _vector2$1.fromBufferAttribute( this, i );
  11196. _vector2$1.applyMatrix3( m );
  11197. this.setXY( i, _vector2$1.x, _vector2$1.y );
  11198. }
  11199. } else if ( this.itemSize === 3 ) {
  11200. for ( var i$1 = 0, l$1 = this.count; i$1 < l$1; i$1 ++ ) {
  11201. _vector$3.fromBufferAttribute( this, i$1 );
  11202. _vector$3.applyMatrix3( m );
  11203. this.setXYZ( i$1, _vector$3.x, _vector$3.y, _vector$3.z );
  11204. }
  11205. }
  11206. return this;
  11207. },
  11208. applyMatrix4: function ( m ) {
  11209. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11210. _vector$3.x = this.getX( i );
  11211. _vector$3.y = this.getY( i );
  11212. _vector$3.z = this.getZ( i );
  11213. _vector$3.applyMatrix4( m );
  11214. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11215. }
  11216. return this;
  11217. },
  11218. applyNormalMatrix: function ( m ) {
  11219. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11220. _vector$3.x = this.getX( i );
  11221. _vector$3.y = this.getY( i );
  11222. _vector$3.z = this.getZ( i );
  11223. _vector$3.applyNormalMatrix( m );
  11224. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11225. }
  11226. return this;
  11227. },
  11228. transformDirection: function ( m ) {
  11229. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11230. _vector$3.x = this.getX( i );
  11231. _vector$3.y = this.getY( i );
  11232. _vector$3.z = this.getZ( i );
  11233. _vector$3.transformDirection( m );
  11234. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11235. }
  11236. return this;
  11237. },
  11238. set: function ( value, offset ) {
  11239. if ( offset === undefined ) { offset = 0; }
  11240. this.array.set( value, offset );
  11241. return this;
  11242. },
  11243. getX: function ( index ) {
  11244. return this.array[ index * this.itemSize ];
  11245. },
  11246. setX: function ( index, x ) {
  11247. this.array[ index * this.itemSize ] = x;
  11248. return this;
  11249. },
  11250. getY: function ( index ) {
  11251. return this.array[ index * this.itemSize + 1 ];
  11252. },
  11253. setY: function ( index, y ) {
  11254. this.array[ index * this.itemSize + 1 ] = y;
  11255. return this;
  11256. },
  11257. getZ: function ( index ) {
  11258. return this.array[ index * this.itemSize + 2 ];
  11259. },
  11260. setZ: function ( index, z ) {
  11261. this.array[ index * this.itemSize + 2 ] = z;
  11262. return this;
  11263. },
  11264. getW: function ( index ) {
  11265. return this.array[ index * this.itemSize + 3 ];
  11266. },
  11267. setW: function ( index, w ) {
  11268. this.array[ index * this.itemSize + 3 ] = w;
  11269. return this;
  11270. },
  11271. setXY: function ( index, x, y ) {
  11272. index *= this.itemSize;
  11273. this.array[ index + 0 ] = x;
  11274. this.array[ index + 1 ] = y;
  11275. return this;
  11276. },
  11277. setXYZ: function ( index, x, y, z ) {
  11278. index *= this.itemSize;
  11279. this.array[ index + 0 ] = x;
  11280. this.array[ index + 1 ] = y;
  11281. this.array[ index + 2 ] = z;
  11282. return this;
  11283. },
  11284. setXYZW: function ( index, x, y, z, w ) {
  11285. index *= this.itemSize;
  11286. this.array[ index + 0 ] = x;
  11287. this.array[ index + 1 ] = y;
  11288. this.array[ index + 2 ] = z;
  11289. this.array[ index + 3 ] = w;
  11290. return this;
  11291. },
  11292. onUpload: function ( callback ) {
  11293. this.onUploadCallback = callback;
  11294. return this;
  11295. },
  11296. clone: function () {
  11297. return new this.constructor( this.array, this.itemSize ).copy( this );
  11298. },
  11299. toJSON: function () {
  11300. return {
  11301. itemSize: this.itemSize,
  11302. type: this.array.constructor.name,
  11303. array: Array.prototype.slice.call( this.array ),
  11304. normalized: this.normalized
  11305. };
  11306. }
  11307. } );
  11308. //
  11309. function Int8BufferAttribute( array, itemSize, normalized ) {
  11310. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  11311. }
  11312. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11313. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11314. function Uint8BufferAttribute( array, itemSize, normalized ) {
  11315. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11316. }
  11317. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11318. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11319. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  11320. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  11321. }
  11322. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11323. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11324. function Int16BufferAttribute( array, itemSize, normalized ) {
  11325. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  11326. }
  11327. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11328. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11329. function Uint16BufferAttribute( array, itemSize, normalized ) {
  11330. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  11331. }
  11332. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11333. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11334. function Int32BufferAttribute( array, itemSize, normalized ) {
  11335. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  11336. }
  11337. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11338. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11339. function Uint32BufferAttribute( array, itemSize, normalized ) {
  11340. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  11341. }
  11342. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11343. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11344. function Float32BufferAttribute( array, itemSize, normalized ) {
  11345. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  11346. }
  11347. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11348. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11349. function Float64BufferAttribute( array, itemSize, normalized ) {
  11350. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  11351. }
  11352. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11353. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11354. function DirectGeometry() {
  11355. this.vertices = [];
  11356. this.normals = [];
  11357. this.colors = [];
  11358. this.uvs = [];
  11359. this.uvs2 = [];
  11360. this.groups = [];
  11361. this.morphTargets = {};
  11362. this.skinWeights = [];
  11363. this.skinIndices = [];
  11364. // this.lineDistances = [];
  11365. this.boundingBox = null;
  11366. this.boundingSphere = null;
  11367. // update flags
  11368. this.verticesNeedUpdate = false;
  11369. this.normalsNeedUpdate = false;
  11370. this.colorsNeedUpdate = false;
  11371. this.uvsNeedUpdate = false;
  11372. this.groupsNeedUpdate = false;
  11373. }
  11374. Object.assign( DirectGeometry.prototype, {
  11375. computeGroups: function ( geometry ) {
  11376. var groups = [];
  11377. var group, i;
  11378. var materialIndex = undefined;
  11379. var faces = geometry.faces;
  11380. for ( i = 0; i < faces.length; i ++ ) {
  11381. var face = faces[ i ];
  11382. // materials
  11383. if ( face.materialIndex !== materialIndex ) {
  11384. materialIndex = face.materialIndex;
  11385. if ( group !== undefined ) {
  11386. group.count = ( i * 3 ) - group.start;
  11387. groups.push( group );
  11388. }
  11389. group = {
  11390. start: i * 3,
  11391. materialIndex: materialIndex
  11392. };
  11393. }
  11394. }
  11395. if ( group !== undefined ) {
  11396. group.count = ( i * 3 ) - group.start;
  11397. groups.push( group );
  11398. }
  11399. this.groups = groups;
  11400. },
  11401. fromGeometry: function ( geometry ) {
  11402. var faces = geometry.faces;
  11403. var vertices = geometry.vertices;
  11404. var faceVertexUvs = geometry.faceVertexUvs;
  11405. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11406. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11407. // morphs
  11408. var morphTargets = geometry.morphTargets;
  11409. var morphTargetsLength = morphTargets.length;
  11410. var morphTargetsPosition;
  11411. if ( morphTargetsLength > 0 ) {
  11412. morphTargetsPosition = [];
  11413. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11414. morphTargetsPosition[ i ] = {
  11415. name: morphTargets[ i ].name,
  11416. data: []
  11417. };
  11418. }
  11419. this.morphTargets.position = morphTargetsPosition;
  11420. }
  11421. var morphNormals = geometry.morphNormals;
  11422. var morphNormalsLength = morphNormals.length;
  11423. var morphTargetsNormal;
  11424. if ( morphNormalsLength > 0 ) {
  11425. morphTargetsNormal = [];
  11426. for ( var i$1 = 0; i$1 < morphNormalsLength; i$1 ++ ) {
  11427. morphTargetsNormal[ i$1 ] = {
  11428. name: morphNormals[ i$1 ].name,
  11429. data: []
  11430. };
  11431. }
  11432. this.morphTargets.normal = morphTargetsNormal;
  11433. }
  11434. // skins
  11435. var skinIndices = geometry.skinIndices;
  11436. var skinWeights = geometry.skinWeights;
  11437. var hasSkinIndices = skinIndices.length === vertices.length;
  11438. var hasSkinWeights = skinWeights.length === vertices.length;
  11439. //
  11440. if ( vertices.length > 0 && faces.length === 0 ) {
  11441. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  11442. }
  11443. for ( var i$2 = 0; i$2 < faces.length; i$2 ++ ) {
  11444. var face = faces[ i$2 ];
  11445. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11446. var vertexNormals = face.vertexNormals;
  11447. if ( vertexNormals.length === 3 ) {
  11448. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11449. } else {
  11450. var normal = face.normal;
  11451. this.normals.push( normal, normal, normal );
  11452. }
  11453. var vertexColors = face.vertexColors;
  11454. if ( vertexColors.length === 3 ) {
  11455. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11456. } else {
  11457. var color = face.color;
  11458. this.colors.push( color, color, color );
  11459. }
  11460. if ( hasFaceVertexUv === true ) {
  11461. var vertexUvs = faceVertexUvs[ 0 ][ i$2 ];
  11462. if ( vertexUvs !== undefined ) {
  11463. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11464. } else {
  11465. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i$2 );
  11466. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11467. }
  11468. }
  11469. if ( hasFaceVertexUv2 === true ) {
  11470. var vertexUvs$1 = faceVertexUvs[ 1 ][ i$2 ];
  11471. if ( vertexUvs$1 !== undefined ) {
  11472. this.uvs2.push( vertexUvs$1[ 0 ], vertexUvs$1[ 1 ], vertexUvs$1[ 2 ] );
  11473. } else {
  11474. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i$2 );
  11475. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11476. }
  11477. }
  11478. // morphs
  11479. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11480. var morphTarget = morphTargets[ j ].vertices;
  11481. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11482. }
  11483. for ( var j$1 = 0; j$1 < morphNormalsLength; j$1 ++ ) {
  11484. var morphNormal = morphNormals[ j$1 ].vertexNormals[ i$2 ];
  11485. morphTargetsNormal[ j$1 ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  11486. }
  11487. // skins
  11488. if ( hasSkinIndices ) {
  11489. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11490. }
  11491. if ( hasSkinWeights ) {
  11492. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11493. }
  11494. }
  11495. this.computeGroups( geometry );
  11496. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11497. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11498. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11499. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11500. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11501. if ( geometry.boundingSphere !== null ) {
  11502. this.boundingSphere = geometry.boundingSphere.clone();
  11503. }
  11504. if ( geometry.boundingBox !== null ) {
  11505. this.boundingBox = geometry.boundingBox.clone();
  11506. }
  11507. return this;
  11508. }
  11509. } );
  11510. function arrayMax( array ) {
  11511. if ( array.length === 0 ) { return - Infinity; }
  11512. var max = array[ 0 ];
  11513. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11514. if ( array[ i ] > max ) { max = array[ i ]; }
  11515. }
  11516. return max;
  11517. }
  11518. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11519. var _m1$2 = new Matrix4();
  11520. var _obj = new Object3D();
  11521. var _offset = new Vector3();
  11522. var _box$2 = new Box3();
  11523. var _boxMorphTargets = new Box3();
  11524. var _vector$4 = new Vector3();
  11525. function BufferGeometry() {
  11526. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  11527. this.uuid = MathUtils.generateUUID();
  11528. this.name = '';
  11529. this.type = 'BufferGeometry';
  11530. this.index = null;
  11531. this.attributes = {};
  11532. this.morphAttributes = {};
  11533. this.morphTargetsRelative = false;
  11534. this.groups = [];
  11535. this.boundingBox = null;
  11536. this.boundingSphere = null;
  11537. this.drawRange = { start: 0, count: Infinity };
  11538. this.userData = {};
  11539. }
  11540. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11541. constructor: BufferGeometry,
  11542. isBufferGeometry: true,
  11543. getIndex: function () {
  11544. return this.index;
  11545. },
  11546. setIndex: function ( index ) {
  11547. if ( Array.isArray( index ) ) {
  11548. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11549. } else {
  11550. this.index = index;
  11551. }
  11552. },
  11553. getAttribute: function ( name ) {
  11554. return this.attributes[ name ];
  11555. },
  11556. setAttribute: function ( name, attribute ) {
  11557. this.attributes[ name ] = attribute;
  11558. return this;
  11559. },
  11560. deleteAttribute: function ( name ) {
  11561. delete this.attributes[ name ];
  11562. return this;
  11563. },
  11564. addGroup: function ( start, count, materialIndex ) {
  11565. this.groups.push( {
  11566. start: start,
  11567. count: count,
  11568. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11569. } );
  11570. },
  11571. clearGroups: function () {
  11572. this.groups = [];
  11573. },
  11574. setDrawRange: function ( start, count ) {
  11575. this.drawRange.start = start;
  11576. this.drawRange.count = count;
  11577. },
  11578. applyMatrix4: function ( matrix ) {
  11579. var position = this.attributes.position;
  11580. if ( position !== undefined ) {
  11581. position.applyMatrix4( matrix );
  11582. position.needsUpdate = true;
  11583. }
  11584. var normal = this.attributes.normal;
  11585. if ( normal !== undefined ) {
  11586. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11587. normal.applyNormalMatrix( normalMatrix );
  11588. normal.needsUpdate = true;
  11589. }
  11590. var tangent = this.attributes.tangent;
  11591. if ( tangent !== undefined ) {
  11592. tangent.transformDirection( matrix );
  11593. tangent.needsUpdate = true;
  11594. }
  11595. if ( this.boundingBox !== null ) {
  11596. this.computeBoundingBox();
  11597. }
  11598. if ( this.boundingSphere !== null ) {
  11599. this.computeBoundingSphere();
  11600. }
  11601. return this;
  11602. },
  11603. rotateX: function ( angle ) {
  11604. // rotate geometry around world x-axis
  11605. _m1$2.makeRotationX( angle );
  11606. this.applyMatrix4( _m1$2 );
  11607. return this;
  11608. },
  11609. rotateY: function ( angle ) {
  11610. // rotate geometry around world y-axis
  11611. _m1$2.makeRotationY( angle );
  11612. this.applyMatrix4( _m1$2 );
  11613. return this;
  11614. },
  11615. rotateZ: function ( angle ) {
  11616. // rotate geometry around world z-axis
  11617. _m1$2.makeRotationZ( angle );
  11618. this.applyMatrix4( _m1$2 );
  11619. return this;
  11620. },
  11621. translate: function ( x, y, z ) {
  11622. // translate geometry
  11623. _m1$2.makeTranslation( x, y, z );
  11624. this.applyMatrix4( _m1$2 );
  11625. return this;
  11626. },
  11627. scale: function ( x, y, z ) {
  11628. // scale geometry
  11629. _m1$2.makeScale( x, y, z );
  11630. this.applyMatrix4( _m1$2 );
  11631. return this;
  11632. },
  11633. lookAt: function ( vector ) {
  11634. _obj.lookAt( vector );
  11635. _obj.updateMatrix();
  11636. this.applyMatrix4( _obj.matrix );
  11637. return this;
  11638. },
  11639. center: function () {
  11640. this.computeBoundingBox();
  11641. this.boundingBox.getCenter( _offset ).negate();
  11642. this.translate( _offset.x, _offset.y, _offset.z );
  11643. return this;
  11644. },
  11645. setFromObject: function ( object ) {
  11646. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11647. var geometry = object.geometry;
  11648. if ( object.isPoints || object.isLine ) {
  11649. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11650. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11651. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11652. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11653. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11654. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11655. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11656. }
  11657. if ( geometry.boundingSphere !== null ) {
  11658. this.boundingSphere = geometry.boundingSphere.clone();
  11659. }
  11660. if ( geometry.boundingBox !== null ) {
  11661. this.boundingBox = geometry.boundingBox.clone();
  11662. }
  11663. } else if ( object.isMesh ) {
  11664. if ( geometry && geometry.isGeometry ) {
  11665. this.fromGeometry( geometry );
  11666. }
  11667. }
  11668. return this;
  11669. },
  11670. setFromPoints: function ( points ) {
  11671. var position = [];
  11672. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11673. var point = points[ i ];
  11674. position.push( point.x, point.y, point.z || 0 );
  11675. }
  11676. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11677. return this;
  11678. },
  11679. updateFromObject: function ( object ) {
  11680. var geometry = object.geometry;
  11681. if ( object.isMesh ) {
  11682. var direct = geometry.__directGeometry;
  11683. if ( geometry.elementsNeedUpdate === true ) {
  11684. direct = undefined;
  11685. geometry.elementsNeedUpdate = false;
  11686. }
  11687. if ( direct === undefined ) {
  11688. return this.fromGeometry( geometry );
  11689. }
  11690. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11691. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11692. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11693. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11694. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11695. geometry.verticesNeedUpdate = false;
  11696. geometry.normalsNeedUpdate = false;
  11697. geometry.colorsNeedUpdate = false;
  11698. geometry.uvsNeedUpdate = false;
  11699. geometry.groupsNeedUpdate = false;
  11700. geometry = direct;
  11701. }
  11702. if ( geometry.verticesNeedUpdate === true ) {
  11703. var attribute = this.attributes.position;
  11704. if ( attribute !== undefined ) {
  11705. attribute.copyVector3sArray( geometry.vertices );
  11706. attribute.needsUpdate = true;
  11707. }
  11708. geometry.verticesNeedUpdate = false;
  11709. }
  11710. if ( geometry.normalsNeedUpdate === true ) {
  11711. var attribute$1 = this.attributes.normal;
  11712. if ( attribute$1 !== undefined ) {
  11713. attribute$1.copyVector3sArray( geometry.normals );
  11714. attribute$1.needsUpdate = true;
  11715. }
  11716. geometry.normalsNeedUpdate = false;
  11717. }
  11718. if ( geometry.colorsNeedUpdate === true ) {
  11719. var attribute$2 = this.attributes.color;
  11720. if ( attribute$2 !== undefined ) {
  11721. attribute$2.copyColorsArray( geometry.colors );
  11722. attribute$2.needsUpdate = true;
  11723. }
  11724. geometry.colorsNeedUpdate = false;
  11725. }
  11726. if ( geometry.uvsNeedUpdate ) {
  11727. var attribute$3 = this.attributes.uv;
  11728. if ( attribute$3 !== undefined ) {
  11729. attribute$3.copyVector2sArray( geometry.uvs );
  11730. attribute$3.needsUpdate = true;
  11731. }
  11732. geometry.uvsNeedUpdate = false;
  11733. }
  11734. if ( geometry.lineDistancesNeedUpdate ) {
  11735. var attribute$4 = this.attributes.lineDistance;
  11736. if ( attribute$4 !== undefined ) {
  11737. attribute$4.copyArray( geometry.lineDistances );
  11738. attribute$4.needsUpdate = true;
  11739. }
  11740. geometry.lineDistancesNeedUpdate = false;
  11741. }
  11742. if ( geometry.groupsNeedUpdate ) {
  11743. geometry.computeGroups( object.geometry );
  11744. this.groups = geometry.groups;
  11745. geometry.groupsNeedUpdate = false;
  11746. }
  11747. return this;
  11748. },
  11749. fromGeometry: function ( geometry ) {
  11750. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11751. return this.fromDirectGeometry( geometry.__directGeometry );
  11752. },
  11753. fromDirectGeometry: function ( geometry ) {
  11754. var positions = new Float32Array( geometry.vertices.length * 3 );
  11755. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11756. if ( geometry.normals.length > 0 ) {
  11757. var normals = new Float32Array( geometry.normals.length * 3 );
  11758. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11759. }
  11760. if ( geometry.colors.length > 0 ) {
  11761. var colors = new Float32Array( geometry.colors.length * 3 );
  11762. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11763. }
  11764. if ( geometry.uvs.length > 0 ) {
  11765. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11766. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11767. }
  11768. if ( geometry.uvs2.length > 0 ) {
  11769. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11770. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11771. }
  11772. // groups
  11773. this.groups = geometry.groups;
  11774. // morphs
  11775. for ( var name in geometry.morphTargets ) {
  11776. var array = [];
  11777. var morphTargets = geometry.morphTargets[ name ];
  11778. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11779. var morphTarget = morphTargets[ i ];
  11780. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  11781. attribute.name = morphTarget.name;
  11782. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  11783. }
  11784. this.morphAttributes[ name ] = array;
  11785. }
  11786. // skinning
  11787. if ( geometry.skinIndices.length > 0 ) {
  11788. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11789. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11790. }
  11791. if ( geometry.skinWeights.length > 0 ) {
  11792. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11793. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11794. }
  11795. //
  11796. if ( geometry.boundingSphere !== null ) {
  11797. this.boundingSphere = geometry.boundingSphere.clone();
  11798. }
  11799. if ( geometry.boundingBox !== null ) {
  11800. this.boundingBox = geometry.boundingBox.clone();
  11801. }
  11802. return this;
  11803. },
  11804. computeBoundingBox: function () {
  11805. if ( this.boundingBox === null ) {
  11806. this.boundingBox = new Box3();
  11807. }
  11808. var position = this.attributes.position;
  11809. var morphAttributesPosition = this.morphAttributes.position;
  11810. if ( position !== undefined ) {
  11811. this.boundingBox.setFromBufferAttribute( position );
  11812. // process morph attributes if present
  11813. if ( morphAttributesPosition ) {
  11814. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11815. var morphAttribute = morphAttributesPosition[ i ];
  11816. _box$2.setFromBufferAttribute( morphAttribute );
  11817. if ( this.morphTargetsRelative ) {
  11818. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  11819. this.boundingBox.expandByPoint( _vector$4 );
  11820. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  11821. this.boundingBox.expandByPoint( _vector$4 );
  11822. } else {
  11823. this.boundingBox.expandByPoint( _box$2.min );
  11824. this.boundingBox.expandByPoint( _box$2.max );
  11825. }
  11826. }
  11827. }
  11828. } else {
  11829. this.boundingBox.makeEmpty();
  11830. }
  11831. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11832. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11833. }
  11834. },
  11835. computeBoundingSphere: function () {
  11836. if ( this.boundingSphere === null ) {
  11837. this.boundingSphere = new Sphere();
  11838. }
  11839. var position = this.attributes.position;
  11840. var morphAttributesPosition = this.morphAttributes.position;
  11841. if ( position ) {
  11842. // first, find the center of the bounding sphere
  11843. var center = this.boundingSphere.center;
  11844. _box$2.setFromBufferAttribute( position );
  11845. // process morph attributes if present
  11846. if ( morphAttributesPosition ) {
  11847. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11848. var morphAttribute = morphAttributesPosition[ i ];
  11849. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11850. if ( this.morphTargetsRelative ) {
  11851. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  11852. _box$2.expandByPoint( _vector$4 );
  11853. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  11854. _box$2.expandByPoint( _vector$4 );
  11855. } else {
  11856. _box$2.expandByPoint( _boxMorphTargets.min );
  11857. _box$2.expandByPoint( _boxMorphTargets.max );
  11858. }
  11859. }
  11860. }
  11861. _box$2.getCenter( center );
  11862. // second, try to find a boundingSphere with a radius smaller than the
  11863. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11864. var maxRadiusSq = 0;
  11865. for ( var i$1 = 0, il$1 = position.count; i$1 < il$1; i$1 ++ ) {
  11866. _vector$4.fromBufferAttribute( position, i$1 );
  11867. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11868. }
  11869. // process morph attributes if present
  11870. if ( morphAttributesPosition ) {
  11871. for ( var i$2 = 0, il$2 = morphAttributesPosition.length; i$2 < il$2; i$2 ++ ) {
  11872. var morphAttribute$1 = morphAttributesPosition[ i$2 ];
  11873. var morphTargetsRelative = this.morphTargetsRelative;
  11874. for ( var j = 0, jl = morphAttribute$1.count; j < jl; j ++ ) {
  11875. _vector$4.fromBufferAttribute( morphAttribute$1, j );
  11876. if ( morphTargetsRelative ) {
  11877. _offset.fromBufferAttribute( position, j );
  11878. _vector$4.add( _offset );
  11879. }
  11880. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11881. }
  11882. }
  11883. }
  11884. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11885. if ( isNaN( this.boundingSphere.radius ) ) {
  11886. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11887. }
  11888. }
  11889. },
  11890. computeFaceNormals: function () {
  11891. // backwards compatibility
  11892. },
  11893. computeVertexNormals: function () {
  11894. var index = this.index;
  11895. var positionAttribute = this.getAttribute( 'position' );
  11896. if ( positionAttribute !== undefined ) {
  11897. var normalAttribute = this.getAttribute( 'normal' );
  11898. if ( normalAttribute === undefined ) {
  11899. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  11900. this.setAttribute( 'normal', normalAttribute );
  11901. } else {
  11902. // reset existing normals to zero
  11903. for ( var i = 0, il = normalAttribute.count; i < il; i ++ ) {
  11904. normalAttribute.setXYZ( i, 0, 0, 0 );
  11905. }
  11906. }
  11907. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11908. var nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  11909. var cb = new Vector3(), ab = new Vector3();
  11910. // indexed elements
  11911. if ( index ) {
  11912. for ( var i$1 = 0, il$1 = index.count; i$1 < il$1; i$1 += 3 ) {
  11913. var vA = index.getX( i$1 + 0 );
  11914. var vB = index.getX( i$1 + 1 );
  11915. var vC = index.getX( i$1 + 2 );
  11916. pA.fromBufferAttribute( positionAttribute, vA );
  11917. pB.fromBufferAttribute( positionAttribute, vB );
  11918. pC.fromBufferAttribute( positionAttribute, vC );
  11919. cb.subVectors( pC, pB );
  11920. ab.subVectors( pA, pB );
  11921. cb.cross( ab );
  11922. nA.fromBufferAttribute( normalAttribute, vA );
  11923. nB.fromBufferAttribute( normalAttribute, vB );
  11924. nC.fromBufferAttribute( normalAttribute, vC );
  11925. nA.add( cb );
  11926. nB.add( cb );
  11927. nC.add( cb );
  11928. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  11929. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  11930. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  11931. }
  11932. } else {
  11933. // non-indexed elements (unconnected triangle soup)
  11934. for ( var i$2 = 0, il$2 = positionAttribute.count; i$2 < il$2; i$2 += 3 ) {
  11935. pA.fromBufferAttribute( positionAttribute, i$2 + 0 );
  11936. pB.fromBufferAttribute( positionAttribute, i$2 + 1 );
  11937. pC.fromBufferAttribute( positionAttribute, i$2 + 2 );
  11938. cb.subVectors( pC, pB );
  11939. ab.subVectors( pA, pB );
  11940. cb.cross( ab );
  11941. normalAttribute.setXYZ( i$2 + 0, cb.x, cb.y, cb.z );
  11942. normalAttribute.setXYZ( i$2 + 1, cb.x, cb.y, cb.z );
  11943. normalAttribute.setXYZ( i$2 + 2, cb.x, cb.y, cb.z );
  11944. }
  11945. }
  11946. this.normalizeNormals();
  11947. normalAttribute.needsUpdate = true;
  11948. }
  11949. },
  11950. merge: function ( geometry, offset ) {
  11951. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11952. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11953. return;
  11954. }
  11955. if ( offset === undefined ) {
  11956. offset = 0;
  11957. console.warn(
  11958. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11959. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11960. );
  11961. }
  11962. var attributes = this.attributes;
  11963. for ( var key in attributes ) {
  11964. if ( geometry.attributes[ key ] === undefined ) { continue; }
  11965. var attribute1 = attributes[ key ];
  11966. var attributeArray1 = attribute1.array;
  11967. var attribute2 = geometry.attributes[ key ];
  11968. var attributeArray2 = attribute2.array;
  11969. var attributeOffset = attribute2.itemSize * offset;
  11970. var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  11971. for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  11972. attributeArray1[ j ] = attributeArray2[ i ];
  11973. }
  11974. }
  11975. return this;
  11976. },
  11977. normalizeNormals: function () {
  11978. var normals = this.attributes.normal;
  11979. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11980. _vector$4.fromBufferAttribute( normals, i );
  11981. _vector$4.normalize();
  11982. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  11983. }
  11984. },
  11985. toNonIndexed: function () {
  11986. function convertBufferAttribute( attribute, indices ) {
  11987. var array = attribute.array;
  11988. var itemSize = attribute.itemSize;
  11989. var normalized = attribute.normalized;
  11990. var array2 = new array.constructor( indices.length * itemSize );
  11991. var index = 0, index2 = 0;
  11992. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11993. index = indices[ i ] * itemSize;
  11994. for ( var j = 0; j < itemSize; j ++ ) {
  11995. array2[ index2 ++ ] = array[ index ++ ];
  11996. }
  11997. }
  11998. return new BufferAttribute( array2, itemSize, normalized );
  11999. }
  12000. //
  12001. if ( this.index === null ) {
  12002. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12003. return this;
  12004. }
  12005. var geometry2 = new BufferGeometry();
  12006. var indices = this.index.array;
  12007. var attributes = this.attributes;
  12008. // attributes
  12009. for ( var name in attributes ) {
  12010. var attribute = attributes[ name ];
  12011. var newAttribute = convertBufferAttribute( attribute, indices );
  12012. geometry2.setAttribute( name, newAttribute );
  12013. }
  12014. // morph attributes
  12015. var morphAttributes = this.morphAttributes;
  12016. for ( var name$1 in morphAttributes ) {
  12017. var morphArray = [];
  12018. var morphAttribute = morphAttributes[ name$1 ]; // morphAttribute: array of Float32BufferAttributes
  12019. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  12020. var attribute$1 = morphAttribute[ i ];
  12021. var newAttribute$1 = convertBufferAttribute( attribute$1, indices );
  12022. morphArray.push( newAttribute$1 );
  12023. }
  12024. geometry2.morphAttributes[ name$1 ] = morphArray;
  12025. }
  12026. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  12027. // groups
  12028. var groups = this.groups;
  12029. for ( var i$1 = 0, l = groups.length; i$1 < l; i$1 ++ ) {
  12030. var group = groups[ i$1 ];
  12031. geometry2.addGroup( group.start, group.count, group.materialIndex );
  12032. }
  12033. return geometry2;
  12034. },
  12035. toJSON: function () {
  12036. var data = {
  12037. metadata: {
  12038. version: 4.5,
  12039. type: 'BufferGeometry',
  12040. generator: 'BufferGeometry.toJSON'
  12041. }
  12042. };
  12043. // standard BufferGeometry serialization
  12044. data.uuid = this.uuid;
  12045. data.type = this.type;
  12046. if ( this.name !== '' ) { data.name = this.name; }
  12047. if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; }
  12048. if ( this.parameters !== undefined ) {
  12049. var parameters = this.parameters;
  12050. for ( var key in parameters ) {
  12051. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  12052. }
  12053. return data;
  12054. }
  12055. data.data = { attributes: {} };
  12056. var index = this.index;
  12057. if ( index !== null ) {
  12058. data.data.index = {
  12059. type: index.array.constructor.name,
  12060. array: Array.prototype.slice.call( index.array )
  12061. };
  12062. }
  12063. var attributes = this.attributes;
  12064. for ( var key$1 in attributes ) {
  12065. var attribute = attributes[ key$1 ];
  12066. var attributeData = attribute.toJSON( data.data );
  12067. if ( attribute.name !== '' ) { attributeData.name = attribute.name; }
  12068. data.data.attributes[ key$1 ] = attributeData;
  12069. }
  12070. var morphAttributes = {};
  12071. var hasMorphAttributes = false;
  12072. for ( var key$2 in this.morphAttributes ) {
  12073. var attributeArray = this.morphAttributes[ key$2 ];
  12074. var array = [];
  12075. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  12076. var attribute$1 = attributeArray[ i ];
  12077. var attributeData$1 = attribute$1.toJSON( data.data );
  12078. if ( attribute$1.name !== '' ) { attributeData$1.name = attribute$1.name; }
  12079. array.push( attributeData$1 );
  12080. }
  12081. if ( array.length > 0 ) {
  12082. morphAttributes[ key$2 ] = array;
  12083. hasMorphAttributes = true;
  12084. }
  12085. }
  12086. if ( hasMorphAttributes ) {
  12087. data.data.morphAttributes = morphAttributes;
  12088. data.data.morphTargetsRelative = this.morphTargetsRelative;
  12089. }
  12090. var groups = this.groups;
  12091. if ( groups.length > 0 ) {
  12092. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  12093. }
  12094. var boundingSphere = this.boundingSphere;
  12095. if ( boundingSphere !== null ) {
  12096. data.data.boundingSphere = {
  12097. center: boundingSphere.center.toArray(),
  12098. radius: boundingSphere.radius
  12099. };
  12100. }
  12101. return data;
  12102. },
  12103. clone: function () {
  12104. /*
  12105. // Handle primitives
  12106. const parameters = this.parameters;
  12107. if ( parameters !== undefined ) {
  12108. const values = [];
  12109. for ( const key in parameters ) {
  12110. values.push( parameters[ key ] );
  12111. }
  12112. const geometry = Object.create( this.constructor.prototype );
  12113. this.constructor.apply( geometry, values );
  12114. return geometry;
  12115. }
  12116. return new this.constructor().copy( this );
  12117. */
  12118. return new BufferGeometry().copy( this );
  12119. },
  12120. copy: function ( source ) {
  12121. // reset
  12122. this.index = null;
  12123. this.attributes = {};
  12124. this.morphAttributes = {};
  12125. this.groups = [];
  12126. this.boundingBox = null;
  12127. this.boundingSphere = null;
  12128. // used for storing cloned, shared data
  12129. var data = {};
  12130. // name
  12131. this.name = source.name;
  12132. // index
  12133. var index = source.index;
  12134. if ( index !== null ) {
  12135. this.setIndex( index.clone( data ) );
  12136. }
  12137. // attributes
  12138. var attributes = source.attributes;
  12139. for ( var name in attributes ) {
  12140. var attribute = attributes[ name ];
  12141. this.setAttribute( name, attribute.clone( data ) );
  12142. }
  12143. // morph attributes
  12144. var morphAttributes = source.morphAttributes;
  12145. for ( var name$1 in morphAttributes ) {
  12146. var array = [];
  12147. var morphAttribute = morphAttributes[ name$1 ]; // morphAttribute: array of Float32BufferAttributes
  12148. for ( var i = 0, l = morphAttribute.length; i < l; i ++ ) {
  12149. array.push( morphAttribute[ i ].clone( data ) );
  12150. }
  12151. this.morphAttributes[ name$1 ] = array;
  12152. }
  12153. this.morphTargetsRelative = source.morphTargetsRelative;
  12154. // groups
  12155. var groups = source.groups;
  12156. for ( var i$1 = 0, l$1 = groups.length; i$1 < l$1; i$1 ++ ) {
  12157. var group = groups[ i$1 ];
  12158. this.addGroup( group.start, group.count, group.materialIndex );
  12159. }
  12160. // bounding box
  12161. var boundingBox = source.boundingBox;
  12162. if ( boundingBox !== null ) {
  12163. this.boundingBox = boundingBox.clone();
  12164. }
  12165. // bounding sphere
  12166. var boundingSphere = source.boundingSphere;
  12167. if ( boundingSphere !== null ) {
  12168. this.boundingSphere = boundingSphere.clone();
  12169. }
  12170. // draw range
  12171. this.drawRange.start = source.drawRange.start;
  12172. this.drawRange.count = source.drawRange.count;
  12173. // user data
  12174. this.userData = source.userData;
  12175. return this;
  12176. },
  12177. dispose: function () {
  12178. this.dispatchEvent( { type: 'dispose' } );
  12179. }
  12180. } );
  12181. var _inverseMatrix = new Matrix4();
  12182. var _ray = new Ray();
  12183. var _sphere = new Sphere();
  12184. var _vA = new Vector3();
  12185. var _vB = new Vector3();
  12186. var _vC = new Vector3();
  12187. var _tempA = new Vector3();
  12188. var _tempB = new Vector3();
  12189. var _tempC = new Vector3();
  12190. var _morphA = new Vector3();
  12191. var _morphB = new Vector3();
  12192. var _morphC = new Vector3();
  12193. var _uvA = new Vector2();
  12194. var _uvB = new Vector2();
  12195. var _uvC = new Vector2();
  12196. var _intersectionPoint = new Vector3();
  12197. var _intersectionPointWorld = new Vector3();
  12198. function Mesh( geometry, material ) {
  12199. Object3D.call( this );
  12200. this.type = 'Mesh';
  12201. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12202. this.material = material !== undefined ? material : new MeshBasicMaterial();
  12203. this.updateMorphTargets();
  12204. }
  12205. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12206. constructor: Mesh,
  12207. isMesh: true,
  12208. copy: function ( source ) {
  12209. Object3D.prototype.copy.call( this, source );
  12210. if ( source.morphTargetInfluences !== undefined ) {
  12211. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12212. }
  12213. if ( source.morphTargetDictionary !== undefined ) {
  12214. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12215. }
  12216. this.material = source.material;
  12217. this.geometry = source.geometry;
  12218. return this;
  12219. },
  12220. updateMorphTargets: function () {
  12221. var geometry = this.geometry;
  12222. if ( geometry.isBufferGeometry ) {
  12223. var morphAttributes = geometry.morphAttributes;
  12224. var keys = Object.keys( morphAttributes );
  12225. if ( keys.length > 0 ) {
  12226. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12227. if ( morphAttribute !== undefined ) {
  12228. this.morphTargetInfluences = [];
  12229. this.morphTargetDictionary = {};
  12230. for ( var m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12231. var name = morphAttribute[ m ].name || String( m );
  12232. this.morphTargetInfluences.push( 0 );
  12233. this.morphTargetDictionary[ name ] = m;
  12234. }
  12235. }
  12236. }
  12237. } else {
  12238. var morphTargets = geometry.morphTargets;
  12239. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12240. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  12241. }
  12242. }
  12243. },
  12244. raycast: function ( raycaster, intersects ) {
  12245. var geometry = this.geometry;
  12246. var material = this.material;
  12247. var matrixWorld = this.matrixWorld;
  12248. if ( material === undefined ) { return; }
  12249. // Checking boundingSphere distance to ray
  12250. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  12251. _sphere.copy( geometry.boundingSphere );
  12252. _sphere.applyMatrix4( matrixWorld );
  12253. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; }
  12254. //
  12255. _inverseMatrix.getInverse( matrixWorld );
  12256. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  12257. // Check boundingBox before continuing
  12258. if ( geometry.boundingBox !== null ) {
  12259. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; }
  12260. }
  12261. var intersection;
  12262. if ( geometry.isBufferGeometry ) {
  12263. var index = geometry.index;
  12264. var position = geometry.attributes.position;
  12265. var morphPosition = geometry.morphAttributes.position;
  12266. var morphTargetsRelative = geometry.morphTargetsRelative;
  12267. var uv = geometry.attributes.uv;
  12268. var uv2 = geometry.attributes.uv2;
  12269. var groups = geometry.groups;
  12270. var drawRange = geometry.drawRange;
  12271. if ( index !== null ) {
  12272. // indexed buffer geometry
  12273. if ( Array.isArray( material ) ) {
  12274. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  12275. var group = groups[ i ];
  12276. var groupMaterial = material[ group.materialIndex ];
  12277. var start = Math.max( group.start, drawRange.start );
  12278. var end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12279. for ( var j = start, jl = end; j < jl; j += 3 ) {
  12280. var a = index.getX( j );
  12281. var b = index.getX( j + 1 );
  12282. var c = index.getX( j + 2 );
  12283. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  12284. if ( intersection ) {
  12285. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12286. intersection.face.materialIndex = group.materialIndex;
  12287. intersects.push( intersection );
  12288. }
  12289. }
  12290. }
  12291. } else {
  12292. var start$1 = Math.max( 0, drawRange.start );
  12293. var end$1 = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12294. for ( var i$1 = start$1, il$1 = end$1; i$1 < il$1; i$1 += 3 ) {
  12295. var a$1 = index.getX( i$1 );
  12296. var b$1 = index.getX( i$1 + 1 );
  12297. var c$1 = index.getX( i$1 + 2 );
  12298. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a$1, b$1, c$1 );
  12299. if ( intersection ) {
  12300. intersection.faceIndex = Math.floor( i$1 / 3 ); // triangle number in indexed buffer semantics
  12301. intersects.push( intersection );
  12302. }
  12303. }
  12304. }
  12305. } else if ( position !== undefined ) {
  12306. // non-indexed buffer geometry
  12307. if ( Array.isArray( material ) ) {
  12308. for ( var i$2 = 0, il$2 = groups.length; i$2 < il$2; i$2 ++ ) {
  12309. var group$1 = groups[ i$2 ];
  12310. var groupMaterial$1 = material[ group$1.materialIndex ];
  12311. var start$2 = Math.max( group$1.start, drawRange.start );
  12312. var end$2 = Math.min( ( group$1.start + group$1.count ), ( drawRange.start + drawRange.count ) );
  12313. for ( var j$1 = start$2, jl$1 = end$2; j$1 < jl$1; j$1 += 3 ) {
  12314. var a$2 = j$1;
  12315. var b$2 = j$1 + 1;
  12316. var c$2 = j$1 + 2;
  12317. intersection = checkBufferGeometryIntersection( this, groupMaterial$1, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a$2, b$2, c$2 );
  12318. if ( intersection ) {
  12319. intersection.faceIndex = Math.floor( j$1 / 3 ); // triangle number in non-indexed buffer semantics
  12320. intersection.face.materialIndex = group$1.materialIndex;
  12321. intersects.push( intersection );
  12322. }
  12323. }
  12324. }
  12325. } else {
  12326. var start$3 = Math.max( 0, drawRange.start );
  12327. var end$3 = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12328. for ( var i$3 = start$3, il$3 = end$3; i$3 < il$3; i$3 += 3 ) {
  12329. var a$3 = i$3;
  12330. var b$3 = i$3 + 1;
  12331. var c$3 = i$3 + 2;
  12332. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a$3, b$3, c$3 );
  12333. if ( intersection ) {
  12334. intersection.faceIndex = Math.floor( i$3 / 3 ); // triangle number in non-indexed buffer semantics
  12335. intersects.push( intersection );
  12336. }
  12337. }
  12338. }
  12339. }
  12340. } else if ( geometry.isGeometry ) {
  12341. var isMultiMaterial = Array.isArray( material );
  12342. var vertices = geometry.vertices;
  12343. var faces = geometry.faces;
  12344. var uvs;
  12345. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12346. if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; }
  12347. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12348. var face = faces[ f ];
  12349. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12350. if ( faceMaterial === undefined ) { continue; }
  12351. var fvA = vertices[ face.a ];
  12352. var fvB = vertices[ face.b ];
  12353. var fvC = vertices[ face.c ];
  12354. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  12355. if ( intersection ) {
  12356. if ( uvs && uvs[ f ] ) {
  12357. var uvs_f = uvs[ f ];
  12358. _uvA.copy( uvs_f[ 0 ] );
  12359. _uvB.copy( uvs_f[ 1 ] );
  12360. _uvC.copy( uvs_f[ 2 ] );
  12361. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
  12362. }
  12363. intersection.face = face;
  12364. intersection.faceIndex = f;
  12365. intersects.push( intersection );
  12366. }
  12367. }
  12368. }
  12369. }
  12370. } );
  12371. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12372. var intersect;
  12373. if ( material.side === BackSide ) {
  12374. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12375. } else {
  12376. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12377. }
  12378. if ( intersect === null ) { return null; }
  12379. _intersectionPointWorld.copy( point );
  12380. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12381. var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12382. if ( distance < raycaster.near || distance > raycaster.far ) { return null; }
  12383. return {
  12384. distance: distance,
  12385. point: _intersectionPointWorld.clone(),
  12386. object: object
  12387. };
  12388. }
  12389. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  12390. _vA.fromBufferAttribute( position, a );
  12391. _vB.fromBufferAttribute( position, b );
  12392. _vC.fromBufferAttribute( position, c );
  12393. var morphInfluences = object.morphTargetInfluences;
  12394. if ( material.morphTargets && morphPosition && morphInfluences ) {
  12395. _morphA.set( 0, 0, 0 );
  12396. _morphB.set( 0, 0, 0 );
  12397. _morphC.set( 0, 0, 0 );
  12398. for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
  12399. var influence = morphInfluences[ i ];
  12400. var morphAttribute = morphPosition[ i ];
  12401. if ( influence === 0 ) { continue; }
  12402. _tempA.fromBufferAttribute( morphAttribute, a );
  12403. _tempB.fromBufferAttribute( morphAttribute, b );
  12404. _tempC.fromBufferAttribute( morphAttribute, c );
  12405. if ( morphTargetsRelative ) {
  12406. _morphA.addScaledVector( _tempA, influence );
  12407. _morphB.addScaledVector( _tempB, influence );
  12408. _morphC.addScaledVector( _tempC, influence );
  12409. } else {
  12410. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  12411. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  12412. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  12413. }
  12414. }
  12415. _vA.add( _morphA );
  12416. _vB.add( _morphB );
  12417. _vC.add( _morphC );
  12418. }
  12419. if ( object.isSkinnedMesh ) {
  12420. object.boneTransform( a, _vA );
  12421. object.boneTransform( b, _vB );
  12422. object.boneTransform( c, _vC );
  12423. }
  12424. var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  12425. if ( intersection ) {
  12426. if ( uv ) {
  12427. _uvA.fromBufferAttribute( uv, a );
  12428. _uvB.fromBufferAttribute( uv, b );
  12429. _uvC.fromBufferAttribute( uv, c );
  12430. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12431. }
  12432. if ( uv2 ) {
  12433. _uvA.fromBufferAttribute( uv2, a );
  12434. _uvB.fromBufferAttribute( uv2, b );
  12435. _uvC.fromBufferAttribute( uv2, c );
  12436. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12437. }
  12438. var face = new Face3( a, b, c );
  12439. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  12440. intersection.face = face;
  12441. }
  12442. return intersection;
  12443. }
  12444. var _geometryId = 0; // Geometry uses even numbers as Id
  12445. var _m1$3 = new Matrix4();
  12446. var _obj$1 = new Object3D();
  12447. var _offset$1 = new Vector3();
  12448. function Geometry() {
  12449. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  12450. this.uuid = MathUtils.generateUUID();
  12451. this.name = '';
  12452. this.type = 'Geometry';
  12453. this.vertices = [];
  12454. this.colors = [];
  12455. this.faces = [];
  12456. this.faceVertexUvs = [[]];
  12457. this.morphTargets = [];
  12458. this.morphNormals = [];
  12459. this.skinWeights = [];
  12460. this.skinIndices = [];
  12461. this.lineDistances = [];
  12462. this.boundingBox = null;
  12463. this.boundingSphere = null;
  12464. // update flags
  12465. this.elementsNeedUpdate = false;
  12466. this.verticesNeedUpdate = false;
  12467. this.uvsNeedUpdate = false;
  12468. this.normalsNeedUpdate = false;
  12469. this.colorsNeedUpdate = false;
  12470. this.lineDistancesNeedUpdate = false;
  12471. this.groupsNeedUpdate = false;
  12472. }
  12473. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12474. constructor: Geometry,
  12475. isGeometry: true,
  12476. applyMatrix4: function ( matrix ) {
  12477. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12478. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  12479. var vertex = this.vertices[ i ];
  12480. vertex.applyMatrix4( matrix );
  12481. }
  12482. for ( var i$1 = 0, il$1 = this.faces.length; i$1 < il$1; i$1 ++ ) {
  12483. var face = this.faces[ i$1 ];
  12484. face.normal.applyMatrix3( normalMatrix ).normalize();
  12485. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  12486. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  12487. }
  12488. }
  12489. if ( this.boundingBox !== null ) {
  12490. this.computeBoundingBox();
  12491. }
  12492. if ( this.boundingSphere !== null ) {
  12493. this.computeBoundingSphere();
  12494. }
  12495. this.verticesNeedUpdate = true;
  12496. this.normalsNeedUpdate = true;
  12497. return this;
  12498. },
  12499. rotateX: function ( angle ) {
  12500. // rotate geometry around world x-axis
  12501. _m1$3.makeRotationX( angle );
  12502. this.applyMatrix4( _m1$3 );
  12503. return this;
  12504. },
  12505. rotateY: function ( angle ) {
  12506. // rotate geometry around world y-axis
  12507. _m1$3.makeRotationY( angle );
  12508. this.applyMatrix4( _m1$3 );
  12509. return this;
  12510. },
  12511. rotateZ: function ( angle ) {
  12512. // rotate geometry around world z-axis
  12513. _m1$3.makeRotationZ( angle );
  12514. this.applyMatrix4( _m1$3 );
  12515. return this;
  12516. },
  12517. translate: function ( x, y, z ) {
  12518. // translate geometry
  12519. _m1$3.makeTranslation( x, y, z );
  12520. this.applyMatrix4( _m1$3 );
  12521. return this;
  12522. },
  12523. scale: function ( x, y, z ) {
  12524. // scale geometry
  12525. _m1$3.makeScale( x, y, z );
  12526. this.applyMatrix4( _m1$3 );
  12527. return this;
  12528. },
  12529. lookAt: function ( vector ) {
  12530. _obj$1.lookAt( vector );
  12531. _obj$1.updateMatrix();
  12532. this.applyMatrix4( _obj$1.matrix );
  12533. return this;
  12534. },
  12535. fromBufferGeometry: function ( geometry ) {
  12536. var scope = this;
  12537. var index = geometry.index !== null ? geometry.index : undefined;
  12538. var attributes = geometry.attributes;
  12539. if ( attributes.position === undefined ) {
  12540. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  12541. return this;
  12542. }
  12543. var position = attributes.position;
  12544. var normal = attributes.normal;
  12545. var color = attributes.color;
  12546. var uv = attributes.uv;
  12547. var uv2 = attributes.uv2;
  12548. if ( uv2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; }
  12549. for ( var i = 0; i < position.count; i ++ ) {
  12550. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  12551. if ( color !== undefined ) {
  12552. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  12553. }
  12554. }
  12555. function addFace( a, b, c, materialIndex ) {
  12556. var vertexColors = ( color === undefined ) ? [] : [
  12557. scope.colors[ a ].clone(),
  12558. scope.colors[ b ].clone(),
  12559. scope.colors[ c ].clone()
  12560. ];
  12561. var vertexNormals = ( normal === undefined ) ? [] : [
  12562. new Vector3().fromBufferAttribute( normal, a ),
  12563. new Vector3().fromBufferAttribute( normal, b ),
  12564. new Vector3().fromBufferAttribute( normal, c )
  12565. ];
  12566. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  12567. scope.faces.push( face );
  12568. if ( uv !== undefined ) {
  12569. scope.faceVertexUvs[ 0 ].push( [
  12570. new Vector2().fromBufferAttribute( uv, a ),
  12571. new Vector2().fromBufferAttribute( uv, b ),
  12572. new Vector2().fromBufferAttribute( uv, c )
  12573. ] );
  12574. }
  12575. if ( uv2 !== undefined ) {
  12576. scope.faceVertexUvs[ 1 ].push( [
  12577. new Vector2().fromBufferAttribute( uv2, a ),
  12578. new Vector2().fromBufferAttribute( uv2, b ),
  12579. new Vector2().fromBufferAttribute( uv2, c )
  12580. ] );
  12581. }
  12582. }
  12583. var groups = geometry.groups;
  12584. if ( groups.length > 0 ) {
  12585. for ( var i$1 = 0; i$1 < groups.length; i$1 ++ ) {
  12586. var group = groups[ i$1 ];
  12587. var start = group.start;
  12588. var count = group.count;
  12589. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  12590. if ( index !== undefined ) {
  12591. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  12592. } else {
  12593. addFace( j, j + 1, j + 2, group.materialIndex );
  12594. }
  12595. }
  12596. }
  12597. } else {
  12598. if ( index !== undefined ) {
  12599. for ( var i$2 = 0; i$2 < index.count; i$2 += 3 ) {
  12600. addFace( index.getX( i$2 ), index.getX( i$2 + 1 ), index.getX( i$2 + 2 ) );
  12601. }
  12602. } else {
  12603. for ( var i$3 = 0; i$3 < position.count; i$3 += 3 ) {
  12604. addFace( i$3, i$3 + 1, i$3 + 2 );
  12605. }
  12606. }
  12607. }
  12608. this.computeFaceNormals();
  12609. if ( geometry.boundingBox !== null ) {
  12610. this.boundingBox = geometry.boundingBox.clone();
  12611. }
  12612. if ( geometry.boundingSphere !== null ) {
  12613. this.boundingSphere = geometry.boundingSphere.clone();
  12614. }
  12615. return this;
  12616. },
  12617. center: function () {
  12618. this.computeBoundingBox();
  12619. this.boundingBox.getCenter( _offset$1 ).negate();
  12620. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  12621. return this;
  12622. },
  12623. normalize: function () {
  12624. this.computeBoundingSphere();
  12625. var center = this.boundingSphere.center;
  12626. var radius = this.boundingSphere.radius;
  12627. var s = radius === 0 ? 1 : 1.0 / radius;
  12628. var matrix = new Matrix4();
  12629. matrix.set(
  12630. s, 0, 0, - s * center.x,
  12631. 0, s, 0, - s * center.y,
  12632. 0, 0, s, - s * center.z,
  12633. 0, 0, 0, 1
  12634. );
  12635. this.applyMatrix4( matrix );
  12636. return this;
  12637. },
  12638. computeFaceNormals: function () {
  12639. var cb = new Vector3(), ab = new Vector3();
  12640. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12641. var face = this.faces[ f ];
  12642. var vA = this.vertices[ face.a ];
  12643. var vB = this.vertices[ face.b ];
  12644. var vC = this.vertices[ face.c ];
  12645. cb.subVectors( vC, vB );
  12646. ab.subVectors( vA, vB );
  12647. cb.cross( ab );
  12648. cb.normalize();
  12649. face.normal.copy( cb );
  12650. }
  12651. },
  12652. computeVertexNormals: function ( areaWeighted ) {
  12653. if ( areaWeighted === undefined ) { areaWeighted = true; }
  12654. var vertices = new Array( this.vertices.length );
  12655. for ( var v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12656. vertices[ v ] = new Vector3();
  12657. }
  12658. if ( areaWeighted ) {
  12659. // vertex normals weighted by triangle areas
  12660. // http://www.iquilezles.org/www/articles/normals/normals.htm
  12661. var cb = new Vector3(), ab = new Vector3();
  12662. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12663. var face = this.faces[ f ];
  12664. var vA = this.vertices[ face.a ];
  12665. var vB = this.vertices[ face.b ];
  12666. var vC = this.vertices[ face.c ];
  12667. cb.subVectors( vC, vB );
  12668. ab.subVectors( vA, vB );
  12669. cb.cross( ab );
  12670. vertices[ face.a ].add( cb );
  12671. vertices[ face.b ].add( cb );
  12672. vertices[ face.c ].add( cb );
  12673. }
  12674. } else {
  12675. this.computeFaceNormals();
  12676. for ( var f$1 = 0, fl$1 = this.faces.length; f$1 < fl$1; f$1 ++ ) {
  12677. var face$1 = this.faces[ f$1 ];
  12678. vertices[ face$1.a ].add( face$1.normal );
  12679. vertices[ face$1.b ].add( face$1.normal );
  12680. vertices[ face$1.c ].add( face$1.normal );
  12681. }
  12682. }
  12683. for ( var v$1 = 0, vl$1 = this.vertices.length; v$1 < vl$1; v$1 ++ ) {
  12684. vertices[ v$1 ].normalize();
  12685. }
  12686. for ( var f$2 = 0, fl$2 = this.faces.length; f$2 < fl$2; f$2 ++ ) {
  12687. var face$2 = this.faces[ f$2 ];
  12688. var vertexNormals = face$2.vertexNormals;
  12689. if ( vertexNormals.length === 3 ) {
  12690. vertexNormals[ 0 ].copy( vertices[ face$2.a ] );
  12691. vertexNormals[ 1 ].copy( vertices[ face$2.b ] );
  12692. vertexNormals[ 2 ].copy( vertices[ face$2.c ] );
  12693. } else {
  12694. vertexNormals[ 0 ] = vertices[ face$2.a ].clone();
  12695. vertexNormals[ 1 ] = vertices[ face$2.b ].clone();
  12696. vertexNormals[ 2 ] = vertices[ face$2.c ].clone();
  12697. }
  12698. }
  12699. if ( this.faces.length > 0 ) {
  12700. this.normalsNeedUpdate = true;
  12701. }
  12702. },
  12703. computeFlatVertexNormals: function () {
  12704. this.computeFaceNormals();
  12705. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12706. var face = this.faces[ f ];
  12707. var vertexNormals = face.vertexNormals;
  12708. if ( vertexNormals.length === 3 ) {
  12709. vertexNormals[ 0 ].copy( face.normal );
  12710. vertexNormals[ 1 ].copy( face.normal );
  12711. vertexNormals[ 2 ].copy( face.normal );
  12712. } else {
  12713. vertexNormals[ 0 ] = face.normal.clone();
  12714. vertexNormals[ 1 ] = face.normal.clone();
  12715. vertexNormals[ 2 ] = face.normal.clone();
  12716. }
  12717. }
  12718. if ( this.faces.length > 0 ) {
  12719. this.normalsNeedUpdate = true;
  12720. }
  12721. },
  12722. computeMorphNormals: function () {
  12723. // save original normals
  12724. // - create temp variables on first access
  12725. // otherwise just copy (for faster repeated calls)
  12726. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12727. var face = this.faces[ f ];
  12728. if ( ! face.__originalFaceNormal ) {
  12729. face.__originalFaceNormal = face.normal.clone();
  12730. } else {
  12731. face.__originalFaceNormal.copy( face.normal );
  12732. }
  12733. if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; }
  12734. for ( var i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  12735. if ( ! face.__originalVertexNormals[ i ] ) {
  12736. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  12737. } else {
  12738. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  12739. }
  12740. }
  12741. }
  12742. // use temp geometry to compute face and vertex normals for each morph
  12743. var tmpGeo = new Geometry();
  12744. tmpGeo.faces = this.faces;
  12745. for ( var i$1 = 0, il$1 = this.morphTargets.length; i$1 < il$1; i$1 ++ ) {
  12746. // create on first access
  12747. if ( ! this.morphNormals[ i$1 ] ) {
  12748. this.morphNormals[ i$1 ] = {};
  12749. this.morphNormals[ i$1 ].faceNormals = [];
  12750. this.morphNormals[ i$1 ].vertexNormals = [];
  12751. var dstNormalsFace = this.morphNormals[ i$1 ].faceNormals;
  12752. var dstNormalsVertex = this.morphNormals[ i$1 ].vertexNormals;
  12753. for ( var f$1 = 0, fl$1 = this.faces.length; f$1 < fl$1; f$1 ++ ) {
  12754. var faceNormal = new Vector3();
  12755. var vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  12756. dstNormalsFace.push( faceNormal );
  12757. dstNormalsVertex.push( vertexNormals );
  12758. }
  12759. }
  12760. var morphNormals = this.morphNormals[ i$1 ];
  12761. // set vertices to morph target
  12762. tmpGeo.vertices = this.morphTargets[ i$1 ].vertices;
  12763. // compute morph normals
  12764. tmpGeo.computeFaceNormals();
  12765. tmpGeo.computeVertexNormals();
  12766. // store morph normals
  12767. for ( var f$2 = 0, fl$2 = this.faces.length; f$2 < fl$2; f$2 ++ ) {
  12768. var face$1 = this.faces[ f$2 ];
  12769. var faceNormal$1 = morphNormals.faceNormals[ f$2 ];
  12770. var vertexNormals$1 = morphNormals.vertexNormals[ f$2 ];
  12771. faceNormal$1.copy( face$1.normal );
  12772. vertexNormals$1.a.copy( face$1.vertexNormals[ 0 ] );
  12773. vertexNormals$1.b.copy( face$1.vertexNormals[ 1 ] );
  12774. vertexNormals$1.c.copy( face$1.vertexNormals[ 2 ] );
  12775. }
  12776. }
  12777. // restore original normals
  12778. for ( var f$3 = 0, fl$3 = this.faces.length; f$3 < fl$3; f$3 ++ ) {
  12779. var face$2 = this.faces[ f$3 ];
  12780. face$2.normal = face$2.__originalFaceNormal;
  12781. face$2.vertexNormals = face$2.__originalVertexNormals;
  12782. }
  12783. },
  12784. computeBoundingBox: function () {
  12785. if ( this.boundingBox === null ) {
  12786. this.boundingBox = new Box3();
  12787. }
  12788. this.boundingBox.setFromPoints( this.vertices );
  12789. },
  12790. computeBoundingSphere: function () {
  12791. if ( this.boundingSphere === null ) {
  12792. this.boundingSphere = new Sphere();
  12793. }
  12794. this.boundingSphere.setFromPoints( this.vertices );
  12795. },
  12796. merge: function ( geometry, matrix, materialIndexOffset ) {
  12797. if ( ! ( geometry && geometry.isGeometry ) ) {
  12798. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  12799. return;
  12800. }
  12801. var normalMatrix,
  12802. vertexOffset = this.vertices.length,
  12803. vertices1 = this.vertices,
  12804. vertices2 = geometry.vertices,
  12805. faces1 = this.faces,
  12806. faces2 = geometry.faces,
  12807. colors1 = this.colors,
  12808. colors2 = geometry.colors;
  12809. if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; }
  12810. if ( matrix !== undefined ) {
  12811. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12812. }
  12813. // vertices
  12814. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  12815. var vertex = vertices2[ i ];
  12816. var vertexCopy = vertex.clone();
  12817. if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); }
  12818. vertices1.push( vertexCopy );
  12819. }
  12820. // colors
  12821. for ( var i$1 = 0, il$1 = colors2.length; i$1 < il$1; i$1 ++ ) {
  12822. colors1.push( colors2[ i$1 ].clone() );
  12823. }
  12824. // faces
  12825. for ( var i$2 = 0, il$2 = faces2.length; i$2 < il$2; i$2 ++ ) {
  12826. var face = faces2[ i$2 ], faceCopy = (void 0), normal = (void 0), color = (void 0),
  12827. faceVertexNormals = face.vertexNormals,
  12828. faceVertexColors = face.vertexColors;
  12829. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  12830. faceCopy.normal.copy( face.normal );
  12831. if ( normalMatrix !== undefined ) {
  12832. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  12833. }
  12834. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  12835. normal = faceVertexNormals[ j ].clone();
  12836. if ( normalMatrix !== undefined ) {
  12837. normal.applyMatrix3( normalMatrix ).normalize();
  12838. }
  12839. faceCopy.vertexNormals.push( normal );
  12840. }
  12841. faceCopy.color.copy( face.color );
  12842. for ( var j$1 = 0, jl$1 = faceVertexColors.length; j$1 < jl$1; j$1 ++ ) {
  12843. color = faceVertexColors[ j$1 ];
  12844. faceCopy.vertexColors.push( color.clone() );
  12845. }
  12846. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  12847. faces1.push( faceCopy );
  12848. }
  12849. // uvs
  12850. for ( var i$3 = 0, il$3 = geometry.faceVertexUvs.length; i$3 < il$3; i$3 ++ ) {
  12851. var faceVertexUvs2 = geometry.faceVertexUvs[ i$3 ];
  12852. if ( this.faceVertexUvs[ i$3 ] === undefined ) { this.faceVertexUvs[ i$3 ] = []; }
  12853. for ( var j$2 = 0, jl$2 = faceVertexUvs2.length; j$2 < jl$2; j$2 ++ ) {
  12854. var uvs2 = faceVertexUvs2[ j$2 ], uvsCopy = [];
  12855. for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) {
  12856. uvsCopy.push( uvs2[ k ].clone() );
  12857. }
  12858. this.faceVertexUvs[ i$3 ].push( uvsCopy );
  12859. }
  12860. }
  12861. },
  12862. mergeMesh: function ( mesh ) {
  12863. if ( ! ( mesh && mesh.isMesh ) ) {
  12864. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  12865. return;
  12866. }
  12867. if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); }
  12868. this.merge( mesh.geometry, mesh.matrix );
  12869. },
  12870. /*
  12871. * Checks for duplicate vertices with hashmap.
  12872. * Duplicated vertices are removed
  12873. * and faces' vertices are updated.
  12874. */
  12875. mergeVertices: function () {
  12876. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  12877. var unique = [], changes = [];
  12878. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  12879. var precision = Math.pow( 10, precisionPoints );
  12880. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  12881. var v = this.vertices[ i ];
  12882. var key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12883. if ( verticesMap[ key ] === undefined ) {
  12884. verticesMap[ key ] = i;
  12885. unique.push( this.vertices[ i ] );
  12886. changes[ i ] = unique.length - 1;
  12887. } else {
  12888. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12889. changes[ i ] = changes[ verticesMap[ key ] ];
  12890. }
  12891. }
  12892. // if faces are completely degenerate after merging vertices, we
  12893. // have to remove them from the geometry.
  12894. var faceIndicesToRemove = [];
  12895. for ( var i$1 = 0, il$1 = this.faces.length; i$1 < il$1; i$1 ++ ) {
  12896. var face = this.faces[ i$1 ];
  12897. face.a = changes[ face.a ];
  12898. face.b = changes[ face.b ];
  12899. face.c = changes[ face.c ];
  12900. var indices = [ face.a, face.b, face.c ];
  12901. // if any duplicate vertices are found in a Face3
  12902. // we have to remove the face as nothing can be saved
  12903. for ( var n = 0; n < 3; n ++ ) {
  12904. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12905. faceIndicesToRemove.push( i$1 );
  12906. break;
  12907. }
  12908. }
  12909. }
  12910. for ( var i$2 = faceIndicesToRemove.length - 1; i$2 >= 0; i$2 -- ) {
  12911. var idx = faceIndicesToRemove[ i$2 ];
  12912. this.faces.splice( idx, 1 );
  12913. for ( var j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12914. this.faceVertexUvs[ j ].splice( idx, 1 );
  12915. }
  12916. }
  12917. // Use unique set of vertices
  12918. var diff = this.vertices.length - unique.length;
  12919. this.vertices = unique;
  12920. return diff;
  12921. },
  12922. setFromPoints: function ( points ) {
  12923. this.vertices = [];
  12924. for ( var i = 0, l = points.length; i < l; i ++ ) {
  12925. var point = points[ i ];
  12926. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  12927. }
  12928. return this;
  12929. },
  12930. sortFacesByMaterialIndex: function () {
  12931. var faces = this.faces;
  12932. var length = faces.length;
  12933. // tag faces
  12934. for ( var i = 0; i < length; i ++ ) {
  12935. faces[ i ]._id = i;
  12936. }
  12937. // sort faces
  12938. function materialIndexSort( a, b ) {
  12939. return a.materialIndex - b.materialIndex;
  12940. }
  12941. faces.sort( materialIndexSort );
  12942. // sort uvs
  12943. var uvs1 = this.faceVertexUvs[ 0 ];
  12944. var uvs2 = this.faceVertexUvs[ 1 ];
  12945. var newUvs1, newUvs2;
  12946. if ( uvs1 && uvs1.length === length ) { newUvs1 = []; }
  12947. if ( uvs2 && uvs2.length === length ) { newUvs2 = []; }
  12948. for ( var i$1 = 0; i$1 < length; i$1 ++ ) {
  12949. var id = faces[ i$1 ]._id;
  12950. if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); }
  12951. if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); }
  12952. }
  12953. if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; }
  12954. if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; }
  12955. },
  12956. toJSON: function () {
  12957. var data = {
  12958. metadata: {
  12959. version: 4.5,
  12960. type: 'Geometry',
  12961. generator: 'Geometry.toJSON'
  12962. }
  12963. };
  12964. // standard Geometry serialization
  12965. data.uuid = this.uuid;
  12966. data.type = this.type;
  12967. if ( this.name !== '' ) { data.name = this.name; }
  12968. if ( this.parameters !== undefined ) {
  12969. var parameters = this.parameters;
  12970. for ( var key in parameters ) {
  12971. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  12972. }
  12973. return data;
  12974. }
  12975. var vertices = [];
  12976. for ( var i = 0; i < this.vertices.length; i ++ ) {
  12977. var vertex = this.vertices[ i ];
  12978. vertices.push( vertex.x, vertex.y, vertex.z );
  12979. }
  12980. var faces = [];
  12981. var normals = [];
  12982. var normalsHash = {};
  12983. var colors = [];
  12984. var colorsHash = {};
  12985. var uvs = [];
  12986. var uvsHash = {};
  12987. for ( var i$1 = 0; i$1 < this.faces.length; i$1 ++ ) {
  12988. var face = this.faces[ i$1 ];
  12989. var hasMaterial = true;
  12990. var hasFaceUv = false; // deprecated
  12991. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i$1 ] !== undefined;
  12992. var hasFaceNormal = face.normal.length() > 0;
  12993. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  12994. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  12995. var hasFaceVertexColor = face.vertexColors.length > 0;
  12996. var faceType = 0;
  12997. faceType = setBit( faceType, 0, 0 ); // isQuad
  12998. faceType = setBit( faceType, 1, hasMaterial );
  12999. faceType = setBit( faceType, 2, hasFaceUv );
  13000. faceType = setBit( faceType, 3, hasFaceVertexUv );
  13001. faceType = setBit( faceType, 4, hasFaceNormal );
  13002. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  13003. faceType = setBit( faceType, 6, hasFaceColor );
  13004. faceType = setBit( faceType, 7, hasFaceVertexColor );
  13005. faces.push( faceType );
  13006. faces.push( face.a, face.b, face.c );
  13007. faces.push( face.materialIndex );
  13008. if ( hasFaceVertexUv ) {
  13009. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i$1 ];
  13010. faces.push(
  13011. getUvIndex( faceVertexUvs[ 0 ] ),
  13012. getUvIndex( faceVertexUvs[ 1 ] ),
  13013. getUvIndex( faceVertexUvs[ 2 ] )
  13014. );
  13015. }
  13016. if ( hasFaceNormal ) {
  13017. faces.push( getNormalIndex( face.normal ) );
  13018. }
  13019. if ( hasFaceVertexNormal ) {
  13020. var vertexNormals = face.vertexNormals;
  13021. faces.push(
  13022. getNormalIndex( vertexNormals[ 0 ] ),
  13023. getNormalIndex( vertexNormals[ 1 ] ),
  13024. getNormalIndex( vertexNormals[ 2 ] )
  13025. );
  13026. }
  13027. if ( hasFaceColor ) {
  13028. faces.push( getColorIndex( face.color ) );
  13029. }
  13030. if ( hasFaceVertexColor ) {
  13031. var vertexColors = face.vertexColors;
  13032. faces.push(
  13033. getColorIndex( vertexColors[ 0 ] ),
  13034. getColorIndex( vertexColors[ 1 ] ),
  13035. getColorIndex( vertexColors[ 2 ] )
  13036. );
  13037. }
  13038. }
  13039. function setBit( value, position, enabled ) {
  13040. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  13041. }
  13042. function getNormalIndex( normal ) {
  13043. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  13044. if ( normalsHash[ hash ] !== undefined ) {
  13045. return normalsHash[ hash ];
  13046. }
  13047. normalsHash[ hash ] = normals.length / 3;
  13048. normals.push( normal.x, normal.y, normal.z );
  13049. return normalsHash[ hash ];
  13050. }
  13051. function getColorIndex( color ) {
  13052. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  13053. if ( colorsHash[ hash ] !== undefined ) {
  13054. return colorsHash[ hash ];
  13055. }
  13056. colorsHash[ hash ] = colors.length;
  13057. colors.push( color.getHex() );
  13058. return colorsHash[ hash ];
  13059. }
  13060. function getUvIndex( uv ) {
  13061. var hash = uv.x.toString() + uv.y.toString();
  13062. if ( uvsHash[ hash ] !== undefined ) {
  13063. return uvsHash[ hash ];
  13064. }
  13065. uvsHash[ hash ] = uvs.length / 2;
  13066. uvs.push( uv.x, uv.y );
  13067. return uvsHash[ hash ];
  13068. }
  13069. data.data = {};
  13070. data.data.vertices = vertices;
  13071. data.data.normals = normals;
  13072. if ( colors.length > 0 ) { data.data.colors = colors; }
  13073. if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility
  13074. data.data.faces = faces;
  13075. return data;
  13076. },
  13077. clone: function () {
  13078. /*
  13079. // Handle primitives
  13080. const parameters = this.parameters;
  13081. if ( parameters !== undefined ) {
  13082. const values = [];
  13083. for ( const key in parameters ) {
  13084. values.push( parameters[ key ] );
  13085. }
  13086. const geometry = Object.create( this.constructor.prototype );
  13087. this.constructor.apply( geometry, values );
  13088. return geometry;
  13089. }
  13090. return new this.constructor().copy( this );
  13091. */
  13092. return new Geometry().copy( this );
  13093. },
  13094. copy: function ( source ) {
  13095. // reset
  13096. this.vertices = [];
  13097. this.colors = [];
  13098. this.faces = [];
  13099. this.faceVertexUvs = [[]];
  13100. this.morphTargets = [];
  13101. this.morphNormals = [];
  13102. this.skinWeights = [];
  13103. this.skinIndices = [];
  13104. this.lineDistances = [];
  13105. this.boundingBox = null;
  13106. this.boundingSphere = null;
  13107. // name
  13108. this.name = source.name;
  13109. // vertices
  13110. var vertices = source.vertices;
  13111. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  13112. this.vertices.push( vertices[ i ].clone() );
  13113. }
  13114. // colors
  13115. var colors = source.colors;
  13116. for ( var i$1 = 0, il$1 = colors.length; i$1 < il$1; i$1 ++ ) {
  13117. this.colors.push( colors[ i$1 ].clone() );
  13118. }
  13119. // faces
  13120. var faces = source.faces;
  13121. for ( var i$2 = 0, il$2 = faces.length; i$2 < il$2; i$2 ++ ) {
  13122. this.faces.push( faces[ i$2 ].clone() );
  13123. }
  13124. // face vertex uvs
  13125. for ( var i$3 = 0, il$3 = source.faceVertexUvs.length; i$3 < il$3; i$3 ++ ) {
  13126. var faceVertexUvs = source.faceVertexUvs[ i$3 ];
  13127. if ( this.faceVertexUvs[ i$3 ] === undefined ) {
  13128. this.faceVertexUvs[ i$3 ] = [];
  13129. }
  13130. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  13131. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  13132. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  13133. var uv = uvs[ k ];
  13134. uvsCopy.push( uv.clone() );
  13135. }
  13136. this.faceVertexUvs[ i$3 ].push( uvsCopy );
  13137. }
  13138. }
  13139. // morph targets
  13140. var morphTargets = source.morphTargets;
  13141. for ( var i$4 = 0, il$4 = morphTargets.length; i$4 < il$4; i$4 ++ ) {
  13142. var morphTarget = {};
  13143. morphTarget.name = morphTargets[ i$4 ].name;
  13144. // vertices
  13145. if ( morphTargets[ i$4 ].vertices !== undefined ) {
  13146. morphTarget.vertices = [];
  13147. for ( var j$1 = 0, jl$1 = morphTargets[ i$4 ].vertices.length; j$1 < jl$1; j$1 ++ ) {
  13148. morphTarget.vertices.push( morphTargets[ i$4 ].vertices[ j$1 ].clone() );
  13149. }
  13150. }
  13151. // normals
  13152. if ( morphTargets[ i$4 ].normals !== undefined ) {
  13153. morphTarget.normals = [];
  13154. for ( var j$2 = 0, jl$2 = morphTargets[ i$4 ].normals.length; j$2 < jl$2; j$2 ++ ) {
  13155. morphTarget.normals.push( morphTargets[ i$4 ].normals[ j$2 ].clone() );
  13156. }
  13157. }
  13158. this.morphTargets.push( morphTarget );
  13159. }
  13160. // morph normals
  13161. var morphNormals = source.morphNormals;
  13162. for ( var i$5 = 0, il$5 = morphNormals.length; i$5 < il$5; i$5 ++ ) {
  13163. var morphNormal = {};
  13164. // vertex normals
  13165. if ( morphNormals[ i$5 ].vertexNormals !== undefined ) {
  13166. morphNormal.vertexNormals = [];
  13167. for ( var j$3 = 0, jl$3 = morphNormals[ i$5 ].vertexNormals.length; j$3 < jl$3; j$3 ++ ) {
  13168. var srcVertexNormal = morphNormals[ i$5 ].vertexNormals[ j$3 ];
  13169. var destVertexNormal = {};
  13170. destVertexNormal.a = srcVertexNormal.a.clone();
  13171. destVertexNormal.b = srcVertexNormal.b.clone();
  13172. destVertexNormal.c = srcVertexNormal.c.clone();
  13173. morphNormal.vertexNormals.push( destVertexNormal );
  13174. }
  13175. }
  13176. // face normals
  13177. if ( morphNormals[ i$5 ].faceNormals !== undefined ) {
  13178. morphNormal.faceNormals = [];
  13179. for ( var j$4 = 0, jl$4 = morphNormals[ i$5 ].faceNormals.length; j$4 < jl$4; j$4 ++ ) {
  13180. morphNormal.faceNormals.push( morphNormals[ i$5 ].faceNormals[ j$4 ].clone() );
  13181. }
  13182. }
  13183. this.morphNormals.push( morphNormal );
  13184. }
  13185. // skin weights
  13186. var skinWeights = source.skinWeights;
  13187. for ( var i$6 = 0, il$6 = skinWeights.length; i$6 < il$6; i$6 ++ ) {
  13188. this.skinWeights.push( skinWeights[ i$6 ].clone() );
  13189. }
  13190. // skin indices
  13191. var skinIndices = source.skinIndices;
  13192. for ( var i$7 = 0, il$7 = skinIndices.length; i$7 < il$7; i$7 ++ ) {
  13193. this.skinIndices.push( skinIndices[ i$7 ].clone() );
  13194. }
  13195. // line distances
  13196. var lineDistances = source.lineDistances;
  13197. for ( var i$8 = 0, il$8 = lineDistances.length; i$8 < il$8; i$8 ++ ) {
  13198. this.lineDistances.push( lineDistances[ i$8 ] );
  13199. }
  13200. // bounding box
  13201. var boundingBox = source.boundingBox;
  13202. if ( boundingBox !== null ) {
  13203. this.boundingBox = boundingBox.clone();
  13204. }
  13205. // bounding sphere
  13206. var boundingSphere = source.boundingSphere;
  13207. if ( boundingSphere !== null ) {
  13208. this.boundingSphere = boundingSphere.clone();
  13209. }
  13210. // update flags
  13211. this.elementsNeedUpdate = source.elementsNeedUpdate;
  13212. this.verticesNeedUpdate = source.verticesNeedUpdate;
  13213. this.uvsNeedUpdate = source.uvsNeedUpdate;
  13214. this.normalsNeedUpdate = source.normalsNeedUpdate;
  13215. this.colorsNeedUpdate = source.colorsNeedUpdate;
  13216. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  13217. this.groupsNeedUpdate = source.groupsNeedUpdate;
  13218. return this;
  13219. },
  13220. dispose: function () {
  13221. this.dispatchEvent( { type: 'dispose' } );
  13222. }
  13223. } );
  13224. // BoxGeometry
  13225. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13226. Geometry.call(this);
  13227. this.type = 'BoxGeometry';
  13228. this.parameters = {
  13229. width: width,
  13230. height: height,
  13231. depth: depth,
  13232. widthSegments: widthSegments,
  13233. heightSegments: heightSegments,
  13234. depthSegments: depthSegments
  13235. };
  13236. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13237. this.mergeVertices();
  13238. }
  13239. BoxGeometry.prototype = Object.create( Geometry.prototype );
  13240. BoxGeometry.prototype.constructor = BoxGeometry;
  13241. // BoxBufferGeometry
  13242. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13243. if ( width === void 0 ) width = 1;
  13244. if ( height === void 0 ) height = 1;
  13245. if ( depth === void 0 ) depth = 1;
  13246. if ( widthSegments === void 0 ) widthSegments = 1;
  13247. if ( heightSegments === void 0 ) heightSegments = 1;
  13248. if ( depthSegments === void 0 ) depthSegments = 1;
  13249. BufferGeometry.call(this);
  13250. this.type = 'BoxBufferGeometry';
  13251. this.parameters = {
  13252. width: width,
  13253. height: height,
  13254. depth: depth,
  13255. widthSegments: widthSegments,
  13256. heightSegments: heightSegments,
  13257. depthSegments: depthSegments
  13258. };
  13259. var scope = this;
  13260. // segments
  13261. widthSegments = Math.floor( widthSegments );
  13262. heightSegments = Math.floor( heightSegments );
  13263. depthSegments = Math.floor( depthSegments );
  13264. // buffers
  13265. var indices = [];
  13266. var vertices = [];
  13267. var normals = [];
  13268. var uvs = [];
  13269. // helper variables
  13270. var numberOfVertices = 0;
  13271. var groupStart = 0;
  13272. // build each side of the box geometry
  13273. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13274. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13275. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13276. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13277. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13278. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13279. // build geometry
  13280. this.setIndex( indices );
  13281. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13282. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13283. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13284. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13285. var segmentWidth = width / gridX;
  13286. var segmentHeight = height / gridY;
  13287. var widthHalf = width / 2;
  13288. var heightHalf = height / 2;
  13289. var depthHalf = depth / 2;
  13290. var gridX1 = gridX + 1;
  13291. var gridY1 = gridY + 1;
  13292. var vertexCounter = 0;
  13293. var groupCount = 0;
  13294. var vector = new Vector3();
  13295. // generate vertices, normals and uvs
  13296. for ( var iy = 0; iy < gridY1; iy ++ ) {
  13297. var y = iy * segmentHeight - heightHalf;
  13298. for ( var ix = 0; ix < gridX1; ix ++ ) {
  13299. var x = ix * segmentWidth - widthHalf;
  13300. // set values to correct vector component
  13301. vector[ u ] = x * udir;
  13302. vector[ v ] = y * vdir;
  13303. vector[ w ] = depthHalf;
  13304. // now apply vector to vertex buffer
  13305. vertices.push( vector.x, vector.y, vector.z );
  13306. // set values to correct vector component
  13307. vector[ u ] = 0;
  13308. vector[ v ] = 0;
  13309. vector[ w ] = depth > 0 ? 1 : - 1;
  13310. // now apply vector to normal buffer
  13311. normals.push( vector.x, vector.y, vector.z );
  13312. // uvs
  13313. uvs.push( ix / gridX );
  13314. uvs.push( 1 - ( iy / gridY ) );
  13315. // counters
  13316. vertexCounter += 1;
  13317. }
  13318. }
  13319. // indices
  13320. // 1. you need three indices to draw a single face
  13321. // 2. a single segment consists of two faces
  13322. // 3. so we need to generate six (2*3) indices per segment
  13323. for ( var iy$1 = 0; iy$1 < gridY; iy$1 ++ ) {
  13324. for ( var ix$1 = 0; ix$1 < gridX; ix$1 ++ ) {
  13325. var a = numberOfVertices + ix$1 + gridX1 * iy$1;
  13326. var b = numberOfVertices + ix$1 + gridX1 * ( iy$1 + 1 );
  13327. var c = numberOfVertices + ( ix$1 + 1 ) + gridX1 * ( iy$1 + 1 );
  13328. var d = numberOfVertices + ( ix$1 + 1 ) + gridX1 * iy$1;
  13329. // faces
  13330. indices.push( a, b, d );
  13331. indices.push( b, c, d );
  13332. // increase counter
  13333. groupCount += 6;
  13334. }
  13335. }
  13336. // add a group to the geometry. this will ensure multi material support
  13337. scope.addGroup( groupStart, groupCount, materialIndex );
  13338. // calculate new start value for groups
  13339. groupStart += groupCount;
  13340. // update total number of vertices
  13341. numberOfVertices += vertexCounter;
  13342. }
  13343. }
  13344. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13345. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13346. /**
  13347. * Uniform Utilities
  13348. */
  13349. function cloneUniforms( src ) {
  13350. var dst = {};
  13351. for ( var u in src ) {
  13352. dst[ u ] = {};
  13353. for ( var p in src[ u ] ) {
  13354. var property = src[ u ][ p ];
  13355. if ( property && ( property.isColor ||
  13356. property.isMatrix3 || property.isMatrix4 ||
  13357. property.isVector2 || property.isVector3 || property.isVector4 ||
  13358. property.isTexture ) ) {
  13359. dst[ u ][ p ] = property.clone();
  13360. } else if ( Array.isArray( property ) ) {
  13361. dst[ u ][ p ] = property.slice();
  13362. } else {
  13363. dst[ u ][ p ] = property;
  13364. }
  13365. }
  13366. }
  13367. return dst;
  13368. }
  13369. function mergeUniforms( uniforms ) {
  13370. var merged = {};
  13371. for ( var u = 0; u < uniforms.length; u ++ ) {
  13372. var tmp = cloneUniforms( uniforms[ u ] );
  13373. for ( var p in tmp ) {
  13374. merged[ p ] = tmp[ p ];
  13375. }
  13376. }
  13377. return merged;
  13378. }
  13379. // Legacy
  13380. var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  13381. var default_vertex = /* glsl */"\nvoid main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}\n";
  13382. var default_fragment = /* glsl */"\nvoid main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}\n";
  13383. /**
  13384. * parameters = {
  13385. * defines: { "label" : "value" },
  13386. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13387. *
  13388. * fragmentShader: <string>,
  13389. * vertexShader: <string>,
  13390. *
  13391. * wireframe: <boolean>,
  13392. * wireframeLinewidth: <float>,
  13393. *
  13394. * lights: <bool>,
  13395. *
  13396. * skinning: <bool>,
  13397. * morphTargets: <bool>,
  13398. * morphNormals: <bool>
  13399. * }
  13400. */
  13401. function ShaderMaterial( parameters ) {
  13402. Material.call( this );
  13403. this.type = 'ShaderMaterial';
  13404. this.defines = {};
  13405. this.uniforms = {};
  13406. this.vertexShader = default_vertex;
  13407. this.fragmentShader = default_fragment;
  13408. this.linewidth = 1;
  13409. this.wireframe = false;
  13410. this.wireframeLinewidth = 1;
  13411. this.fog = false; // set to use scene fog
  13412. this.lights = false; // set to use scene lights
  13413. this.clipping = false; // set to use user-defined clipping planes
  13414. this.skinning = false; // set to use skinning attribute streams
  13415. this.morphTargets = false; // set to use morph targets
  13416. this.morphNormals = false; // set to use morph normals
  13417. this.extensions = {
  13418. derivatives: false, // set to use derivatives
  13419. fragDepth: false, // set to use fragment depth values
  13420. drawBuffers: false, // set to use draw buffers
  13421. shaderTextureLOD: false // set to use shader texture LOD
  13422. };
  13423. // When rendered geometry doesn't include these attributes but the material does,
  13424. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13425. this.defaultAttributeValues = {
  13426. 'color': [ 1, 1, 1 ],
  13427. 'uv': [ 0, 0 ],
  13428. 'uv2': [ 0, 0 ]
  13429. };
  13430. this.index0AttributeName = undefined;
  13431. this.uniformsNeedUpdate = false;
  13432. if ( parameters !== undefined ) {
  13433. if ( parameters.attributes !== undefined ) {
  13434. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  13435. }
  13436. this.setValues( parameters );
  13437. }
  13438. }
  13439. ShaderMaterial.prototype = Object.create( Material.prototype );
  13440. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13441. ShaderMaterial.prototype.isShaderMaterial = true;
  13442. ShaderMaterial.prototype.copy = function ( source ) {
  13443. Material.prototype.copy.call( this, source );
  13444. this.fragmentShader = source.fragmentShader;
  13445. this.vertexShader = source.vertexShader;
  13446. this.uniforms = cloneUniforms( source.uniforms );
  13447. this.defines = Object.assign( {}, source.defines );
  13448. this.wireframe = source.wireframe;
  13449. this.wireframeLinewidth = source.wireframeLinewidth;
  13450. this.lights = source.lights;
  13451. this.clipping = source.clipping;
  13452. this.skinning = source.skinning;
  13453. this.morphTargets = source.morphTargets;
  13454. this.morphNormals = source.morphNormals;
  13455. this.extensions = Object.assign( {}, source.extensions );
  13456. return this;
  13457. };
  13458. ShaderMaterial.prototype.toJSON = function ( meta ) {
  13459. var data = Material.prototype.toJSON.call( this, meta );
  13460. data.uniforms = {};
  13461. for ( var name in this.uniforms ) {
  13462. var uniform = this.uniforms[ name ];
  13463. var value = uniform.value;
  13464. if ( value && value.isTexture ) {
  13465. data.uniforms[ name ] = {
  13466. type: 't',
  13467. value: value.toJSON( meta ).uuid
  13468. };
  13469. } else if ( value && value.isColor ) {
  13470. data.uniforms[ name ] = {
  13471. type: 'c',
  13472. value: value.getHex()
  13473. };
  13474. } else if ( value && value.isVector2 ) {
  13475. data.uniforms[ name ] = {
  13476. type: 'v2',
  13477. value: value.toArray()
  13478. };
  13479. } else if ( value && value.isVector3 ) {
  13480. data.uniforms[ name ] = {
  13481. type: 'v3',
  13482. value: value.toArray()
  13483. };
  13484. } else if ( value && value.isVector4 ) {
  13485. data.uniforms[ name ] = {
  13486. type: 'v4',
  13487. value: value.toArray()
  13488. };
  13489. } else if ( value && value.isMatrix3 ) {
  13490. data.uniforms[ name ] = {
  13491. type: 'm3',
  13492. value: value.toArray()
  13493. };
  13494. } else if ( value && value.isMatrix4 ) {
  13495. data.uniforms[ name ] = {
  13496. type: 'm4',
  13497. value: value.toArray()
  13498. };
  13499. } else {
  13500. data.uniforms[ name ] = {
  13501. value: value
  13502. };
  13503. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13504. }
  13505. }
  13506. if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; }
  13507. data.vertexShader = this.vertexShader;
  13508. data.fragmentShader = this.fragmentShader;
  13509. var extensions = {};
  13510. for ( var key in this.extensions ) {
  13511. if ( this.extensions[ key ] === true ) { extensions[ key ] = true; }
  13512. }
  13513. if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; }
  13514. return data;
  13515. };
  13516. function Camera() {
  13517. Object3D.call( this );
  13518. this.type = 'Camera';
  13519. this.matrixWorldInverse = new Matrix4();
  13520. this.projectionMatrix = new Matrix4();
  13521. this.projectionMatrixInverse = new Matrix4();
  13522. }
  13523. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13524. constructor: Camera,
  13525. isCamera: true,
  13526. copy: function ( source, recursive ) {
  13527. Object3D.prototype.copy.call( this, source, recursive );
  13528. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13529. this.projectionMatrix.copy( source.projectionMatrix );
  13530. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  13531. return this;
  13532. },
  13533. getWorldDirection: function ( target ) {
  13534. if ( target === undefined ) {
  13535. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  13536. target = new Vector3();
  13537. }
  13538. this.updateMatrixWorld( true );
  13539. var e = this.matrixWorld.elements;
  13540. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  13541. },
  13542. updateMatrixWorld: function ( force ) {
  13543. Object3D.prototype.updateMatrixWorld.call( this, force );
  13544. this.matrixWorldInverse.getInverse( this.matrixWorld );
  13545. },
  13546. updateWorldMatrix: function ( updateParents, updateChildren ) {
  13547. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  13548. this.matrixWorldInverse.getInverse( this.matrixWorld );
  13549. },
  13550. clone: function () {
  13551. return new this.constructor().copy( this );
  13552. }
  13553. } );
  13554. function PerspectiveCamera( fov, aspect, near, far ) {
  13555. Camera.call( this );
  13556. this.type = 'PerspectiveCamera';
  13557. this.fov = fov !== undefined ? fov : 50;
  13558. this.zoom = 1;
  13559. this.near = near !== undefined ? near : 0.1;
  13560. this.far = far !== undefined ? far : 2000;
  13561. this.focus = 10;
  13562. this.aspect = aspect !== undefined ? aspect : 1;
  13563. this.view = null;
  13564. this.filmGauge = 35; // width of the film (default in millimeters)
  13565. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13566. this.updateProjectionMatrix();
  13567. }
  13568. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13569. constructor: PerspectiveCamera,
  13570. isPerspectiveCamera: true,
  13571. copy: function ( source, recursive ) {
  13572. Camera.prototype.copy.call( this, source, recursive );
  13573. this.fov = source.fov;
  13574. this.zoom = source.zoom;
  13575. this.near = source.near;
  13576. this.far = source.far;
  13577. this.focus = source.focus;
  13578. this.aspect = source.aspect;
  13579. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13580. this.filmGauge = source.filmGauge;
  13581. this.filmOffset = source.filmOffset;
  13582. return this;
  13583. },
  13584. /**
  13585. * Sets the FOV by focal length in respect to the current .filmGauge.
  13586. *
  13587. * The default film gauge is 35, so that the focal length can be specified for
  13588. * a 35mm (full frame) camera.
  13589. *
  13590. * Values for focal length and film gauge must have the same unit.
  13591. */
  13592. setFocalLength: function ( focalLength ) {
  13593. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13594. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13595. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13596. this.updateProjectionMatrix();
  13597. },
  13598. /**
  13599. * Calculates the focal length from the current .fov and .filmGauge.
  13600. */
  13601. getFocalLength: function () {
  13602. var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  13603. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13604. },
  13605. getEffectiveFOV: function () {
  13606. return MathUtils.RAD2DEG * 2 * Math.atan(
  13607. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13608. },
  13609. getFilmWidth: function () {
  13610. // film not completely covered in portrait format (aspect < 1)
  13611. return this.filmGauge * Math.min( this.aspect, 1 );
  13612. },
  13613. getFilmHeight: function () {
  13614. // film not completely covered in landscape format (aspect > 1)
  13615. return this.filmGauge / Math.max( this.aspect, 1 );
  13616. },
  13617. /**
  13618. * Sets an offset in a larger frustum. This is useful for multi-window or
  13619. * multi-monitor/multi-machine setups.
  13620. *
  13621. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13622. * the monitors are in grid like this
  13623. *
  13624. * +---+---+---+
  13625. * | A | B | C |
  13626. * +---+---+---+
  13627. * | D | E | F |
  13628. * +---+---+---+
  13629. *
  13630. * then for each monitor you would call it like this
  13631. *
  13632. * const w = 1920;
  13633. * const h = 1080;
  13634. * const fullWidth = w * 3;
  13635. * const fullHeight = h * 2;
  13636. *
  13637. * --A--
  13638. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13639. * --B--
  13640. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13641. * --C--
  13642. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13643. * --D--
  13644. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13645. * --E--
  13646. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13647. * --F--
  13648. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13649. *
  13650. * Note there is no reason monitors have to be the same size or in a grid.
  13651. */
  13652. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  13653. this.aspect = fullWidth / fullHeight;
  13654. if ( this.view === null ) {
  13655. this.view = {
  13656. enabled: true,
  13657. fullWidth: 1,
  13658. fullHeight: 1,
  13659. offsetX: 0,
  13660. offsetY: 0,
  13661. width: 1,
  13662. height: 1
  13663. };
  13664. }
  13665. this.view.enabled = true;
  13666. this.view.fullWidth = fullWidth;
  13667. this.view.fullHeight = fullHeight;
  13668. this.view.offsetX = x;
  13669. this.view.offsetY = y;
  13670. this.view.width = width;
  13671. this.view.height = height;
  13672. this.updateProjectionMatrix();
  13673. },
  13674. clearViewOffset: function () {
  13675. if ( this.view !== null ) {
  13676. this.view.enabled = false;
  13677. }
  13678. this.updateProjectionMatrix();
  13679. },
  13680. updateProjectionMatrix: function () {
  13681. var near = this.near,
  13682. top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  13683. height = 2 * top,
  13684. width = this.aspect * height,
  13685. left = - 0.5 * width,
  13686. view = this.view;
  13687. if ( this.view !== null && this.view.enabled ) {
  13688. var fullWidth = view.fullWidth,
  13689. fullHeight = view.fullHeight;
  13690. left += view.offsetX * width / fullWidth;
  13691. top -= view.offsetY * height / fullHeight;
  13692. width *= view.width / fullWidth;
  13693. height *= view.height / fullHeight;
  13694. }
  13695. var skew = this.filmOffset;
  13696. if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); }
  13697. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  13698. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  13699. },
  13700. toJSON: function ( meta ) {
  13701. var data = Object3D.prototype.toJSON.call( this, meta );
  13702. data.object.fov = this.fov;
  13703. data.object.zoom = this.zoom;
  13704. data.object.near = this.near;
  13705. data.object.far = this.far;
  13706. data.object.focus = this.focus;
  13707. data.object.aspect = this.aspect;
  13708. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  13709. data.object.filmGauge = this.filmGauge;
  13710. data.object.filmOffset = this.filmOffset;
  13711. return data;
  13712. }
  13713. } );
  13714. var fov = 90, aspect = 1;
  13715. function CubeCamera( near, far, renderTarget ) {
  13716. Object3D.call( this );
  13717. this.type = 'CubeCamera';
  13718. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  13719. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  13720. return;
  13721. }
  13722. this.renderTarget = renderTarget;
  13723. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  13724. cameraPX.layers = this.layers;
  13725. cameraPX.up.set( 0, - 1, 0 );
  13726. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  13727. this.add( cameraPX );
  13728. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  13729. cameraNX.layers = this.layers;
  13730. cameraNX.up.set( 0, - 1, 0 );
  13731. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  13732. this.add( cameraNX );
  13733. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  13734. cameraPY.layers = this.layers;
  13735. cameraPY.up.set( 0, 0, 1 );
  13736. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  13737. this.add( cameraPY );
  13738. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  13739. cameraNY.layers = this.layers;
  13740. cameraNY.up.set( 0, 0, - 1 );
  13741. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  13742. this.add( cameraNY );
  13743. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  13744. cameraPZ.layers = this.layers;
  13745. cameraPZ.up.set( 0, - 1, 0 );
  13746. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  13747. this.add( cameraPZ );
  13748. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  13749. cameraNZ.layers = this.layers;
  13750. cameraNZ.up.set( 0, - 1, 0 );
  13751. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  13752. this.add( cameraNZ );
  13753. this.update = function ( renderer, scene ) {
  13754. if ( this.parent === null ) { this.updateMatrixWorld(); }
  13755. var currentXrEnabled = renderer.xr.enabled;
  13756. var currentRenderTarget = renderer.getRenderTarget();
  13757. renderer.xr.enabled = false;
  13758. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13759. renderTarget.texture.generateMipmaps = false;
  13760. renderer.setRenderTarget( renderTarget, 0 );
  13761. renderer.render( scene, cameraPX );
  13762. renderer.setRenderTarget( renderTarget, 1 );
  13763. renderer.render( scene, cameraNX );
  13764. renderer.setRenderTarget( renderTarget, 2 );
  13765. renderer.render( scene, cameraPY );
  13766. renderer.setRenderTarget( renderTarget, 3 );
  13767. renderer.render( scene, cameraNY );
  13768. renderer.setRenderTarget( renderTarget, 4 );
  13769. renderer.render( scene, cameraPZ );
  13770. renderTarget.texture.generateMipmaps = generateMipmaps;
  13771. renderer.setRenderTarget( renderTarget, 5 );
  13772. renderer.render( scene, cameraNZ );
  13773. renderer.setRenderTarget( currentRenderTarget );
  13774. renderer.xr.enabled = currentXrEnabled;
  13775. };
  13776. this.clear = function ( renderer, color, depth, stencil ) {
  13777. var currentRenderTarget = renderer.getRenderTarget();
  13778. for ( var i = 0; i < 6; i ++ ) {
  13779. renderer.setRenderTarget( renderTarget, i );
  13780. renderer.clear( color, depth, stencil );
  13781. }
  13782. renderer.setRenderTarget( currentRenderTarget );
  13783. };
  13784. }
  13785. CubeCamera.prototype = Object.create( Object3D.prototype );
  13786. CubeCamera.prototype.constructor = CubeCamera;
  13787. function WebGLCubeRenderTarget( size, options, dummy ) {
  13788. if ( Number.isInteger( options ) ) {
  13789. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  13790. options = dummy;
  13791. }
  13792. WebGLRenderTarget.call( this, size, size, options );
  13793. }
  13794. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  13795. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  13796. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  13797. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  13798. this.texture.type = texture.type;
  13799. this.texture.format = RGBAFormat; // see #18859
  13800. this.texture.encoding = texture.encoding;
  13801. this.texture.generateMipmaps = texture.generateMipmaps;
  13802. this.texture.minFilter = texture.minFilter;
  13803. this.texture.magFilter = texture.magFilter;
  13804. var scene = new Scene();
  13805. var shader = {
  13806. uniforms: {
  13807. tEquirect: { value: null },
  13808. },
  13809. vertexShader: /* glsl */"\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include <begin_vertex>\n\t\t\t\t#include <project_vertex>\n\n\t\t\t}\n\t\t",
  13810. fragmentShader: /* glsl */"\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"
  13811. };
  13812. var material = new ShaderMaterial( {
  13813. name: 'CubemapFromEquirect',
  13814. uniforms: cloneUniforms( shader.uniforms ),
  13815. vertexShader: shader.vertexShader,
  13816. fragmentShader: shader.fragmentShader,
  13817. side: BackSide,
  13818. blending: NoBlending
  13819. } );
  13820. material.uniforms.tEquirect.value = texture;
  13821. var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );
  13822. scene.add( mesh );
  13823. var camera = new CubeCamera( 1, 10, this );
  13824. camera.update( renderer, scene );
  13825. mesh.geometry.dispose();
  13826. mesh.material.dispose();
  13827. return this;
  13828. };
  13829. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13830. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13831. this.image = { data: data || null, width: width || 1, height: height || 1 };
  13832. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13833. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13834. this.generateMipmaps = false;
  13835. this.flipY = false;
  13836. this.unpackAlignment = 1;
  13837. this.needsUpdate = true;
  13838. }
  13839. DataTexture.prototype = Object.create( Texture.prototype );
  13840. DataTexture.prototype.constructor = DataTexture;
  13841. DataTexture.prototype.isDataTexture = true;
  13842. var _sphere$1 = new Sphere();
  13843. var _vector$5 = new Vector3();
  13844. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  13845. this.planes = [
  13846. ( p0 !== undefined ) ? p0 : new Plane(),
  13847. ( p1 !== undefined ) ? p1 : new Plane(),
  13848. ( p2 !== undefined ) ? p2 : new Plane(),
  13849. ( p3 !== undefined ) ? p3 : new Plane(),
  13850. ( p4 !== undefined ) ? p4 : new Plane(),
  13851. ( p5 !== undefined ) ? p5 : new Plane()
  13852. ];
  13853. }
  13854. Object.assign( Frustum.prototype, {
  13855. set: function ( p0, p1, p2, p3, p4, p5 ) {
  13856. var planes = this.planes;
  13857. planes[ 0 ].copy( p0 );
  13858. planes[ 1 ].copy( p1 );
  13859. planes[ 2 ].copy( p2 );
  13860. planes[ 3 ].copy( p3 );
  13861. planes[ 4 ].copy( p4 );
  13862. planes[ 5 ].copy( p5 );
  13863. return this;
  13864. },
  13865. clone: function () {
  13866. return new this.constructor().copy( this );
  13867. },
  13868. copy: function ( frustum ) {
  13869. var planes = this.planes;
  13870. for ( var i = 0; i < 6; i ++ ) {
  13871. planes[ i ].copy( frustum.planes[ i ] );
  13872. }
  13873. return this;
  13874. },
  13875. setFromProjectionMatrix: function ( m ) {
  13876. var planes = this.planes;
  13877. var me = m.elements;
  13878. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  13879. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  13880. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  13881. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  13882. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  13883. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  13884. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  13885. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  13886. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  13887. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  13888. return this;
  13889. },
  13890. intersectsObject: function ( object ) {
  13891. var geometry = object.geometry;
  13892. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  13893. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  13894. return this.intersectsSphere( _sphere$1 );
  13895. },
  13896. intersectsSprite: function ( sprite ) {
  13897. _sphere$1.center.set( 0, 0, 0 );
  13898. _sphere$1.radius = 0.7071067811865476;
  13899. _sphere$1.applyMatrix4( sprite.matrixWorld );
  13900. return this.intersectsSphere( _sphere$1 );
  13901. },
  13902. intersectsSphere: function ( sphere ) {
  13903. var planes = this.planes;
  13904. var center = sphere.center;
  13905. var negRadius = - sphere.radius;
  13906. for ( var i = 0; i < 6; i ++ ) {
  13907. var distance = planes[ i ].distanceToPoint( center );
  13908. if ( distance < negRadius ) {
  13909. return false;
  13910. }
  13911. }
  13912. return true;
  13913. },
  13914. intersectsBox: function ( box ) {
  13915. var planes = this.planes;
  13916. for ( var i = 0; i < 6; i ++ ) {
  13917. var plane = planes[ i ];
  13918. // corner at max distance
  13919. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  13920. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  13921. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  13922. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  13923. return false;
  13924. }
  13925. }
  13926. return true;
  13927. },
  13928. containsPoint: function ( point ) {
  13929. var planes = this.planes;
  13930. for ( var i = 0; i < 6; i ++ ) {
  13931. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  13932. return false;
  13933. }
  13934. }
  13935. return true;
  13936. }
  13937. } );
  13938. /**
  13939. * Uniforms library for shared webgl shaders
  13940. */
  13941. var UniformsLib = {
  13942. common: {
  13943. diffuse: { value: new Color( 0xeeeeee ) },
  13944. opacity: { value: 1.0 },
  13945. map: { value: null },
  13946. uvTransform: { value: new Matrix3() },
  13947. uv2Transform: { value: new Matrix3() },
  13948. alphaMap: { value: null },
  13949. },
  13950. specularmap: {
  13951. specularMap: { value: null },
  13952. },
  13953. envmap: {
  13954. envMap: { value: null },
  13955. flipEnvMap: { value: - 1 },
  13956. reflectivity: { value: 1.0 },
  13957. refractionRatio: { value: 0.98 },
  13958. maxMipLevel: { value: 0 }
  13959. },
  13960. aomap: {
  13961. aoMap: { value: null },
  13962. aoMapIntensity: { value: 1 }
  13963. },
  13964. lightmap: {
  13965. lightMap: { value: null },
  13966. lightMapIntensity: { value: 1 }
  13967. },
  13968. emissivemap: {
  13969. emissiveMap: { value: null }
  13970. },
  13971. bumpmap: {
  13972. bumpMap: { value: null },
  13973. bumpScale: { value: 1 }
  13974. },
  13975. normalmap: {
  13976. normalMap: { value: null },
  13977. normalScale: { value: new Vector2( 1, 1 ) }
  13978. },
  13979. displacementmap: {
  13980. displacementMap: { value: null },
  13981. displacementScale: { value: 1 },
  13982. displacementBias: { value: 0 }
  13983. },
  13984. roughnessmap: {
  13985. roughnessMap: { value: null }
  13986. },
  13987. metalnessmap: {
  13988. metalnessMap: { value: null }
  13989. },
  13990. gradientmap: {
  13991. gradientMap: { value: null }
  13992. },
  13993. fog: {
  13994. fogDensity: { value: 0.00025 },
  13995. fogNear: { value: 1 },
  13996. fogFar: { value: 2000 },
  13997. fogColor: { value: new Color( 0xffffff ) }
  13998. },
  13999. lights: {
  14000. ambientLightColor: { value: [] },
  14001. lightProbe: { value: [] },
  14002. directionalLights: { value: [], properties: {
  14003. direction: {},
  14004. color: {}
  14005. } },
  14006. directionalLightShadows: { value: [], properties: {
  14007. shadowBias: {},
  14008. shadowNormalBias: {},
  14009. shadowRadius: {},
  14010. shadowMapSize: {}
  14011. } },
  14012. directionalShadowMap: { value: [] },
  14013. directionalShadowMatrix: { value: [] },
  14014. spotLights: { value: [], properties: {
  14015. color: {},
  14016. position: {},
  14017. direction: {},
  14018. distance: {},
  14019. coneCos: {},
  14020. penumbraCos: {},
  14021. decay: {}
  14022. } },
  14023. spotLightShadows: { value: [], properties: {
  14024. shadowBias: {},
  14025. shadowNormalBias: {},
  14026. shadowRadius: {},
  14027. shadowMapSize: {}
  14028. } },
  14029. spotShadowMap: { value: [] },
  14030. spotShadowMatrix: { value: [] },
  14031. pointLights: { value: [], properties: {
  14032. color: {},
  14033. position: {},
  14034. decay: {},
  14035. distance: {}
  14036. } },
  14037. pointLightShadows: { value: [], properties: {
  14038. shadowBias: {},
  14039. shadowNormalBias: {},
  14040. shadowRadius: {},
  14041. shadowMapSize: {},
  14042. shadowCameraNear: {},
  14043. shadowCameraFar: {}
  14044. } },
  14045. pointShadowMap: { value: [] },
  14046. pointShadowMatrix: { value: [] },
  14047. hemisphereLights: { value: [], properties: {
  14048. direction: {},
  14049. skyColor: {},
  14050. groundColor: {}
  14051. } },
  14052. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14053. rectAreaLights: { value: [], properties: {
  14054. color: {},
  14055. position: {},
  14056. width: {},
  14057. height: {}
  14058. } }
  14059. },
  14060. points: {
  14061. diffuse: { value: new Color( 0xeeeeee ) },
  14062. opacity: { value: 1.0 },
  14063. size: { value: 1.0 },
  14064. scale: { value: 1.0 },
  14065. map: { value: null },
  14066. alphaMap: { value: null },
  14067. uvTransform: { value: new Matrix3() }
  14068. },
  14069. sprite: {
  14070. diffuse: { value: new Color( 0xeeeeee ) },
  14071. opacity: { value: 1.0 },
  14072. center: { value: new Vector2( 0.5, 0.5 ) },
  14073. rotation: { value: 0.0 },
  14074. map: { value: null },
  14075. alphaMap: { value: null },
  14076. uvTransform: { value: new Matrix3() }
  14077. }
  14078. };
  14079. function WebGLAnimation() {
  14080. var context = null;
  14081. var isAnimating = false;
  14082. var animationLoop = null;
  14083. var requestId = null;
  14084. function onAnimationFrame( time, frame ) {
  14085. animationLoop( time, frame );
  14086. requestId = context.requestAnimationFrame( onAnimationFrame );
  14087. }
  14088. return {
  14089. start: function () {
  14090. if ( isAnimating === true ) { return; }
  14091. if ( animationLoop === null ) { return; }
  14092. requestId = context.requestAnimationFrame( onAnimationFrame );
  14093. isAnimating = true;
  14094. },
  14095. stop: function () {
  14096. context.cancelAnimationFrame( requestId );
  14097. isAnimating = false;
  14098. },
  14099. setAnimationLoop: function ( callback ) {
  14100. animationLoop = callback;
  14101. },
  14102. setContext: function ( value ) {
  14103. context = value;
  14104. }
  14105. };
  14106. }
  14107. function WebGLAttributes( gl, capabilities ) {
  14108. var isWebGL2 = capabilities.isWebGL2;
  14109. var buffers = new WeakMap();
  14110. function createBuffer( attribute, bufferType ) {
  14111. var array = attribute.array;
  14112. var usage = attribute.usage;
  14113. var buffer = gl.createBuffer();
  14114. gl.bindBuffer( bufferType, buffer );
  14115. gl.bufferData( bufferType, array, usage );
  14116. attribute.onUploadCallback();
  14117. var type = 5126;
  14118. if ( array instanceof Float32Array ) {
  14119. type = 5126;
  14120. } else if ( array instanceof Float64Array ) {
  14121. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  14122. } else if ( array instanceof Uint16Array ) {
  14123. type = 5123;
  14124. } else if ( array instanceof Int16Array ) {
  14125. type = 5122;
  14126. } else if ( array instanceof Uint32Array ) {
  14127. type = 5125;
  14128. } else if ( array instanceof Int32Array ) {
  14129. type = 5124;
  14130. } else if ( array instanceof Int8Array ) {
  14131. type = 5120;
  14132. } else if ( array instanceof Uint8Array ) {
  14133. type = 5121;
  14134. }
  14135. return {
  14136. buffer: buffer,
  14137. type: type,
  14138. bytesPerElement: array.BYTES_PER_ELEMENT,
  14139. version: attribute.version
  14140. };
  14141. }
  14142. function updateBuffer( buffer, attribute, bufferType ) {
  14143. var array = attribute.array;
  14144. var updateRange = attribute.updateRange;
  14145. gl.bindBuffer( bufferType, buffer );
  14146. if ( updateRange.count === - 1 ) {
  14147. // Not using update ranges
  14148. gl.bufferSubData( bufferType, 0, array );
  14149. } else {
  14150. if ( isWebGL2 ) {
  14151. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  14152. array, updateRange.offset, updateRange.count );
  14153. } else {
  14154. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  14155. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  14156. }
  14157. updateRange.count = - 1; // reset range
  14158. }
  14159. }
  14160. //
  14161. function get( attribute ) {
  14162. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14163. return buffers.get( attribute );
  14164. }
  14165. function remove( attribute ) {
  14166. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14167. var data = buffers.get( attribute );
  14168. if ( data ) {
  14169. gl.deleteBuffer( data.buffer );
  14170. buffers.delete( attribute );
  14171. }
  14172. }
  14173. function update( attribute, bufferType ) {
  14174. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14175. var data = buffers.get( attribute );
  14176. if ( data === undefined ) {
  14177. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  14178. } else if ( data.version < attribute.version ) {
  14179. updateBuffer( data.buffer, attribute, bufferType );
  14180. data.version = attribute.version;
  14181. }
  14182. }
  14183. return {
  14184. get: get,
  14185. remove: remove,
  14186. update: update
  14187. };
  14188. }
  14189. // PlaneGeometry
  14190. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  14191. Geometry.call( this );
  14192. this.type = 'PlaneGeometry';
  14193. this.parameters = {
  14194. width: width,
  14195. height: height,
  14196. widthSegments: widthSegments,
  14197. heightSegments: heightSegments
  14198. };
  14199. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  14200. this.mergeVertices();
  14201. }
  14202. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  14203. PlaneGeometry.prototype.constructor = PlaneGeometry;
  14204. // PlaneBufferGeometry
  14205. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  14206. BufferGeometry.call( this );
  14207. this.type = 'PlaneBufferGeometry';
  14208. this.parameters = {
  14209. width: width,
  14210. height: height,
  14211. widthSegments: widthSegments,
  14212. heightSegments: heightSegments
  14213. };
  14214. width = width || 1;
  14215. height = height || 1;
  14216. var width_half = width / 2;
  14217. var height_half = height / 2;
  14218. var gridX = Math.floor( widthSegments ) || 1;
  14219. var gridY = Math.floor( heightSegments ) || 1;
  14220. var gridX1 = gridX + 1;
  14221. var gridY1 = gridY + 1;
  14222. var segment_width = width / gridX;
  14223. var segment_height = height / gridY;
  14224. // buffers
  14225. var indices = [];
  14226. var vertices = [];
  14227. var normals = [];
  14228. var uvs = [];
  14229. // generate vertices, normals and uvs
  14230. for ( var iy = 0; iy < gridY1; iy ++ ) {
  14231. var y = iy * segment_height - height_half;
  14232. for ( var ix = 0; ix < gridX1; ix ++ ) {
  14233. var x = ix * segment_width - width_half;
  14234. vertices.push( x, - y, 0 );
  14235. normals.push( 0, 0, 1 );
  14236. uvs.push( ix / gridX );
  14237. uvs.push( 1 - ( iy / gridY ) );
  14238. }
  14239. }
  14240. // indices
  14241. for ( var iy$1 = 0; iy$1 < gridY; iy$1 ++ ) {
  14242. for ( var ix$1 = 0; ix$1 < gridX; ix$1 ++ ) {
  14243. var a = ix$1 + gridX1 * iy$1;
  14244. var b = ix$1 + gridX1 * ( iy$1 + 1 );
  14245. var c = ( ix$1 + 1 ) + gridX1 * ( iy$1 + 1 );
  14246. var d = ( ix$1 + 1 ) + gridX1 * iy$1;
  14247. // faces
  14248. indices.push( a, b, d );
  14249. indices.push( b, c, d );
  14250. }
  14251. }
  14252. // build geometry
  14253. this.setIndex( indices );
  14254. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14255. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14256. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14257. }
  14258. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14259. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  14260. var alphamap_fragment = /* glsl */"\n#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  14261. var alphamap_pars_fragment = /* glsl */"\n#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n";
  14262. var alphatest_fragment = /* glsl */"\n#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  14263. var aomap_fragment = /* glsl */"\n#ifdef USE_AOMAP\n\n\t// reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n";
  14264. var aomap_pars_fragment = /* glsl */"\n#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif\n";
  14265. var begin_vertex = /* glsl */"\nvec3 transformed = vec3( position );\n";
  14266. var beginnormal_vertex = /* glsl */"\nvec3 objectNormal = vec3( normal );\n\n#ifdef USE_TANGENT\n\n\tvec3 objectTangent = vec3( tangent.xyz );\n\n#endif\n";
  14267. var bsdfs = /* glsl */"\n\n// Analytical approximation of the DFG LUT, one half of the\n// split-sum approximation used in indirect specular lighting.\n// via 'environmentBRDF' from \"Physically Based Shading on Mobile\"\n// https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t// page 32, equation 26: E[window1]\n\t// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\n\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t// but who must be converted to luminous irradiance for surface lighting calculation\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\n\tif( cutoffDistance > 0.0 ) {\n\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\n\t}\n\n\treturn distanceFalloff;\n\n#else\n\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n\t}\n\n\treturn 1.0;\n\n#endif\n\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\n\t// See F_Schlick\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\n\treturn Fr * fresnel + F0;\n\n}\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term (normalized) = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\n\t// also see #12151\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n\n}\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// Rect Area Light\n\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\n// code: https://github.com/selfshadow/ltc_code/\n\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\n\tfloat dotNV = saturate( dot( N, V ) );\n\n\t// texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\n\treturn uv;\n\n}\n\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\n\t// Real-Time Area Lighting: a Journey from Research to Production (p.102)\n\t// An approximation of the form factor of a horizon-clipped rectangle.\n\n\tfloat l = length( f );\n\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n\n}\n\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\n\tfloat x = dot( v1, v2 );\n\n\tfloat y = abs( x );\n\n\t// rational polynomial approximation to theta / sin( theta ) / 2PI\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\n\treturn cross( v1, v2 ) * theta_sintheta;\n\n}\n\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\n\t// bail if point is on back side of plane of light\n\t// assumes ccw winding order of light vertices\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\n\t// construct orthonormal basis around N\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\n\n\t// compute transform\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\n\t// transform rect\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\n\t// project rect onto sphere\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\n\t// calculate vector form factor\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\n\t// adjust for horizon clipping\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\n/*\n\t// alternate method of adjusting for horizon clipping (see referece)\n\t// refactoring required\n\tfloat len = length( vectorFormFactor );\n\tfloat z = vectorFormFactor.z / len;\n\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\n\t// tabulated horizon-clipped sphere, apparently...\n\tvec2 uv = vec2( z * 0.5 + 0.5, len );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\n\tfloat scale = texture2D( ltc_2, uv ).w;\n\n\tfloat result = len * scale;\n*/\n\n\treturn vec3( result );\n\n}\n\n// End Rect Area Light\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\n\treturn specularColor * brdf.x + brdf.y;\n\n} // validated\n\n// Fdez-Agüera's \"Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting\"\n// Approximates multiscattering in order to preserve energy.\n// http://www.jcgt.org/published/0008/01/03/\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619; // 1/21\n\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n\n}\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n\n#if defined( USE_SHEEN )\n\n// https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L94\nfloat D_Charlie(float roughness, float NoH) {\n\t// Estevez and Kulla 2017, \"Production Friendly Microfacet Sheen BRDF\"\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16\n\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\n\n// https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L136\nfloat V_Neubelt(float NoV, float NoL) {\n\t// Neubelt and Pettineo 2013, \"Crafting a Next-gen Material Pipeline for The Order: 1886\"\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\n\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n\n}\n\n#endif\n";
  14268. var bumpmap_pars_fragment = /* glsl */"\n#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen\n\t// http://api.unrealengine.com/attachments/Engine/Rendering/LightingAndShadows/BumpMappingWithoutTangentSpace/mm_sfgrad_bump.pdf\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n";
  14269. var clipping_planes_fragment = /* glsl */"\n#if NUM_CLIPPING_PLANES > 0\n\n\tvec4 plane;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\n\t\tbool clipped = true;\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t\tif ( clipped ) discard;\n\n\t#endif\n\n#endif\n";
  14270. var clipping_planes_pars_fragment = /* glsl */"\n#if NUM_CLIPPING_PLANES > 0\n\n\tvarying vec3 vClipPosition;\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n";
  14271. var clipping_planes_pars_vertex = /* glsl */"\n#if NUM_CLIPPING_PLANES > 0\n\n\tvarying vec3 vClipPosition;\n\n#endif\n";
  14272. var clipping_planes_vertex = /* glsl */"\n#if NUM_CLIPPING_PLANES > 0\n\n\tvClipPosition = - mvPosition.xyz;\n\n#endif\n";
  14273. var color_fragment = /* glsl */"\n#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif\n";
  14274. var color_pars_fragment = /* glsl */"\n#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n";
  14275. var color_pars_vertex = /* glsl */"\n#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n";
  14276. var color_vertex = /* glsl */"\n#ifdef USE_COLOR\n\n\tvColor.xyz = color.xyz;\n\n#endif\n";
  14277. var common = /* glsl */"\n#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n\n#ifndef saturate\n// <tonemapping_pars_fragment> may have defined saturate() already\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t// dir can be either a direction vector or a normal vector\n\t// upper-left 3x3 of matrix is assumed to be orthogonal\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n\nmat3 transposeMat3( const in mat3 m ) {\n\n\tmat3 tmp;\n\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\n\treturn tmp;\n\n}\n\n// https://en.wikipedia.org/wiki/Relative_luminance\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\n\treturn dot( weights, color.rgb );\n\n}\n\nbool isPerspectiveMatrix( mat4 m ) {\n\n\treturn m[ 2 ][ 3 ] == - 1.0;\n\n}\n\nvec2 equirectUv( in vec3 dir ) {\n\n\t// dir is assumed to be unit length\n\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\n\treturn vec2( u, v );\n\n}\n";
  14278. var cube_uv_reflection_fragment = /* glsl */"\n#ifdef ENVMAP_TYPE_CUBE_UV\n\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\n\n// These shader functions convert between the UV coordinates of a single face of\n// a cubemap, the 0-5 integer index of a cube face, and the direction vector for\n// sampling a textureCube (not generally normalized).\n\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\n\n// RH coordinate system; PMREM face-indexing convention\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x); // pos x\n } else if (face == 1.0) {\n uv = vec2(-direction.x, -direction.z) / abs(direction.y); // pos y\n } else if (face == 2.0) {\n uv = vec2(-direction.x, direction.y) / abs(direction.z); // pos z\n } else if (face == 3.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x); // neg x\n } else if (face == 4.0) {\n uv = vec2(-direction.x, direction.z) / abs(direction.y); // neg y\n } else {\n uv = vec2(direction.x, direction.y) / abs(direction.z); // neg z\n }\n return 0.5 * (uv + 1.0);\n}\n\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n\n// These defines must match with PMREMGenerator\n\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\n\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness);// 1.16 = 1.79^0.25\n }\n return mip;\n}\n\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif\n";
  14279. var defaultnormal_vertex = /* glsl */"\nvec3 transformedNormal = objectNormal;\n\n#ifdef USE_INSTANCING\n\n\t// this is in lieu of a per-instance normal-matrix\n\t// shear transforms in the instance matrix are not supported\n\n\tmat3 m = mat3( instanceMatrix );\n\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\n\ttransformedNormal = m * transformedNormal;\n\n#endif\n\ntransformedNormal = normalMatrix * transformedNormal;\n\n#ifdef FLIP_SIDED\n\n\ttransformedNormal = - transformedNormal;\n\n#endif\n\n#ifdef USE_TANGENT\n\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\n\t#ifdef FLIP_SIDED\n\n\t\ttransformedTangent = - transformedTangent;\n\n\t#endif\n\n#endif\n";
  14280. var displacementmap_pars_vertex = /* glsl */"\n#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n";
  14281. var displacementmap_vertex = /* glsl */"\n#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n\n#endif\n";
  14282. var emissivemap_fragment = /* glsl */"\n#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n";
  14283. var emissivemap_pars_fragment = /* glsl */"\n#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n";
  14284. var encodings_fragment = /* glsl */"\ngl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  14285. var encodings_pars_fragment = /* glsl */"\n// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\n\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\n\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\n\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\n\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\n\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\t// NOTE: The implementation with min causes the shader to not compile on\n\t// a common Alcatel A502DL in Chrome 78/Android 8.1. Some research suggests \n\t// that the chipset is Mediatek MT6739 w/ IMG PowerVR GE8100 GPU.\n\t// D = min( floor( D ) / 255.0, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}\n";
  14286. var envmap_fragment = /* glsl */"\n#ifdef USE_ENVMAP\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\n\t\t} else {\n\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\n\t\t}\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\treflectVec = normalize( reflectVec );\n\n\t\tvec2 sampleUV = equirectUv( reflectVec );\n\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\n\t#else\n\n\t\tvec4 envColor = vec4( 0.0 );\n\n\t#endif\n\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\n\t\tenvColor = envMapTexelToLinear( envColor );\n\n\t#endif\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n";
  14287. var envmap_common_pars_fragment = /* glsl */"\n#ifdef USE_ENVMAP\n\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif\n";
  14288. var envmap_pars_fragment = /* glsl */"\n#ifdef USE_ENVMAP\n\n\tuniform float reflectivity;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\t#define ENV_WORLDPOS\n\n\t#endif\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n";
  14289. var envmap_pars_vertex = /* glsl */"\n#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\n\t\t#define ENV_WORLDPOS\n\n\t#endif\n\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n";
  14290. var envmap_vertex = /* glsl */"\n#ifdef USE_ENVMAP\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex;\n\n\t\tif ( isOrthographic ) {\n\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\n\t\t} else {\n\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\t}\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n";
  14291. var fog_vertex = /* glsl */"\n#ifdef USE_FOG\n\n\tfogDepth = - mvPosition.z;\n\n#endif\n";
  14292. var fog_pars_vertex = /* glsl */"\n#ifdef USE_FOG\n\n\tvarying float fogDepth;\n\n#endif\n";
  14293. var fog_fragment = /* glsl */"\n#ifdef USE_FOG\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n";
  14294. var fog_pars_fragment = /* glsl */"\n#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\n\t#endif\n\n#endif\n";
  14295. var gradientmap_pars_fragment = /* glsl */"\n\n#ifdef USE_GRADIENTMAP\n\n\tuniform sampler2D gradientMap;\n\n#endif\n\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\n\t// dotNL will be from -1.0 to 1.0\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\n\t#ifdef USE_GRADIENTMAP\n\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\n\t#else\n\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\n\t#endif\n\n}\n";
  14296. var lightmap_fragment = /* glsl */"\n#ifdef USE_LIGHTMAP\n\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n";
  14297. var lightmap_pars_fragment = /* glsl */"\n#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif\n";
  14298. var lights_lambert_vertex = /* glsl */"\nvec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\n\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n\n#ifdef DOUBLE_SIDED\n\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n\n#endif\n\n#if NUM_POINT_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n/*\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n\t\t// TODO (abelnation): implement\n\n\t}\n\n#endif\n*/\n\n#if NUM_DIR_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n";
  14299. var lights_pars_begin = /* glsl */"\nuniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\n\n// get the irradiance (radiance convolved with cosine lobe) at the point 'normal' on the unit sphere\n// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\n\t// normal is assumed to have unit length\n\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\n\t// band 0\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\n\t// band 1\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\n\t// band 2\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\n\treturn result;\n\n}\n\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\n\treturn irradiance;\n\n}\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( angleCos > spotLight.coneCos ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\t}\n\n#endif\n\n\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\n\t// Pre-computed values of LinearTransformedCosine approximation of BRDF\n\t// BRDF approximation Texture is 64x64\n\tuniform sampler2D ltc_1; // RGBA Float\n\tuniform sampler2D ltc_2; // RGBA Float\n\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n";
  14300. var envmap_physical_pars_fragment = /* glsl */"\n#if defined( USE_ENVMAP )\n\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// Trowbridge-Reitz distribution to Mip level, following the logic of http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\n\t\t // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\n\t\t#else\n\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\n\t\t#endif\n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\n\t\t\tvec2 sampleUV = equirectUv( reflectVec );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n";
  14301. var lights_toon_fragment = /* glsl */"\nToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\n";
  14302. var lights_toon_pars_fragment = /* glsl */"\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct ToonMaterial {\n\n\tvec3 diffuseColor;\n\n};\n\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n\n#define Material_LightProbeLOD( material )\t(0)\n";
  14303. var lights_phong_fragment = /* glsl */"\nBlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  14304. var lights_phong_pars_fragment = /* glsl */"\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n";
  14305. var lights_physical_fragment = /* glsl */"\nPhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\n\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\n\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.\nmaterial.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n\n#ifdef REFLECTIVITY\n\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\n#else\n\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n\n#endif\n\n#ifdef CLEARCOAT\n\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\n\t#ifdef USE_CLEARCOATMAP\n\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\n\t#endif\n\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\n\t#endif\n\n\tmaterial.clearcoat = saturate( material.clearcoat ); // Burley clearcoat model\n\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n\n#endif\n\n#ifdef USE_SHEEN\n\n\tmaterial.sheenColor = sheen;\n\n#endif\n";
  14306. var lights_physical_pars_fragment = /* glsl */"\nstruct PhysicalMaterial {\n\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight; // counterclockwise; light shines in local neg z direction\n\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\n\t\t// LTC Fresnel Approximation by Stephen Hill\n\t\t// http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\n\t}\n\n#endif\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifdef CLEARCOAT\n\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tccIrradiance *= PI; // punctual light\n\n\t\t#endif\n\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\n\t#else\n\n\t\tfloat clearcoatDHR = 0.0;\n\n\t#endif\n\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\n\t#ifdef CLEARCOAT\n\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\n\t#else\n\n\t\tfloat clearcoatDHR = 0.0;\n\n\t#endif\n\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\n\t// Both indirect specular and indirect diffuse light accumulate here\n\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n// ref: https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n";
  14307. var lights_fragment_begin = /* glsl */"\n/**\n * This is a template that can be used to light a material, it uses pluggable\n * RenderEquations (RE)for specific lighting scenarios.\n *\n * Instructions for use:\n * - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n * - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n * - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n *\n * TODO:\n * - Add area light support.\n * - Add sphere light support.\n * - Add diffuse light probe (irradiance cubemap) support.\n */\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n#ifdef CLEARCOAT\n\n\tgeometry.clearcoatNormal = clearcoatNormal;\n\n#endif\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n\tRectAreaLight rectAreaLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 iblIrradiance = vec3( 0.0 );\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t#endif\n\n#endif\n\n#if defined( RE_IndirectSpecular )\n\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n\n#endif\n";
  14308. var lights_fragment_maps = /* glsl */"\n#if defined( RE_IndirectDiffuse )\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, maxMipLevel );\n\n\t#endif\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\tradiance += getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\n\t#ifdef CLEARCOAT\n\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\n\t#endif\n\n#endif\n";
  14309. var lights_fragment_end = /* glsl */"\n#if defined( RE_IndirectDiffuse )\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( RE_IndirectSpecular )\n\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n\n#endif\n";
  14310. var logdepthbuf_fragment = /* glsl */"\n#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\n\t// Doing a strict comparison with == 1.0 can cause noise artifacts\n\t// on some platforms. See issue #17623.\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n\n#endif\n";
  14311. var logdepthbuf_pars_fragment = /* glsl */"\n#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n\n#endif\n";
  14312. var logdepthbuf_pars_vertex = /* glsl */"\n#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\n\t#else\n\n\t\tuniform float logDepthBufFC;\n\n\t#endif\n\n#endif\n";
  14313. var logdepthbuf_vertex = /* glsl */"\n#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\n\t#else\n\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\n\t\t\tgl_Position.z *= gl_Position.w;\n\n\t\t}\n\n\t#endif\n\n#endif\n";
  14314. var map_fragment = /* glsl */"\n#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n";
  14315. var map_pars_fragment = /* glsl */"\n#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n";
  14316. var map_particle_fragment = /* glsl */"\n#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\n#endif\n\n#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n\n#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n\n#endif\n";
  14317. var map_particle_pars_fragment = /* glsl */"\n#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\n\tuniform mat3 uvTransform;\n\n#endif\n\n#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n\n#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n";
  14318. var metalnessmap_fragment = /* glsl */"\nfloat metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\n\t// reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\tmetalnessFactor *= texelMetalness.b;\n\n#endif\n";
  14319. var metalnessmap_pars_fragment = /* glsl */"\n#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif\n";
  14320. var morphnormal_vertex = /* glsl */"\n#ifdef USE_MORPHNORMALS\n\n\t// morphTargetBaseInfluence is set based on BufferGeometry.morphTargetsRelative value:\n\t// When morphTargetsRelative is false, this is set to 1 - sum(influences); this results in normal = sum((target - base) * influence)\n\t// When morphTargetsRelative is true, this is set to 1; as a result, all morph targets are simply added to the base after weighting\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\n#endif\n";
  14321. var morphtarget_pars_vertex = /* glsl */"\n#ifdef USE_MORPHTARGETS\n\n\tuniform float morphTargetBaseInfluence;\n\n\t#ifndef USE_MORPHNORMALS\n\n\t\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\t\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif\n";
  14322. var morphtarget_vertex = /* glsl */"\n#ifdef USE_MORPHTARGETS\n\n\t// morphTargetBaseInfluence is set based on BufferGeometry.morphTargetsRelative value:\n\t// When morphTargetsRelative is false, this is set to 1 - sum(influences); this results in position = sum((target - base) * influence)\n\t// When morphTargetsRelative is true, this is set to 1; as a result, all morph targets are simply added to the base after weighting\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n";
  14323. var normal_fragment_begin = /* glsl */"\n#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t#endif\n\n\t#ifdef USE_TANGENT\n\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\t#endif\n\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n\n// non perturbed normal for clearcoat among others\n\nvec3 geometryNormal = normal;\n\n";
  14324. var normal_fragment_maps = /* glsl */"\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n\t#ifdef FLIP_SIDED\n\n\t\tnormal = - normal;\n\n\t#endif\n\n\t#ifdef DOUBLE_SIDED\n\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t#endif\n\n\tnormal = normalize( normalMatrix * normal );\n\n#elif defined( TANGENTSPACE_NORMALMAP )\n\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\n\t#ifdef USE_TANGENT\n\n\t\tnormal = normalize( vTBN * mapN );\n\n\t#else\n\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\n\t#endif\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n";
  14325. var normalmap_pars_fragment = /* glsl */"\n#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n\tuniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tmat3 tsn = mat3( S, T, N );\n\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n";
  14326. var clearcoat_normal_fragment_begin = /* glsl */"\n#ifdef CLEARCOAT\n\n\tvec3 clearcoatNormal = geometryNormal;\n\n#endif\n";
  14327. var clearcoat_normal_fragment_maps = /* glsl */"\n#ifdef USE_CLEARCOAT_NORMALMAP\n\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\n\t#ifdef USE_TANGENT\n\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\n\t#else\n\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\n\t#endif\n\n#endif\n";
  14328. var clearcoat_pars_fragment = /* glsl */"\n\n#ifdef USE_CLEARCOATMAP\n\n\tuniform sampler2D clearcoatMap;\n\n#endif\n\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\n\tuniform sampler2D clearcoatRoughnessMap;\n\n#endif\n\n#ifdef USE_CLEARCOAT_NORMALMAP\n\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n\n#endif\n";
  14329. var packing = /* glsl */"\nvec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\n\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  14330. var premultiplied_alpha_fragment = /* glsl */"\n#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n";
  14331. var project_vertex = /* glsl */"\nvec4 mvPosition = vec4( transformed, 1.0 );\n\n#ifdef USE_INSTANCING\n\n\tmvPosition = instanceMatrix * mvPosition;\n\n#endif\n\nmvPosition = modelViewMatrix * mvPosition;\n\ngl_Position = projectionMatrix * mvPosition;\n";
  14332. var dithering_fragment = /* glsl */"\n#ifdef DITHERING\n\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n\n#endif\n";
  14333. var dithering_pars_fragment = /* glsl */"\n#ifdef DITHERING\n\n\t// based on https://www.shadertoy.com/view/MslGR8\n\tvec3 dithering( vec3 color ) {\n\t\t//Calculate grid position\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\n\t\t//Shift the individual colors differently, thus making it even harder to see the dithering pattern\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\n\t\t//modify shift acording to grid position.\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\n\t\t//shift the color by dither_shift\n\t\treturn color + dither_shift_RGB;\n\t}\n\n#endif\n";
  14334. var roughnessmap_fragment = /* glsl */"\nfloat roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\n\t// reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\troughnessFactor *= texelRoughness.g;\n\n#endif\n";
  14335. var roughnessmap_pars_fragment = /* glsl */"\n#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif\n";
  14336. var shadowmap_pars_fragment = /* glsl */"\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): create uniforms for area light shadows\n\n\t#endif\n\t*/\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\n\t}\n\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\n\t\tfloat occlusion = 1.0;\n\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\n\t\tfloat hard_shadow = step( compare , distribution.x ); // Hard Shadow\n\n\t\tif (hard_shadow != 1.0 ) {\n\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance ); // Chebeyshevs inequality\n\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); // 0.3 reduces light bleed\n\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\n\t\t}\n\t\treturn occlusion;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tfloat shadow = 1.0;\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn shadow;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the vector from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// dp = normalized distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); // need to clamp?\n\t\tdp += shadowBias;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n";
  14337. var shadowmap_pars_vertex = /* glsl */"\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): uniforms for area light shadows\n\n\t#endif\n\t*/\n\n#endif\n";
  14338. var shadowmap_vertex = /* glsl */"\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\t// Offsetting the position used for querying occlusion along the world normal can be used to reduce shadow acne.\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\n\t#endif\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): update vAreaShadowCoord with area light info\n\n\t#endif\n\t*/\n\n#endif\n";
  14339. var shadowmask_pars_fragment = /* glsl */"\nfloat getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\tDirectionalLightShadow directionalLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\tSpotLightShadow spotLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\tPointLightShadow pointLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): update shadow for Area light\n\n\t#endif\n\t*/\n\n\t#endif\n\n\treturn shadow;\n\n}\n";
  14340. var skinbase_vertex = /* glsl */"\n#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif\n";
  14341. var skinning_pars_vertex = /* glsl */"\n#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n";
  14342. var skinning_vertex = /* glsl */"\n#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n\n#endif\n";
  14343. var skinnormal_vertex = /* glsl */"\n#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n\t#ifdef USE_TANGENT\n\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\n\t#endif\n\n#endif\n";
  14344. var specularmap_fragment = /* glsl */"\nfloat specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif\n";
  14345. var specularmap_pars_fragment = /* glsl */"\n#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif\n";
  14346. var tonemapping_fragment = /* glsl */"\n#if defined( TONE_MAPPING )\n\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n";
  14347. var tonemapping_pars_fragment = /* glsl */"\n#ifndef saturate\n// <common> may have defined saturate() already\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform float toneMappingExposure;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n\treturn toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n\t// optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n\n// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs\nvec3 RRTAndODTFit( vec3 v ) {\n\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n\n}\n\n// this implementation of ACES is modified to accommodate a brighter viewing environment.\n// the scale factor of 1/0.6 is subjective. see discussion in #19621.\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\n\t// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\n\t// ODT_SAT => XYZ => D60_2_D65 => sRGB\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\n\tcolor *= toneMappingExposure / 0.6;\n\n\tcolor = ACESInputMat * color;\n\n\t// Apply RRT and ODT\n\tcolor = RRTAndODTFit( color );\n\n\tcolor = ACESOutputMat * color;\n\n\t// Clamp to [0, 1]\n\treturn saturate( color );\n\n}\n\nvec3 CustomToneMapping( vec3 color ) { return color; }\n";
  14348. var transmissionmap_fragment = /* glsl */"\n#ifdef USE_TRANSMISSIONMAP\n\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n\n#endif\n";
  14349. var transmissionmap_pars_fragment = /* glsl */"\n#ifdef USE_TRANSMISSIONMAP\n\n\tuniform sampler2D transmissionMap;\n\n#endif\n";
  14350. var uv_pars_fragment = /* glsl */"\n#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\n\tvarying vec2 vUv;\n\n#endif\n";
  14351. var uv_pars_vertex = /* glsl */"\n#ifdef USE_UV\n\n\t#ifdef UVS_VERTEX_ONLY\n\n\t\tvec2 vUv;\n\n\t#else\n\n\t\tvarying vec2 vUv;\n\n\t#endif\n\n\tuniform mat3 uvTransform;\n\n#endif\n";
  14352. var uv_vertex = /* glsl */"\n#ifdef USE_UV\n\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\n#endif\n";
  14353. var uv2_pars_fragment = /* glsl */"\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif\n";
  14354. var uv2_pars_vertex = /* glsl */"\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n\tuniform mat3 uv2Transform;\n\n#endif\n";
  14355. var uv2_vertex = /* glsl */"\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n\n#endif\n";
  14356. var worldpos_vertex = /* glsl */"\n#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\n\t#ifdef USE_INSTANCING\n\n\t\tworldPosition = instanceMatrix * worldPosition;\n\n\t#endif\n\n\tworldPosition = modelMatrix * worldPosition;\n\n#endif\n";
  14357. var background_frag = /* glsl */"\nuniform sampler2D t2D;\n\nvarying vec2 vUv;\n\nvoid main() {\n\n\tvec4 texColor = texture2D( t2D, vUv );\n\n\tgl_FragColor = mapTexelToLinear( texColor );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14358. var background_vert = /* glsl */"\nvarying vec2 vUv;\nuniform mat3 uvTransform;\n\nvoid main() {\n\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n\n}\n";
  14359. var cube_frag = /* glsl */"\n#include <envmap_common_pars_fragment>\nuniform float opacity;\n\nvarying vec3 vWorldDirection;\n\n#include <cube_uv_reflection_fragment>\n\nvoid main() {\n\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14360. var cube_vert = /* glsl */"\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\n\tgl_Position.z = gl_Position.w; // set z to camera.far\n\n}\n";
  14361. var depth_frag = /* glsl */"\n#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvarying vec2 vHighPrecisionZW;\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\t#include <logdepthbuf_fragment>\n\n\t// Higher precision equivalent of gl_FragCoord.z. This assumes depthRange has been left to its default values.\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\n\t#endif\n\n}\n";
  14362. var depth_vert = /* glsl */"\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n// This is used for computing an equivalent of gl_FragCoord.z that is as high precision as possible.\n// Some platforms compute gl_FragCoord at a lower precision which makes the manually computed value better for\n// depth-based postprocessing effects. Reproduced on iPad with A10 processor / iPadOS 13.3.1.\nvarying vec2 vHighPrecisionZW;\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_DISPLACEMENTMAP\n\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvHighPrecisionZW = gl_Position.zw;\n\n}\n";
  14363. var distanceRGBA_frag = /* glsl */"\n#define DISTANCE\n\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main () {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist ); // clamp to [ 0, 1 ]\n\n\tgl_FragColor = packDepthToRGBA( dist );\n\n}\n";
  14364. var distanceRGBA_vert = /* glsl */"\n#define DISTANCE\n\nvarying vec3 vWorldPosition;\n\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_DISPLACEMENTMAP\n\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvWorldPosition = worldPosition.xyz;\n\n}\n";
  14365. var equirect_frag = /* glsl */"\nuniform sampler2D tEquirect;\n\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvec3 direction = normalize( vWorldDirection );\n\n\tvec2 sampleUV = equirectUv( direction );\n\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\n\tgl_FragColor = mapTexelToLinear( texColor );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14366. var equirect_vert = /* glsl */"\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\n}\n";
  14367. var linedashed_frag = /* glsl */"\nuniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\n}\n";
  14368. var linedashed_vert = /* glsl */"\nuniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\tvLineDistance = scale * lineDistance;\n\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14369. var meshbasic_frag = /* glsl */"\nuniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n\t// accumulation (baked indirect lighting only)\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\n\t#else\n\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\n\t#endif\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14370. var meshbasic_vert = /* glsl */"\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_ENVMAP\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14371. var meshlambert_frag = /* glsl */"\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\n\t#else\n\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\n\t#endif\n\n\t#include <lightmap_fragment>\n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  14372. var meshlambert_vert = /* glsl */"\n#define LAMBERT\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  14373. var meshmatcap_frag = /* glsl */"\n#define MATCAP\n\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks\n\n\t#ifdef USE_MATCAP\n\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\n\t#else\n\n\t\tvec4 matcapColor = vec4( 1.0 );\n\n\t#endif\n\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14374. var meshmatcap_vert = /* glsl */"\n#define MATCAP\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\t\tvNormal = normalize( transformedNormal );\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n}\n";
  14375. var meshtoon_frag = /* glsl */"\n#define TOON\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14376. var meshtoon_vert = /* glsl */"\n#define TOON\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14377. var meshphong_frag = /* glsl */"\n#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14378. var meshphong_vert = /* glsl */"\n#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14379. var meshphysical_frag = /* glsl */"\n#define STANDARD\n\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\n\t// accumulation\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t// this is a stub for the transmission model\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14380. var meshphysical_vert = /* glsl */"\n#define STANDARD\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n\t#ifdef USE_TANGENT\n\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\n\t#endif\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14381. var normal_frag = /* glsl */"\n#define NORMAL\n\nuniform float opacity;\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvarying vec3 vViewPosition;\n\n#endif\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\n}\n";
  14382. var normal_vert = /* glsl */"\n#define NORMAL\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvarying vec3 vViewPosition;\n\n#endif\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n\t#ifdef USE_TANGENT\n\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\n\t#endif\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvViewPosition = - mvPosition.xyz;\n\n#endif\n\n}\n";
  14383. var points_frag = /* glsl */"\nuniform vec3 diffuse;\nuniform float opacity;\n\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\n}\n";
  14384. var points_vert = /* glsl */"\nuniform float size;\nuniform float scale;\n\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\n\tgl_PointSize = size;\n\n\t#ifdef USE_SIZEATTENUATION\n\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\n\t#endif\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14385. var shadow_frag = /* glsl */"\nuniform vec3 color;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n\nvoid main() {\n\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\n}\n";
  14386. var shadow_vert = /* glsl */"\n#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n\nvoid main() {\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14387. var sprite_frag = /* glsl */"\nuniform vec3 diffuse;\nuniform float opacity;\n\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\n}\n";
  14388. var sprite_vert = /* glsl */"\nuniform float rotation;\nuniform vec2 center;\n\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n\t#ifndef USE_SIZEATTENUATION\n\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\n\t#endif\n\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n\tmvPosition.xy += rotatedPosition;\n\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14389. var ShaderChunk = {
  14390. alphamap_fragment: alphamap_fragment,
  14391. alphamap_pars_fragment: alphamap_pars_fragment,
  14392. alphatest_fragment: alphatest_fragment,
  14393. aomap_fragment: aomap_fragment,
  14394. aomap_pars_fragment: aomap_pars_fragment,
  14395. begin_vertex: begin_vertex,
  14396. beginnormal_vertex: beginnormal_vertex,
  14397. bsdfs: bsdfs,
  14398. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14399. clipping_planes_fragment: clipping_planes_fragment,
  14400. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14401. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14402. clipping_planes_vertex: clipping_planes_vertex,
  14403. color_fragment: color_fragment,
  14404. color_pars_fragment: color_pars_fragment,
  14405. color_pars_vertex: color_pars_vertex,
  14406. color_vertex: color_vertex,
  14407. common: common,
  14408. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14409. defaultnormal_vertex: defaultnormal_vertex,
  14410. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14411. displacementmap_vertex: displacementmap_vertex,
  14412. emissivemap_fragment: emissivemap_fragment,
  14413. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14414. encodings_fragment: encodings_fragment,
  14415. encodings_pars_fragment: encodings_pars_fragment,
  14416. envmap_fragment: envmap_fragment,
  14417. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14418. envmap_pars_fragment: envmap_pars_fragment,
  14419. envmap_pars_vertex: envmap_pars_vertex,
  14420. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14421. envmap_vertex: envmap_vertex,
  14422. fog_vertex: fog_vertex,
  14423. fog_pars_vertex: fog_pars_vertex,
  14424. fog_fragment: fog_fragment,
  14425. fog_pars_fragment: fog_pars_fragment,
  14426. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14427. lightmap_fragment: lightmap_fragment,
  14428. lightmap_pars_fragment: lightmap_pars_fragment,
  14429. lights_lambert_vertex: lights_lambert_vertex,
  14430. lights_pars_begin: lights_pars_begin,
  14431. lights_toon_fragment: lights_toon_fragment,
  14432. lights_toon_pars_fragment: lights_toon_pars_fragment,
  14433. lights_phong_fragment: lights_phong_fragment,
  14434. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14435. lights_physical_fragment: lights_physical_fragment,
  14436. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14437. lights_fragment_begin: lights_fragment_begin,
  14438. lights_fragment_maps: lights_fragment_maps,
  14439. lights_fragment_end: lights_fragment_end,
  14440. logdepthbuf_fragment: logdepthbuf_fragment,
  14441. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14442. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14443. logdepthbuf_vertex: logdepthbuf_vertex,
  14444. map_fragment: map_fragment,
  14445. map_pars_fragment: map_pars_fragment,
  14446. map_particle_fragment: map_particle_fragment,
  14447. map_particle_pars_fragment: map_particle_pars_fragment,
  14448. metalnessmap_fragment: metalnessmap_fragment,
  14449. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14450. morphnormal_vertex: morphnormal_vertex,
  14451. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14452. morphtarget_vertex: morphtarget_vertex,
  14453. normal_fragment_begin: normal_fragment_begin,
  14454. normal_fragment_maps: normal_fragment_maps,
  14455. normalmap_pars_fragment: normalmap_pars_fragment,
  14456. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14457. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14458. clearcoat_pars_fragment: clearcoat_pars_fragment,
  14459. packing: packing,
  14460. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14461. project_vertex: project_vertex,
  14462. dithering_fragment: dithering_fragment,
  14463. dithering_pars_fragment: dithering_pars_fragment,
  14464. roughnessmap_fragment: roughnessmap_fragment,
  14465. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14466. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14467. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14468. shadowmap_vertex: shadowmap_vertex,
  14469. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14470. skinbase_vertex: skinbase_vertex,
  14471. skinning_pars_vertex: skinning_pars_vertex,
  14472. skinning_vertex: skinning_vertex,
  14473. skinnormal_vertex: skinnormal_vertex,
  14474. specularmap_fragment: specularmap_fragment,
  14475. specularmap_pars_fragment: specularmap_pars_fragment,
  14476. tonemapping_fragment: tonemapping_fragment,
  14477. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14478. transmissionmap_fragment: transmissionmap_fragment,
  14479. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  14480. uv_pars_fragment: uv_pars_fragment,
  14481. uv_pars_vertex: uv_pars_vertex,
  14482. uv_vertex: uv_vertex,
  14483. uv2_pars_fragment: uv2_pars_fragment,
  14484. uv2_pars_vertex: uv2_pars_vertex,
  14485. uv2_vertex: uv2_vertex,
  14486. worldpos_vertex: worldpos_vertex,
  14487. background_frag: background_frag,
  14488. background_vert: background_vert,
  14489. cube_frag: cube_frag,
  14490. cube_vert: cube_vert,
  14491. depth_frag: depth_frag,
  14492. depth_vert: depth_vert,
  14493. distanceRGBA_frag: distanceRGBA_frag,
  14494. distanceRGBA_vert: distanceRGBA_vert,
  14495. equirect_frag: equirect_frag,
  14496. equirect_vert: equirect_vert,
  14497. linedashed_frag: linedashed_frag,
  14498. linedashed_vert: linedashed_vert,
  14499. meshbasic_frag: meshbasic_frag,
  14500. meshbasic_vert: meshbasic_vert,
  14501. meshlambert_frag: meshlambert_frag,
  14502. meshlambert_vert: meshlambert_vert,
  14503. meshmatcap_frag: meshmatcap_frag,
  14504. meshmatcap_vert: meshmatcap_vert,
  14505. meshtoon_frag: meshtoon_frag,
  14506. meshtoon_vert: meshtoon_vert,
  14507. meshphong_frag: meshphong_frag,
  14508. meshphong_vert: meshphong_vert,
  14509. meshphysical_frag: meshphysical_frag,
  14510. meshphysical_vert: meshphysical_vert,
  14511. normal_frag: normal_frag,
  14512. normal_vert: normal_vert,
  14513. points_frag: points_frag,
  14514. points_vert: points_vert,
  14515. shadow_frag: shadow_frag,
  14516. shadow_vert: shadow_vert,
  14517. sprite_frag: sprite_frag,
  14518. sprite_vert: sprite_vert
  14519. };
  14520. var ShaderLib = {
  14521. basic: {
  14522. uniforms: mergeUniforms( [
  14523. UniformsLib.common,
  14524. UniformsLib.specularmap,
  14525. UniformsLib.envmap,
  14526. UniformsLib.aomap,
  14527. UniformsLib.lightmap,
  14528. UniformsLib.fog
  14529. ] ),
  14530. vertexShader: ShaderChunk.meshbasic_vert,
  14531. fragmentShader: ShaderChunk.meshbasic_frag
  14532. },
  14533. lambert: {
  14534. uniforms: mergeUniforms( [
  14535. UniformsLib.common,
  14536. UniformsLib.specularmap,
  14537. UniformsLib.envmap,
  14538. UniformsLib.aomap,
  14539. UniformsLib.lightmap,
  14540. UniformsLib.emissivemap,
  14541. UniformsLib.fog,
  14542. UniformsLib.lights,
  14543. {
  14544. emissive: { value: new Color( 0x000000 ) }
  14545. }
  14546. ] ),
  14547. vertexShader: ShaderChunk.meshlambert_vert,
  14548. fragmentShader: ShaderChunk.meshlambert_frag
  14549. },
  14550. phong: {
  14551. uniforms: mergeUniforms( [
  14552. UniformsLib.common,
  14553. UniformsLib.specularmap,
  14554. UniformsLib.envmap,
  14555. UniformsLib.aomap,
  14556. UniformsLib.lightmap,
  14557. UniformsLib.emissivemap,
  14558. UniformsLib.bumpmap,
  14559. UniformsLib.normalmap,
  14560. UniformsLib.displacementmap,
  14561. UniformsLib.fog,
  14562. UniformsLib.lights,
  14563. {
  14564. emissive: { value: new Color( 0x000000 ) },
  14565. specular: { value: new Color( 0x111111 ) },
  14566. shininess: { value: 30 }
  14567. }
  14568. ] ),
  14569. vertexShader: ShaderChunk.meshphong_vert,
  14570. fragmentShader: ShaderChunk.meshphong_frag
  14571. },
  14572. standard: {
  14573. uniforms: mergeUniforms( [
  14574. UniformsLib.common,
  14575. UniformsLib.envmap,
  14576. UniformsLib.aomap,
  14577. UniformsLib.lightmap,
  14578. UniformsLib.emissivemap,
  14579. UniformsLib.bumpmap,
  14580. UniformsLib.normalmap,
  14581. UniformsLib.displacementmap,
  14582. UniformsLib.roughnessmap,
  14583. UniformsLib.metalnessmap,
  14584. UniformsLib.fog,
  14585. UniformsLib.lights,
  14586. {
  14587. emissive: { value: new Color( 0x000000 ) },
  14588. roughness: { value: 1.0 },
  14589. metalness: { value: 0.0 },
  14590. envMapIntensity: { value: 1 } // temporary
  14591. }
  14592. ] ),
  14593. vertexShader: ShaderChunk.meshphysical_vert,
  14594. fragmentShader: ShaderChunk.meshphysical_frag
  14595. },
  14596. toon: {
  14597. uniforms: mergeUniforms( [
  14598. UniformsLib.common,
  14599. UniformsLib.aomap,
  14600. UniformsLib.lightmap,
  14601. UniformsLib.emissivemap,
  14602. UniformsLib.bumpmap,
  14603. UniformsLib.normalmap,
  14604. UniformsLib.displacementmap,
  14605. UniformsLib.gradientmap,
  14606. UniformsLib.fog,
  14607. UniformsLib.lights,
  14608. {
  14609. emissive: { value: new Color( 0x000000 ) }
  14610. }
  14611. ] ),
  14612. vertexShader: ShaderChunk.meshtoon_vert,
  14613. fragmentShader: ShaderChunk.meshtoon_frag
  14614. },
  14615. matcap: {
  14616. uniforms: mergeUniforms( [
  14617. UniformsLib.common,
  14618. UniformsLib.bumpmap,
  14619. UniformsLib.normalmap,
  14620. UniformsLib.displacementmap,
  14621. UniformsLib.fog,
  14622. {
  14623. matcap: { value: null }
  14624. }
  14625. ] ),
  14626. vertexShader: ShaderChunk.meshmatcap_vert,
  14627. fragmentShader: ShaderChunk.meshmatcap_frag
  14628. },
  14629. points: {
  14630. uniforms: mergeUniforms( [
  14631. UniformsLib.points,
  14632. UniformsLib.fog
  14633. ] ),
  14634. vertexShader: ShaderChunk.points_vert,
  14635. fragmentShader: ShaderChunk.points_frag
  14636. },
  14637. dashed: {
  14638. uniforms: mergeUniforms( [
  14639. UniformsLib.common,
  14640. UniformsLib.fog,
  14641. {
  14642. scale: { value: 1 },
  14643. dashSize: { value: 1 },
  14644. totalSize: { value: 2 }
  14645. }
  14646. ] ),
  14647. vertexShader: ShaderChunk.linedashed_vert,
  14648. fragmentShader: ShaderChunk.linedashed_frag
  14649. },
  14650. depth: {
  14651. uniforms: mergeUniforms( [
  14652. UniformsLib.common,
  14653. UniformsLib.displacementmap
  14654. ] ),
  14655. vertexShader: ShaderChunk.depth_vert,
  14656. fragmentShader: ShaderChunk.depth_frag
  14657. },
  14658. normal: {
  14659. uniforms: mergeUniforms( [
  14660. UniformsLib.common,
  14661. UniformsLib.bumpmap,
  14662. UniformsLib.normalmap,
  14663. UniformsLib.displacementmap,
  14664. {
  14665. opacity: { value: 1.0 }
  14666. }
  14667. ] ),
  14668. vertexShader: ShaderChunk.normal_vert,
  14669. fragmentShader: ShaderChunk.normal_frag
  14670. },
  14671. sprite: {
  14672. uniforms: mergeUniforms( [
  14673. UniformsLib.sprite,
  14674. UniformsLib.fog
  14675. ] ),
  14676. vertexShader: ShaderChunk.sprite_vert,
  14677. fragmentShader: ShaderChunk.sprite_frag
  14678. },
  14679. background: {
  14680. uniforms: {
  14681. uvTransform: { value: new Matrix3() },
  14682. t2D: { value: null },
  14683. },
  14684. vertexShader: ShaderChunk.background_vert,
  14685. fragmentShader: ShaderChunk.background_frag
  14686. },
  14687. /* -------------------------------------------------------------------------
  14688. // Cube map shader
  14689. ------------------------------------------------------------------------- */
  14690. cube: {
  14691. uniforms: mergeUniforms( [
  14692. UniformsLib.envmap,
  14693. {
  14694. opacity: { value: 1.0 }
  14695. }
  14696. ] ),
  14697. vertexShader: ShaderChunk.cube_vert,
  14698. fragmentShader: ShaderChunk.cube_frag
  14699. },
  14700. equirect: {
  14701. uniforms: {
  14702. tEquirect: { value: null },
  14703. },
  14704. vertexShader: ShaderChunk.equirect_vert,
  14705. fragmentShader: ShaderChunk.equirect_frag
  14706. },
  14707. distanceRGBA: {
  14708. uniforms: mergeUniforms( [
  14709. UniformsLib.common,
  14710. UniformsLib.displacementmap,
  14711. {
  14712. referencePosition: { value: new Vector3() },
  14713. nearDistance: { value: 1 },
  14714. farDistance: { value: 1000 }
  14715. }
  14716. ] ),
  14717. vertexShader: ShaderChunk.distanceRGBA_vert,
  14718. fragmentShader: ShaderChunk.distanceRGBA_frag
  14719. },
  14720. shadow: {
  14721. uniforms: mergeUniforms( [
  14722. UniformsLib.lights,
  14723. UniformsLib.fog,
  14724. {
  14725. color: { value: new Color( 0x00000 ) },
  14726. opacity: { value: 1.0 }
  14727. } ] ),
  14728. vertexShader: ShaderChunk.shadow_vert,
  14729. fragmentShader: ShaderChunk.shadow_frag
  14730. }
  14731. };
  14732. ShaderLib.physical = {
  14733. uniforms: mergeUniforms( [
  14734. ShaderLib.standard.uniforms,
  14735. {
  14736. clearcoat: { value: 0 },
  14737. clearcoatMap: { value: null },
  14738. clearcoatRoughness: { value: 0 },
  14739. clearcoatRoughnessMap: { value: null },
  14740. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  14741. clearcoatNormalMap: { value: null },
  14742. sheen: { value: new Color( 0x000000 ) },
  14743. transmission: { value: 0 },
  14744. transmissionMap: { value: null },
  14745. }
  14746. ] ),
  14747. vertexShader: ShaderChunk.meshphysical_vert,
  14748. fragmentShader: ShaderChunk.meshphysical_frag
  14749. };
  14750. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  14751. var clearColor = new Color( 0x000000 );
  14752. var clearAlpha = 0;
  14753. var planeMesh;
  14754. var boxMesh;
  14755. var currentBackground = null;
  14756. var currentBackgroundVersion = 0;
  14757. var currentTonemapping = null;
  14758. function render( renderList, scene, camera, forceClear ) {
  14759. var background = scene.isScene === true ? scene.background : null;
  14760. // Ignore background in AR
  14761. // TODO: Reconsider this.
  14762. var xr = renderer.xr;
  14763. var session = xr.getSession && xr.getSession();
  14764. if ( session && session.environmentBlendMode === 'additive' ) {
  14765. background = null;
  14766. }
  14767. if ( background === null ) {
  14768. setClear( clearColor, clearAlpha );
  14769. } else if ( background && background.isColor ) {
  14770. setClear( background, 1 );
  14771. forceClear = true;
  14772. }
  14773. if ( renderer.autoClear || forceClear ) {
  14774. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  14775. }
  14776. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  14777. if ( boxMesh === undefined ) {
  14778. boxMesh = new Mesh(
  14779. new BoxBufferGeometry( 1, 1, 1 ),
  14780. new ShaderMaterial( {
  14781. name: 'BackgroundCubeMaterial',
  14782. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  14783. vertexShader: ShaderLib.cube.vertexShader,
  14784. fragmentShader: ShaderLib.cube.fragmentShader,
  14785. side: BackSide,
  14786. depthTest: false,
  14787. depthWrite: false,
  14788. fog: false
  14789. } )
  14790. );
  14791. boxMesh.geometry.deleteAttribute( 'normal' );
  14792. boxMesh.geometry.deleteAttribute( 'uv' );
  14793. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14794. this.matrixWorld.copyPosition( camera.matrixWorld );
  14795. };
  14796. // enable code injection for non-built-in material
  14797. Object.defineProperty( boxMesh.material, 'envMap', {
  14798. get: function () {
  14799. return this.uniforms.envMap.value;
  14800. }
  14801. } );
  14802. objects.update( boxMesh );
  14803. }
  14804. var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
  14805. boxMesh.material.uniforms.envMap.value = texture;
  14806. boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1;
  14807. if ( currentBackground !== background ||
  14808. currentBackgroundVersion !== texture.version ||
  14809. currentTonemapping !== renderer.toneMapping ) {
  14810. boxMesh.material.needsUpdate = true;
  14811. currentBackground = background;
  14812. currentBackgroundVersion = texture.version;
  14813. currentTonemapping = renderer.toneMapping;
  14814. }
  14815. // push to the pre-sorted opaque render list
  14816. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  14817. } else if ( background && background.isTexture ) {
  14818. if ( planeMesh === undefined ) {
  14819. planeMesh = new Mesh(
  14820. new PlaneBufferGeometry( 2, 2 ),
  14821. new ShaderMaterial( {
  14822. name: 'BackgroundMaterial',
  14823. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  14824. vertexShader: ShaderLib.background.vertexShader,
  14825. fragmentShader: ShaderLib.background.fragmentShader,
  14826. side: FrontSide,
  14827. depthTest: false,
  14828. depthWrite: false,
  14829. fog: false
  14830. } )
  14831. );
  14832. planeMesh.geometry.deleteAttribute( 'normal' );
  14833. // enable code injection for non-built-in material
  14834. Object.defineProperty( planeMesh.material, 'map', {
  14835. get: function () {
  14836. return this.uniforms.t2D.value;
  14837. }
  14838. } );
  14839. objects.update( planeMesh );
  14840. }
  14841. planeMesh.material.uniforms.t2D.value = background;
  14842. if ( background.matrixAutoUpdate === true ) {
  14843. background.updateMatrix();
  14844. }
  14845. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  14846. if ( currentBackground !== background ||
  14847. currentBackgroundVersion !== background.version ||
  14848. currentTonemapping !== renderer.toneMapping ) {
  14849. planeMesh.material.needsUpdate = true;
  14850. currentBackground = background;
  14851. currentBackgroundVersion = background.version;
  14852. currentTonemapping = renderer.toneMapping;
  14853. }
  14854. // push to the pre-sorted opaque render list
  14855. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  14856. }
  14857. }
  14858. function setClear( color, alpha ) {
  14859. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  14860. }
  14861. return {
  14862. getClearColor: function () {
  14863. return clearColor;
  14864. },
  14865. setClearColor: function ( color, alpha ) {
  14866. clearColor.set( color );
  14867. clearAlpha = alpha !== undefined ? alpha : 1;
  14868. setClear( clearColor, clearAlpha );
  14869. },
  14870. getClearAlpha: function () {
  14871. return clearAlpha;
  14872. },
  14873. setClearAlpha: function ( alpha ) {
  14874. clearAlpha = alpha;
  14875. setClear( clearColor, clearAlpha );
  14876. },
  14877. render: render
  14878. };
  14879. }
  14880. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  14881. var maxVertexAttributes = gl.getParameter( 34921 );
  14882. var extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  14883. var vaoAvailable = capabilities.isWebGL2 || extension !== null;
  14884. var bindingStates = {};
  14885. var defaultState = createBindingState( null );
  14886. var currentState = defaultState;
  14887. function setup( object, material, program, geometry, index ) {
  14888. var updateBuffers = false;
  14889. if ( vaoAvailable ) {
  14890. var state = getBindingState( geometry, program, material );
  14891. if ( currentState !== state ) {
  14892. currentState = state;
  14893. bindVertexArrayObject( currentState.object );
  14894. }
  14895. updateBuffers = needsUpdate( geometry );
  14896. if ( updateBuffers ) { saveCache( geometry ); }
  14897. } else {
  14898. var wireframe = ( material.wireframe === true );
  14899. if ( currentState.geometry !== geometry.id ||
  14900. currentState.program !== program.id ||
  14901. currentState.wireframe !== wireframe ) {
  14902. currentState.geometry = geometry.id;
  14903. currentState.program = program.id;
  14904. currentState.wireframe = wireframe;
  14905. updateBuffers = true;
  14906. }
  14907. }
  14908. if ( object.isInstancedMesh === true ) {
  14909. updateBuffers = true;
  14910. }
  14911. if ( index !== null ) {
  14912. attributes.update( index, 34963 );
  14913. }
  14914. if ( updateBuffers ) {
  14915. setupVertexAttributes( object, material, program, geometry );
  14916. if ( index !== null ) {
  14917. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  14918. }
  14919. }
  14920. }
  14921. function createVertexArrayObject() {
  14922. if ( capabilities.isWebGL2 ) { return gl.createVertexArray(); }
  14923. return extension.createVertexArrayOES();
  14924. }
  14925. function bindVertexArrayObject( vao ) {
  14926. if ( capabilities.isWebGL2 ) { return gl.bindVertexArray( vao ); }
  14927. return extension.bindVertexArrayOES( vao );
  14928. }
  14929. function deleteVertexArrayObject( vao ) {
  14930. if ( capabilities.isWebGL2 ) { return gl.deleteVertexArray( vao ); }
  14931. return extension.deleteVertexArrayOES( vao );
  14932. }
  14933. function getBindingState( geometry, program, material ) {
  14934. var wireframe = ( material.wireframe === true );
  14935. var programMap = bindingStates[ geometry.id ];
  14936. if ( programMap === undefined ) {
  14937. programMap = {};
  14938. bindingStates[ geometry.id ] = programMap;
  14939. }
  14940. var stateMap = programMap[ program.id ];
  14941. if ( stateMap === undefined ) {
  14942. stateMap = {};
  14943. programMap[ program.id ] = stateMap;
  14944. }
  14945. var state = stateMap[ wireframe ];
  14946. if ( state === undefined ) {
  14947. state = createBindingState( createVertexArrayObject() );
  14948. stateMap[ wireframe ] = state;
  14949. }
  14950. return state;
  14951. }
  14952. function createBindingState( vao ) {
  14953. var newAttributes = [];
  14954. var enabledAttributes = [];
  14955. var attributeDivisors = [];
  14956. for ( var i = 0; i < maxVertexAttributes; i ++ ) {
  14957. newAttributes[ i ] = 0;
  14958. enabledAttributes[ i ] = 0;
  14959. attributeDivisors[ i ] = 0;
  14960. }
  14961. return {
  14962. // for backward compatibility on non-VAO support browser
  14963. geometry: null,
  14964. program: null,
  14965. wireframe: false,
  14966. newAttributes: newAttributes,
  14967. enabledAttributes: enabledAttributes,
  14968. attributeDivisors: attributeDivisors,
  14969. object: vao,
  14970. attributes: {}
  14971. };
  14972. }
  14973. function needsUpdate( geometry ) {
  14974. var cachedAttributes = currentState.attributes;
  14975. var geometryAttributes = geometry.attributes;
  14976. if ( Object.keys( cachedAttributes ).length !== Object.keys( geometryAttributes ).length ) { return true; }
  14977. for ( var key in geometryAttributes ) {
  14978. var cachedAttribute = cachedAttributes[ key ];
  14979. var geometryAttribute = geometryAttributes[ key ];
  14980. if ( cachedAttribute.attribute !== geometryAttribute ) { return true; }
  14981. if ( cachedAttribute.data !== geometryAttribute.data ) { return true; }
  14982. }
  14983. return false;
  14984. }
  14985. function saveCache( geometry ) {
  14986. var cache = {};
  14987. var attributes = geometry.attributes;
  14988. for ( var key in attributes ) {
  14989. var attribute = attributes[ key ];
  14990. var data = {};
  14991. data.attribute = attribute;
  14992. if ( attribute.data ) {
  14993. data.data = attribute.data;
  14994. }
  14995. cache[ key ] = data;
  14996. }
  14997. currentState.attributes = cache;
  14998. }
  14999. function initAttributes() {
  15000. var newAttributes = currentState.newAttributes;
  15001. for ( var i = 0, il = newAttributes.length; i < il; i ++ ) {
  15002. newAttributes[ i ] = 0;
  15003. }
  15004. }
  15005. function enableAttribute( attribute ) {
  15006. enableAttributeAndDivisor( attribute, 0 );
  15007. }
  15008. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  15009. var newAttributes = currentState.newAttributes;
  15010. var enabledAttributes = currentState.enabledAttributes;
  15011. var attributeDivisors = currentState.attributeDivisors;
  15012. newAttributes[ attribute ] = 1;
  15013. if ( enabledAttributes[ attribute ] === 0 ) {
  15014. gl.enableVertexAttribArray( attribute );
  15015. enabledAttributes[ attribute ] = 1;
  15016. }
  15017. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15018. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  15019. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  15020. attributeDivisors[ attribute ] = meshPerAttribute;
  15021. }
  15022. }
  15023. function disableUnusedAttributes() {
  15024. var newAttributes = currentState.newAttributes;
  15025. var enabledAttributes = currentState.enabledAttributes;
  15026. for ( var i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  15027. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15028. gl.disableVertexAttribArray( i );
  15029. enabledAttributes[ i ] = 0;
  15030. }
  15031. }
  15032. }
  15033. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  15034. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  15035. gl.vertexAttribIPointer( index, size, type, stride, offset );
  15036. } else {
  15037. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  15038. }
  15039. }
  15040. function setupVertexAttributes( object, material, program, geometry ) {
  15041. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  15042. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { return; }
  15043. }
  15044. initAttributes();
  15045. var geometryAttributes = geometry.attributes;
  15046. var programAttributes = program.getAttributes();
  15047. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15048. for ( var name in programAttributes ) {
  15049. var programAttribute = programAttributes[ name ];
  15050. if ( programAttribute >= 0 ) {
  15051. var geometryAttribute = geometryAttributes[ name ];
  15052. if ( geometryAttribute !== undefined ) {
  15053. var normalized = geometryAttribute.normalized;
  15054. var size = geometryAttribute.itemSize;
  15055. var attribute = attributes.get( geometryAttribute );
  15056. // TODO Attribute may not be available on context restore
  15057. if ( attribute === undefined ) { continue; }
  15058. var buffer = attribute.buffer;
  15059. var type = attribute.type;
  15060. var bytesPerElement = attribute.bytesPerElement;
  15061. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  15062. var data = geometryAttribute.data;
  15063. var stride = data.stride;
  15064. var offset = geometryAttribute.offset;
  15065. if ( data && data.isInstancedInterleavedBuffer ) {
  15066. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  15067. if ( geometry._maxInstanceCount === undefined ) {
  15068. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  15069. }
  15070. } else {
  15071. enableAttribute( programAttribute );
  15072. }
  15073. gl.bindBuffer( 34962, buffer );
  15074. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  15075. } else {
  15076. if ( geometryAttribute.isInstancedBufferAttribute ) {
  15077. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  15078. if ( geometry._maxInstanceCount === undefined ) {
  15079. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15080. }
  15081. } else {
  15082. enableAttribute( programAttribute );
  15083. }
  15084. gl.bindBuffer( 34962, buffer );
  15085. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  15086. }
  15087. } else if ( name === 'instanceMatrix' ) {
  15088. var attribute$1 = attributes.get( object.instanceMatrix );
  15089. // TODO Attribute may not be available on context restore
  15090. if ( attribute$1 === undefined ) { continue; }
  15091. var buffer$1 = attribute$1.buffer;
  15092. var type$1 = attribute$1.type;
  15093. enableAttributeAndDivisor( programAttribute + 0, 1 );
  15094. enableAttributeAndDivisor( programAttribute + 1, 1 );
  15095. enableAttributeAndDivisor( programAttribute + 2, 1 );
  15096. enableAttributeAndDivisor( programAttribute + 3, 1 );
  15097. gl.bindBuffer( 34962, buffer$1 );
  15098. gl.vertexAttribPointer( programAttribute + 0, 4, type$1, false, 64, 0 );
  15099. gl.vertexAttribPointer( programAttribute + 1, 4, type$1, false, 64, 16 );
  15100. gl.vertexAttribPointer( programAttribute + 2, 4, type$1, false, 64, 32 );
  15101. gl.vertexAttribPointer( programAttribute + 3, 4, type$1, false, 64, 48 );
  15102. } else if ( materialDefaultAttributeValues !== undefined ) {
  15103. var value = materialDefaultAttributeValues[ name ];
  15104. if ( value !== undefined ) {
  15105. switch ( value.length ) {
  15106. case 2:
  15107. gl.vertexAttrib2fv( programAttribute, value );
  15108. break;
  15109. case 3:
  15110. gl.vertexAttrib3fv( programAttribute, value );
  15111. break;
  15112. case 4:
  15113. gl.vertexAttrib4fv( programAttribute, value );
  15114. break;
  15115. default:
  15116. gl.vertexAttrib1fv( programAttribute, value );
  15117. }
  15118. }
  15119. }
  15120. }
  15121. }
  15122. disableUnusedAttributes();
  15123. }
  15124. function dispose() {
  15125. reset();
  15126. for ( var geometryId in bindingStates ) {
  15127. var programMap = bindingStates[ geometryId ];
  15128. for ( var programId in programMap ) {
  15129. var stateMap = programMap[ programId ];
  15130. for ( var wireframe in stateMap ) {
  15131. deleteVertexArrayObject( stateMap[ wireframe ].object );
  15132. delete stateMap[ wireframe ];
  15133. }
  15134. delete programMap[ programId ];
  15135. }
  15136. delete bindingStates[ geometryId ];
  15137. }
  15138. }
  15139. function releaseStatesOfGeometry( geometry ) {
  15140. if ( bindingStates[ geometry.id ] === undefined ) { return; }
  15141. var programMap = bindingStates[ geometry.id ];
  15142. for ( var programId in programMap ) {
  15143. var stateMap = programMap[ programId ];
  15144. for ( var wireframe in stateMap ) {
  15145. deleteVertexArrayObject( stateMap[ wireframe ].object );
  15146. delete stateMap[ wireframe ];
  15147. }
  15148. delete programMap[ programId ];
  15149. }
  15150. delete bindingStates[ geometry.id ];
  15151. }
  15152. function releaseStatesOfProgram( program ) {
  15153. for ( var geometryId in bindingStates ) {
  15154. var programMap = bindingStates[ geometryId ];
  15155. if ( programMap[ program.id ] === undefined ) { continue; }
  15156. var stateMap = programMap[ program.id ];
  15157. for ( var wireframe in stateMap ) {
  15158. deleteVertexArrayObject( stateMap[ wireframe ].object );
  15159. delete stateMap[ wireframe ];
  15160. }
  15161. delete programMap[ program.id ];
  15162. }
  15163. }
  15164. function reset() {
  15165. resetDefaultState();
  15166. if ( currentState === defaultState ) { return; }
  15167. currentState = defaultState;
  15168. bindVertexArrayObject( currentState.object );
  15169. }
  15170. // for backward-compatilibity
  15171. function resetDefaultState() {
  15172. defaultState.geometry = null;
  15173. defaultState.program = null;
  15174. defaultState.wireframe = false;
  15175. }
  15176. return {
  15177. setup: setup,
  15178. reset: reset,
  15179. resetDefaultState: resetDefaultState,
  15180. dispose: dispose,
  15181. releaseStatesOfGeometry: releaseStatesOfGeometry,
  15182. releaseStatesOfProgram: releaseStatesOfProgram,
  15183. initAttributes: initAttributes,
  15184. enableAttribute: enableAttribute,
  15185. disableUnusedAttributes: disableUnusedAttributes
  15186. };
  15187. }
  15188. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  15189. var isWebGL2 = capabilities.isWebGL2;
  15190. var mode;
  15191. function setMode( value ) {
  15192. mode = value;
  15193. }
  15194. function render( start, count ) {
  15195. gl.drawArrays( mode, start, count );
  15196. info.update( count, mode, 1 );
  15197. }
  15198. function renderInstances( start, count, primcount ) {
  15199. if ( primcount === 0 ) { return; }
  15200. var extension, methodName;
  15201. if ( isWebGL2 ) {
  15202. extension = gl;
  15203. methodName = 'drawArraysInstanced';
  15204. } else {
  15205. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15206. methodName = 'drawArraysInstancedANGLE';
  15207. if ( extension === null ) {
  15208. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15209. return;
  15210. }
  15211. }
  15212. extension[ methodName ]( mode, start, count, primcount );
  15213. info.update( count, mode, primcount );
  15214. }
  15215. //
  15216. this.setMode = setMode;
  15217. this.render = render;
  15218. this.renderInstances = renderInstances;
  15219. }
  15220. function WebGLCapabilities( gl, extensions, parameters ) {
  15221. var maxAnisotropy;
  15222. function getMaxAnisotropy() {
  15223. if ( maxAnisotropy !== undefined ) { return maxAnisotropy; }
  15224. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15225. if ( extension !== null ) {
  15226. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  15227. } else {
  15228. maxAnisotropy = 0;
  15229. }
  15230. return maxAnisotropy;
  15231. }
  15232. function getMaxPrecision( precision ) {
  15233. if ( precision === 'highp' ) {
  15234. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  15235. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  15236. return 'highp';
  15237. }
  15238. precision = 'mediump';
  15239. }
  15240. if ( precision === 'mediump' ) {
  15241. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  15242. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  15243. return 'mediump';
  15244. }
  15245. }
  15246. return 'lowp';
  15247. }
  15248. /* eslint-disable no-undef */
  15249. var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  15250. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  15251. /* eslint-enable no-undef */
  15252. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15253. var maxPrecision = getMaxPrecision( precision );
  15254. if ( maxPrecision !== precision ) {
  15255. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  15256. precision = maxPrecision;
  15257. }
  15258. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  15259. var maxTextures = gl.getParameter( 34930 );
  15260. var maxVertexTextures = gl.getParameter( 35660 );
  15261. var maxTextureSize = gl.getParameter( 3379 );
  15262. var maxCubemapSize = gl.getParameter( 34076 );
  15263. var maxAttributes = gl.getParameter( 34921 );
  15264. var maxVertexUniforms = gl.getParameter( 36347 );
  15265. var maxVaryings = gl.getParameter( 36348 );
  15266. var maxFragmentUniforms = gl.getParameter( 36349 );
  15267. var vertexTextures = maxVertexTextures > 0;
  15268. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  15269. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15270. var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  15271. return {
  15272. isWebGL2: isWebGL2,
  15273. getMaxAnisotropy: getMaxAnisotropy,
  15274. getMaxPrecision: getMaxPrecision,
  15275. precision: precision,
  15276. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15277. maxTextures: maxTextures,
  15278. maxVertexTextures: maxVertexTextures,
  15279. maxTextureSize: maxTextureSize,
  15280. maxCubemapSize: maxCubemapSize,
  15281. maxAttributes: maxAttributes,
  15282. maxVertexUniforms: maxVertexUniforms,
  15283. maxVaryings: maxVaryings,
  15284. maxFragmentUniforms: maxFragmentUniforms,
  15285. vertexTextures: vertexTextures,
  15286. floatFragmentTextures: floatFragmentTextures,
  15287. floatVertexTextures: floatVertexTextures,
  15288. maxSamples: maxSamples
  15289. };
  15290. }
  15291. function WebGLClipping() {
  15292. var scope = this;
  15293. var globalState = null,
  15294. numGlobalPlanes = 0,
  15295. localClippingEnabled = false,
  15296. renderingShadows = false;
  15297. var plane = new Plane(),
  15298. viewNormalMatrix = new Matrix3(),
  15299. uniform = { value: null, needsUpdate: false };
  15300. this.uniform = uniform;
  15301. this.numPlanes = 0;
  15302. this.numIntersection = 0;
  15303. this.init = function ( planes, enableLocalClipping, camera ) {
  15304. var enabled =
  15305. planes.length !== 0 ||
  15306. enableLocalClipping ||
  15307. // enable state of previous frame - the clipping code has to
  15308. // run another frame in order to reset the state:
  15309. numGlobalPlanes !== 0 ||
  15310. localClippingEnabled;
  15311. localClippingEnabled = enableLocalClipping;
  15312. globalState = projectPlanes( planes, camera, 0 );
  15313. numGlobalPlanes = planes.length;
  15314. return enabled;
  15315. };
  15316. this.beginShadows = function () {
  15317. renderingShadows = true;
  15318. projectPlanes( null );
  15319. };
  15320. this.endShadows = function () {
  15321. renderingShadows = false;
  15322. resetGlobalState();
  15323. };
  15324. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  15325. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  15326. // there's no local clipping
  15327. if ( renderingShadows ) {
  15328. // there's no global clipping
  15329. projectPlanes( null );
  15330. } else {
  15331. resetGlobalState();
  15332. }
  15333. } else {
  15334. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15335. lGlobal = nGlobal * 4;
  15336. var dstArray = cache.clippingState || null;
  15337. uniform.value = dstArray; // ensure unique state
  15338. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  15339. for ( var i = 0; i !== lGlobal; ++ i ) {
  15340. dstArray[ i ] = globalState[ i ];
  15341. }
  15342. cache.clippingState = dstArray;
  15343. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15344. this.numPlanes += nGlobal;
  15345. }
  15346. };
  15347. function resetGlobalState() {
  15348. if ( uniform.value !== globalState ) {
  15349. uniform.value = globalState;
  15350. uniform.needsUpdate = numGlobalPlanes > 0;
  15351. }
  15352. scope.numPlanes = numGlobalPlanes;
  15353. scope.numIntersection = 0;
  15354. }
  15355. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  15356. var nPlanes = planes !== null ? planes.length : 0,
  15357. dstArray = null;
  15358. if ( nPlanes !== 0 ) {
  15359. dstArray = uniform.value;
  15360. if ( skipTransform !== true || dstArray === null ) {
  15361. var flatSize = dstOffset + nPlanes * 4,
  15362. viewMatrix = camera.matrixWorldInverse;
  15363. viewNormalMatrix.getNormalMatrix( viewMatrix );
  15364. if ( dstArray === null || dstArray.length < flatSize ) {
  15365. dstArray = new Float32Array( flatSize );
  15366. }
  15367. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  15368. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  15369. plane.normal.toArray( dstArray, i4 );
  15370. dstArray[ i4 + 3 ] = plane.constant;
  15371. }
  15372. }
  15373. uniform.value = dstArray;
  15374. uniform.needsUpdate = true;
  15375. }
  15376. scope.numPlanes = nPlanes;
  15377. scope.numIntersection = 0;
  15378. return dstArray;
  15379. }
  15380. }
  15381. function WebGLExtensions( gl ) {
  15382. var extensions = {};
  15383. return {
  15384. has: function ( name ) {
  15385. if ( extensions[ name ] !== undefined ) {
  15386. return extensions[ name ];
  15387. }
  15388. var extension;
  15389. switch ( name ) {
  15390. case 'WEBGL_depth_texture':
  15391. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  15392. break;
  15393. case 'EXT_texture_filter_anisotropic':
  15394. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15395. break;
  15396. case 'WEBGL_compressed_texture_s3tc':
  15397. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15398. break;
  15399. case 'WEBGL_compressed_texture_pvrtc':
  15400. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15401. break;
  15402. default:
  15403. extension = gl.getExtension( name );
  15404. }
  15405. extensions[ name ] = extension;
  15406. return !! extension;
  15407. },
  15408. get: function ( name ) {
  15409. if ( ! this.has( name ) ) {
  15410. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15411. }
  15412. return extensions[ name ];
  15413. }
  15414. };
  15415. }
  15416. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  15417. var geometries = new WeakMap();
  15418. var wireframeAttributes = new WeakMap();
  15419. function onGeometryDispose( event ) {
  15420. var geometry = event.target;
  15421. var buffergeometry = geometries.get( geometry );
  15422. if ( buffergeometry.index !== null ) {
  15423. attributes.remove( buffergeometry.index );
  15424. }
  15425. for ( var name in buffergeometry.attributes ) {
  15426. attributes.remove( buffergeometry.attributes[ name ] );
  15427. }
  15428. geometry.removeEventListener( 'dispose', onGeometryDispose );
  15429. geometries.delete( geometry );
  15430. var attribute = wireframeAttributes.get( buffergeometry );
  15431. if ( attribute ) {
  15432. attributes.remove( attribute );
  15433. wireframeAttributes.delete( buffergeometry );
  15434. }
  15435. bindingStates.releaseStatesOfGeometry( geometry );
  15436. if ( geometry.isInstancedBufferGeometry === true ) {
  15437. delete geometry._maxInstanceCount;
  15438. }
  15439. //
  15440. info.memory.geometries --;
  15441. }
  15442. function get( object, geometry ) {
  15443. var buffergeometry = geometries.get( geometry );
  15444. if ( buffergeometry ) { return buffergeometry; }
  15445. geometry.addEventListener( 'dispose', onGeometryDispose );
  15446. if ( geometry.isBufferGeometry ) {
  15447. buffergeometry = geometry;
  15448. } else if ( geometry.isGeometry ) {
  15449. if ( geometry._bufferGeometry === undefined ) {
  15450. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  15451. }
  15452. buffergeometry = geometry._bufferGeometry;
  15453. }
  15454. geometries.set( geometry, buffergeometry );
  15455. info.memory.geometries ++;
  15456. return buffergeometry;
  15457. }
  15458. function update( geometry ) {
  15459. var geometryAttributes = geometry.attributes;
  15460. // Updating index buffer in VAO now. See WebGLBindingStates.
  15461. for ( var name in geometryAttributes ) {
  15462. attributes.update( geometryAttributes[ name ], 34962 );
  15463. }
  15464. // morph targets
  15465. var morphAttributes = geometry.morphAttributes;
  15466. for ( var name$1 in morphAttributes ) {
  15467. var array = morphAttributes[ name$1 ];
  15468. for ( var i = 0, l = array.length; i < l; i ++ ) {
  15469. attributes.update( array[ i ], 34962 );
  15470. }
  15471. }
  15472. }
  15473. function updateWireframeAttribute( geometry ) {
  15474. var indices = [];
  15475. var geometryIndex = geometry.index;
  15476. var geometryPosition = geometry.attributes.position;
  15477. var version = 0;
  15478. if ( geometryIndex !== null ) {
  15479. var array = geometryIndex.array;
  15480. version = geometryIndex.version;
  15481. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  15482. var a = array[ i + 0 ];
  15483. var b = array[ i + 1 ];
  15484. var c = array[ i + 2 ];
  15485. indices.push( a, b, b, c, c, a );
  15486. }
  15487. } else {
  15488. var array$1 = geometryPosition.array;
  15489. version = geometryPosition.version;
  15490. for ( var i$1 = 0, l$1 = ( array$1.length / 3 ) - 1; i$1 < l$1; i$1 += 3 ) {
  15491. var a$1 = i$1 + 0;
  15492. var b$1 = i$1 + 1;
  15493. var c$1 = i$1 + 2;
  15494. indices.push( a$1, b$1, b$1, c$1, c$1, a$1 );
  15495. }
  15496. }
  15497. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  15498. attribute.version = version;
  15499. // Updating index buffer in VAO now. See WebGLBindingStates
  15500. //
  15501. var previousAttribute = wireframeAttributes.get( geometry );
  15502. if ( previousAttribute ) { attributes.remove( previousAttribute ); }
  15503. //
  15504. wireframeAttributes.set( geometry, attribute );
  15505. }
  15506. function getWireframeAttribute( geometry ) {
  15507. var currentAttribute = wireframeAttributes.get( geometry );
  15508. if ( currentAttribute ) {
  15509. var geometryIndex = geometry.index;
  15510. if ( geometryIndex !== null ) {
  15511. // if the attribute is obsolete, create a new one
  15512. if ( currentAttribute.version < geometryIndex.version ) {
  15513. updateWireframeAttribute( geometry );
  15514. }
  15515. }
  15516. } else {
  15517. updateWireframeAttribute( geometry );
  15518. }
  15519. return wireframeAttributes.get( geometry );
  15520. }
  15521. return {
  15522. get: get,
  15523. update: update,
  15524. getWireframeAttribute: getWireframeAttribute
  15525. };
  15526. }
  15527. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  15528. var isWebGL2 = capabilities.isWebGL2;
  15529. var mode;
  15530. function setMode( value ) {
  15531. mode = value;
  15532. }
  15533. var type, bytesPerElement;
  15534. function setIndex( value ) {
  15535. type = value.type;
  15536. bytesPerElement = value.bytesPerElement;
  15537. }
  15538. function render( start, count ) {
  15539. gl.drawElements( mode, count, type, start * bytesPerElement );
  15540. info.update( count, mode, 1 );
  15541. }
  15542. function renderInstances( start, count, primcount ) {
  15543. if ( primcount === 0 ) { return; }
  15544. var extension, methodName;
  15545. if ( isWebGL2 ) {
  15546. extension = gl;
  15547. methodName = 'drawElementsInstanced';
  15548. } else {
  15549. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15550. methodName = 'drawElementsInstancedANGLE';
  15551. if ( extension === null ) {
  15552. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15553. return;
  15554. }
  15555. }
  15556. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  15557. info.update( count, mode, primcount );
  15558. }
  15559. //
  15560. this.setMode = setMode;
  15561. this.setIndex = setIndex;
  15562. this.render = render;
  15563. this.renderInstances = renderInstances;
  15564. }
  15565. function WebGLInfo( gl ) {
  15566. var memory = {
  15567. geometries: 0,
  15568. textures: 0
  15569. };
  15570. var render = {
  15571. frame: 0,
  15572. calls: 0,
  15573. triangles: 0,
  15574. points: 0,
  15575. lines: 0
  15576. };
  15577. function update( count, mode, instanceCount ) {
  15578. render.calls ++;
  15579. switch ( mode ) {
  15580. case 4:
  15581. render.triangles += instanceCount * ( count / 3 );
  15582. break;
  15583. case 1:
  15584. render.lines += instanceCount * ( count / 2 );
  15585. break;
  15586. case 3:
  15587. render.lines += instanceCount * ( count - 1 );
  15588. break;
  15589. case 2:
  15590. render.lines += instanceCount * count;
  15591. break;
  15592. case 0:
  15593. render.points += instanceCount * count;
  15594. break;
  15595. default:
  15596. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  15597. break;
  15598. }
  15599. }
  15600. function reset() {
  15601. render.frame ++;
  15602. render.calls = 0;
  15603. render.triangles = 0;
  15604. render.points = 0;
  15605. render.lines = 0;
  15606. }
  15607. return {
  15608. memory: memory,
  15609. render: render,
  15610. programs: null,
  15611. autoReset: true,
  15612. reset: reset,
  15613. update: update
  15614. };
  15615. }
  15616. function numericalSort( a, b ) {
  15617. return a[ 0 ] - b[ 0 ];
  15618. }
  15619. function absNumericalSort( a, b ) {
  15620. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  15621. }
  15622. function WebGLMorphtargets( gl ) {
  15623. var influencesList = {};
  15624. var morphInfluences = new Float32Array( 8 );
  15625. var workInfluences = [];
  15626. for ( var i = 0; i < 8; i ++ ) {
  15627. workInfluences[ i ] = [ i, 0 ];
  15628. }
  15629. function update( object, geometry, material, program ) {
  15630. var objectInfluences = object.morphTargetInfluences;
  15631. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  15632. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  15633. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  15634. var influences = influencesList[ geometry.id ];
  15635. if ( influences === undefined ) {
  15636. // initialise list
  15637. influences = [];
  15638. for ( var i = 0; i < length; i ++ ) {
  15639. influences[ i ] = [ i, 0 ];
  15640. }
  15641. influencesList[ geometry.id ] = influences;
  15642. }
  15643. // Collect influences
  15644. for ( var i$1 = 0; i$1 < length; i$1 ++ ) {
  15645. var influence = influences[ i$1 ];
  15646. influence[ 0 ] = i$1;
  15647. influence[ 1 ] = objectInfluences[ i$1 ];
  15648. }
  15649. influences.sort( absNumericalSort );
  15650. for ( var i$2 = 0; i$2 < 8; i$2 ++ ) {
  15651. if ( i$2 < length && influences[ i$2 ][ 1 ] ) {
  15652. workInfluences[ i$2 ][ 0 ] = influences[ i$2 ][ 0 ];
  15653. workInfluences[ i$2 ][ 1 ] = influences[ i$2 ][ 1 ];
  15654. } else {
  15655. workInfluences[ i$2 ][ 0 ] = Number.MAX_SAFE_INTEGER;
  15656. workInfluences[ i$2 ][ 1 ] = 0;
  15657. }
  15658. }
  15659. workInfluences.sort( numericalSort );
  15660. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  15661. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  15662. var morphInfluencesSum = 0;
  15663. for ( var i$3 = 0; i$3 < 8; i$3 ++ ) {
  15664. var influence$1 = workInfluences[ i$3 ];
  15665. var index = influence$1[ 0 ];
  15666. var value = influence$1[ 1 ];
  15667. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  15668. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i$3 ) !== morphTargets[ index ] ) {
  15669. geometry.setAttribute( 'morphTarget' + i$3, morphTargets[ index ] );
  15670. }
  15671. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i$3 ) !== morphNormals[ index ] ) {
  15672. geometry.setAttribute( 'morphNormal' + i$3, morphNormals[ index ] );
  15673. }
  15674. morphInfluences[ i$3 ] = value;
  15675. morphInfluencesSum += value;
  15676. } else {
  15677. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i$3 ) !== undefined ) {
  15678. geometry.deleteAttribute( 'morphTarget' + i$3 );
  15679. }
  15680. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i$3 ) !== undefined ) {
  15681. geometry.deleteAttribute( 'morphNormal' + i$3 );
  15682. }
  15683. morphInfluences[ i$3 ] = 0;
  15684. }
  15685. }
  15686. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  15687. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  15688. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  15689. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  15690. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  15691. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  15692. }
  15693. return {
  15694. update: update
  15695. };
  15696. }
  15697. function WebGLObjects( gl, geometries, attributes, info ) {
  15698. var updateMap = new WeakMap();
  15699. function update( object ) {
  15700. var frame = info.render.frame;
  15701. var geometry = object.geometry;
  15702. var buffergeometry = geometries.get( object, geometry );
  15703. // Update once per frame
  15704. if ( updateMap.get( buffergeometry ) !== frame ) {
  15705. if ( geometry.isGeometry ) {
  15706. buffergeometry.updateFromObject( object );
  15707. }
  15708. geometries.update( buffergeometry );
  15709. updateMap.set( buffergeometry, frame );
  15710. }
  15711. if ( object.isInstancedMesh ) {
  15712. attributes.update( object.instanceMatrix, 34962 );
  15713. }
  15714. return buffergeometry;
  15715. }
  15716. function dispose() {
  15717. updateMap = new WeakMap();
  15718. }
  15719. return {
  15720. update: update,
  15721. dispose: dispose
  15722. };
  15723. }
  15724. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  15725. images = images !== undefined ? images : [];
  15726. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  15727. format = format !== undefined ? format : RGBFormat;
  15728. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  15729. this.flipY = false;
  15730. }
  15731. CubeTexture.prototype = Object.create( Texture.prototype );
  15732. CubeTexture.prototype.constructor = CubeTexture;
  15733. CubeTexture.prototype.isCubeTexture = true;
  15734. Object.defineProperty( CubeTexture.prototype, 'images', {
  15735. get: function () {
  15736. return this.image;
  15737. },
  15738. set: function ( value ) {
  15739. this.image = value;
  15740. }
  15741. } );
  15742. function DataTexture2DArray( data, width, height, depth ) {
  15743. Texture.call( this, null );
  15744. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  15745. this.magFilter = NearestFilter;
  15746. this.minFilter = NearestFilter;
  15747. this.wrapR = ClampToEdgeWrapping;
  15748. this.generateMipmaps = false;
  15749. this.flipY = false;
  15750. this.needsUpdate = true;
  15751. }
  15752. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  15753. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  15754. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  15755. function DataTexture3D( data, width, height, depth ) {
  15756. // We're going to add .setXXX() methods for setting properties later.
  15757. // Users can still set in DataTexture3D directly.
  15758. //
  15759. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  15760. // texture.anisotropy = 16;
  15761. //
  15762. // See #14839
  15763. Texture.call( this, null );
  15764. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  15765. this.magFilter = NearestFilter;
  15766. this.minFilter = NearestFilter;
  15767. this.wrapR = ClampToEdgeWrapping;
  15768. this.generateMipmaps = false;
  15769. this.flipY = false;
  15770. this.needsUpdate = true;
  15771. }
  15772. DataTexture3D.prototype = Object.create( Texture.prototype );
  15773. DataTexture3D.prototype.constructor = DataTexture3D;
  15774. DataTexture3D.prototype.isDataTexture3D = true;
  15775. /**
  15776. * Uniforms of a program.
  15777. * Those form a tree structure with a special top-level container for the root,
  15778. * which you get by calling 'new WebGLUniforms( gl, program )'.
  15779. *
  15780. *
  15781. * Properties of inner nodes including the top-level container:
  15782. *
  15783. * .seq - array of nested uniforms
  15784. * .map - nested uniforms by name
  15785. *
  15786. *
  15787. * Methods of all nodes except the top-level container:
  15788. *
  15789. * .setValue( gl, value, [textures] )
  15790. *
  15791. * uploads a uniform value(s)
  15792. * the 'textures' parameter is needed for sampler uniforms
  15793. *
  15794. *
  15795. * Static methods of the top-level container (textures factorizations):
  15796. *
  15797. * .upload( gl, seq, values, textures )
  15798. *
  15799. * sets uniforms in 'seq' to 'values[id].value'
  15800. *
  15801. * .seqWithValue( seq, values ) : filteredSeq
  15802. *
  15803. * filters 'seq' entries with corresponding entry in values
  15804. *
  15805. *
  15806. * Methods of the top-level container (textures factorizations):
  15807. *
  15808. * .setValue( gl, name, value, textures )
  15809. *
  15810. * sets uniform with name 'name' to 'value'
  15811. *
  15812. * .setOptional( gl, obj, prop )
  15813. *
  15814. * like .set for an optional property of the object
  15815. *
  15816. */
  15817. var emptyTexture = new Texture();
  15818. var emptyTexture2dArray = new DataTexture2DArray();
  15819. var emptyTexture3d = new DataTexture3D();
  15820. var emptyCubeTexture = new CubeTexture();
  15821. // --- Utilities ---
  15822. // Array Caches (provide typed arrays for temporary by size)
  15823. var arrayCacheF32 = [];
  15824. var arrayCacheI32 = [];
  15825. // Float32Array caches used for uploading Matrix uniforms
  15826. var mat4array = new Float32Array( 16 );
  15827. var mat3array = new Float32Array( 9 );
  15828. var mat2array = new Float32Array( 4 );
  15829. // Flattening for arrays of vectors and matrices
  15830. function flatten( array, nBlocks, blockSize ) {
  15831. var firstElem = array[ 0 ];
  15832. if ( firstElem <= 0 || firstElem > 0 ) { return array; }
  15833. // unoptimized: ! isNaN( firstElem )
  15834. // see http://jacksondunstan.com/articles/983
  15835. var n = nBlocks * blockSize,
  15836. r = arrayCacheF32[ n ];
  15837. if ( r === undefined ) {
  15838. r = new Float32Array( n );
  15839. arrayCacheF32[ n ] = r;
  15840. }
  15841. if ( nBlocks !== 0 ) {
  15842. firstElem.toArray( r, 0 );
  15843. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  15844. offset += blockSize;
  15845. array[ i ].toArray( r, offset );
  15846. }
  15847. }
  15848. return r;
  15849. }
  15850. function arraysEqual( a, b ) {
  15851. if ( a.length !== b.length ) { return false; }
  15852. for ( var i = 0, l = a.length; i < l; i ++ ) {
  15853. if ( a[ i ] !== b[ i ] ) { return false; }
  15854. }
  15855. return true;
  15856. }
  15857. function copyArray( a, b ) {
  15858. for ( var i = 0, l = b.length; i < l; i ++ ) {
  15859. a[ i ] = b[ i ];
  15860. }
  15861. }
  15862. // Texture unit allocation
  15863. function allocTexUnits( textures, n ) {
  15864. var r = arrayCacheI32[ n ];
  15865. if ( r === undefined ) {
  15866. r = new Int32Array( n );
  15867. arrayCacheI32[ n ] = r;
  15868. }
  15869. for ( var i = 0; i !== n; ++ i ) {
  15870. r[ i ] = textures.allocateTextureUnit();
  15871. }
  15872. return r;
  15873. }
  15874. // --- Setters ---
  15875. // Note: Defining these methods externally, because they come in a bunch
  15876. // and this way their names minify.
  15877. // Single scalar
  15878. function setValueV1f( gl, v ) {
  15879. var cache = this.cache;
  15880. if ( cache[ 0 ] === v ) { return; }
  15881. gl.uniform1f( this.addr, v );
  15882. cache[ 0 ] = v;
  15883. }
  15884. // Single float vector (from flat array or THREE.VectorN)
  15885. function setValueV2f( gl, v ) {
  15886. var cache = this.cache;
  15887. if ( v.x !== undefined ) {
  15888. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  15889. gl.uniform2f( this.addr, v.x, v.y );
  15890. cache[ 0 ] = v.x;
  15891. cache[ 1 ] = v.y;
  15892. }
  15893. } else {
  15894. if ( arraysEqual( cache, v ) ) { return; }
  15895. gl.uniform2fv( this.addr, v );
  15896. copyArray( cache, v );
  15897. }
  15898. }
  15899. function setValueV3f( gl, v ) {
  15900. var cache = this.cache;
  15901. if ( v.x !== undefined ) {
  15902. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  15903. gl.uniform3f( this.addr, v.x, v.y, v.z );
  15904. cache[ 0 ] = v.x;
  15905. cache[ 1 ] = v.y;
  15906. cache[ 2 ] = v.z;
  15907. }
  15908. } else if ( v.r !== undefined ) {
  15909. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  15910. gl.uniform3f( this.addr, v.r, v.g, v.b );
  15911. cache[ 0 ] = v.r;
  15912. cache[ 1 ] = v.g;
  15913. cache[ 2 ] = v.b;
  15914. }
  15915. } else {
  15916. if ( arraysEqual( cache, v ) ) { return; }
  15917. gl.uniform3fv( this.addr, v );
  15918. copyArray( cache, v );
  15919. }
  15920. }
  15921. function setValueV4f( gl, v ) {
  15922. var cache = this.cache;
  15923. if ( v.x !== undefined ) {
  15924. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  15925. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  15926. cache[ 0 ] = v.x;
  15927. cache[ 1 ] = v.y;
  15928. cache[ 2 ] = v.z;
  15929. cache[ 3 ] = v.w;
  15930. }
  15931. } else {
  15932. if ( arraysEqual( cache, v ) ) { return; }
  15933. gl.uniform4fv( this.addr, v );
  15934. copyArray( cache, v );
  15935. }
  15936. }
  15937. // Single matrix (from flat array or MatrixN)
  15938. function setValueM2( gl, v ) {
  15939. var cache = this.cache;
  15940. var elements = v.elements;
  15941. if ( elements === undefined ) {
  15942. if ( arraysEqual( cache, v ) ) { return; }
  15943. gl.uniformMatrix2fv( this.addr, false, v );
  15944. copyArray( cache, v );
  15945. } else {
  15946. if ( arraysEqual( cache, elements ) ) { return; }
  15947. mat2array.set( elements );
  15948. gl.uniformMatrix2fv( this.addr, false, mat2array );
  15949. copyArray( cache, elements );
  15950. }
  15951. }
  15952. function setValueM3( gl, v ) {
  15953. var cache = this.cache;
  15954. var elements = v.elements;
  15955. if ( elements === undefined ) {
  15956. if ( arraysEqual( cache, v ) ) { return; }
  15957. gl.uniformMatrix3fv( this.addr, false, v );
  15958. copyArray( cache, v );
  15959. } else {
  15960. if ( arraysEqual( cache, elements ) ) { return; }
  15961. mat3array.set( elements );
  15962. gl.uniformMatrix3fv( this.addr, false, mat3array );
  15963. copyArray( cache, elements );
  15964. }
  15965. }
  15966. function setValueM4( gl, v ) {
  15967. var cache = this.cache;
  15968. var elements = v.elements;
  15969. if ( elements === undefined ) {
  15970. if ( arraysEqual( cache, v ) ) { return; }
  15971. gl.uniformMatrix4fv( this.addr, false, v );
  15972. copyArray( cache, v );
  15973. } else {
  15974. if ( arraysEqual( cache, elements ) ) { return; }
  15975. mat4array.set( elements );
  15976. gl.uniformMatrix4fv( this.addr, false, mat4array );
  15977. copyArray( cache, elements );
  15978. }
  15979. }
  15980. // Single texture (2D / Cube)
  15981. function setValueT1( gl, v, textures ) {
  15982. var cache = this.cache;
  15983. var unit = textures.allocateTextureUnit();
  15984. if ( cache[ 0 ] !== unit ) {
  15985. gl.uniform1i( this.addr, unit );
  15986. cache[ 0 ] = unit;
  15987. }
  15988. textures.safeSetTexture2D( v || emptyTexture, unit );
  15989. }
  15990. function setValueT2DArray1( gl, v, textures ) {
  15991. var cache = this.cache;
  15992. var unit = textures.allocateTextureUnit();
  15993. if ( cache[ 0 ] !== unit ) {
  15994. gl.uniform1i( this.addr, unit );
  15995. cache[ 0 ] = unit;
  15996. }
  15997. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  15998. }
  15999. function setValueT3D1( gl, v, textures ) {
  16000. var cache = this.cache;
  16001. var unit = textures.allocateTextureUnit();
  16002. if ( cache[ 0 ] !== unit ) {
  16003. gl.uniform1i( this.addr, unit );
  16004. cache[ 0 ] = unit;
  16005. }
  16006. textures.setTexture3D( v || emptyTexture3d, unit );
  16007. }
  16008. function setValueT6( gl, v, textures ) {
  16009. var cache = this.cache;
  16010. var unit = textures.allocateTextureUnit();
  16011. if ( cache[ 0 ] !== unit ) {
  16012. gl.uniform1i( this.addr, unit );
  16013. cache[ 0 ] = unit;
  16014. }
  16015. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  16016. }
  16017. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16018. function setValueV1i( gl, v ) {
  16019. var cache = this.cache;
  16020. if ( cache[ 0 ] === v ) { return; }
  16021. gl.uniform1i( this.addr, v );
  16022. cache[ 0 ] = v;
  16023. }
  16024. function setValueV2i( gl, v ) {
  16025. var cache = this.cache;
  16026. if ( arraysEqual( cache, v ) ) { return; }
  16027. gl.uniform2iv( this.addr, v );
  16028. copyArray( cache, v );
  16029. }
  16030. function setValueV3i( gl, v ) {
  16031. var cache = this.cache;
  16032. if ( arraysEqual( cache, v ) ) { return; }
  16033. gl.uniform3iv( this.addr, v );
  16034. copyArray( cache, v );
  16035. }
  16036. function setValueV4i( gl, v ) {
  16037. var cache = this.cache;
  16038. if ( arraysEqual( cache, v ) ) { return; }
  16039. gl.uniform4iv( this.addr, v );
  16040. copyArray( cache, v );
  16041. }
  16042. // uint
  16043. function setValueV1ui( gl, v ) {
  16044. var cache = this.cache;
  16045. if ( cache[ 0 ] === v ) { return; }
  16046. gl.uniform1ui( this.addr, v );
  16047. cache[ 0 ] = v;
  16048. }
  16049. // Helper to pick the right setter for the singular case
  16050. function getSingularSetter( type ) {
  16051. switch ( type ) {
  16052. case 0x1406: return setValueV1f; // FLOAT
  16053. case 0x8b50: return setValueV2f; // _VEC2
  16054. case 0x8b51: return setValueV3f; // _VEC3
  16055. case 0x8b52: return setValueV4f; // _VEC4
  16056. case 0x8b5a: return setValueM2; // _MAT2
  16057. case 0x8b5b: return setValueM3; // _MAT3
  16058. case 0x8b5c: return setValueM4; // _MAT4
  16059. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  16060. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  16061. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  16062. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  16063. case 0x1405: return setValueV1ui; // UINT
  16064. case 0x8b5e: // SAMPLER_2D
  16065. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16066. case 0x8dca: // INT_SAMPLER_2D
  16067. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16068. case 0x8b62: // SAMPLER_2D_SHADOW
  16069. return setValueT1;
  16070. case 0x8b5f: // SAMPLER_3D
  16071. case 0x8dcb: // INT_SAMPLER_3D
  16072. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  16073. return setValueT3D1;
  16074. case 0x8b60: // SAMPLER_CUBE
  16075. case 0x8dcc: // INT_SAMPLER_CUBE
  16076. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16077. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  16078. return setValueT6;
  16079. case 0x8dc1: // SAMPLER_2D_ARRAY
  16080. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  16081. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  16082. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  16083. return setValueT2DArray1;
  16084. }
  16085. }
  16086. // Array of scalars
  16087. function setValueV1fArray( gl, v ) {
  16088. gl.uniform1fv( this.addr, v );
  16089. }
  16090. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16091. function setValueV1iArray( gl, v ) {
  16092. gl.uniform1iv( this.addr, v );
  16093. }
  16094. function setValueV2iArray( gl, v ) {
  16095. gl.uniform2iv( this.addr, v );
  16096. }
  16097. function setValueV3iArray( gl, v ) {
  16098. gl.uniform3iv( this.addr, v );
  16099. }
  16100. function setValueV4iArray( gl, v ) {
  16101. gl.uniform4iv( this.addr, v );
  16102. }
  16103. // Array of vectors (flat or from THREE classes)
  16104. function setValueV2fArray( gl, v ) {
  16105. var data = flatten( v, this.size, 2 );
  16106. gl.uniform2fv( this.addr, data );
  16107. }
  16108. function setValueV3fArray( gl, v ) {
  16109. var data = flatten( v, this.size, 3 );
  16110. gl.uniform3fv( this.addr, data );
  16111. }
  16112. function setValueV4fArray( gl, v ) {
  16113. var data = flatten( v, this.size, 4 );
  16114. gl.uniform4fv( this.addr, data );
  16115. }
  16116. // Array of matrices (flat or from THREE clases)
  16117. function setValueM2Array( gl, v ) {
  16118. var data = flatten( v, this.size, 4 );
  16119. gl.uniformMatrix2fv( this.addr, false, data );
  16120. }
  16121. function setValueM3Array( gl, v ) {
  16122. var data = flatten( v, this.size, 9 );
  16123. gl.uniformMatrix3fv( this.addr, false, data );
  16124. }
  16125. function setValueM4Array( gl, v ) {
  16126. var data = flatten( v, this.size, 16 );
  16127. gl.uniformMatrix4fv( this.addr, false, data );
  16128. }
  16129. // Array of textures (2D / Cube)
  16130. function setValueT1Array( gl, v, textures ) {
  16131. var n = v.length;
  16132. var units = allocTexUnits( textures, n );
  16133. gl.uniform1iv( this.addr, units );
  16134. for ( var i = 0; i !== n; ++ i ) {
  16135. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  16136. }
  16137. }
  16138. function setValueT6Array( gl, v, textures ) {
  16139. var n = v.length;
  16140. var units = allocTexUnits( textures, n );
  16141. gl.uniform1iv( this.addr, units );
  16142. for ( var i = 0; i !== n; ++ i ) {
  16143. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  16144. }
  16145. }
  16146. // Helper to pick the right setter for a pure (bottom-level) array
  16147. function getPureArraySetter( type ) {
  16148. switch ( type ) {
  16149. case 0x1406: return setValueV1fArray; // FLOAT
  16150. case 0x8b50: return setValueV2fArray; // _VEC2
  16151. case 0x8b51: return setValueV3fArray; // _VEC3
  16152. case 0x8b52: return setValueV4fArray; // _VEC4
  16153. case 0x8b5a: return setValueM2Array; // _MAT2
  16154. case 0x8b5b: return setValueM3Array; // _MAT3
  16155. case 0x8b5c: return setValueM4Array; // _MAT4
  16156. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  16157. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  16158. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  16159. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  16160. case 0x8b5e: // SAMPLER_2D
  16161. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16162. case 0x8dca: // INT_SAMPLER_2D
  16163. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16164. case 0x8b62: // SAMPLER_2D_SHADOW
  16165. return setValueT1Array;
  16166. case 0x8b60: // SAMPLER_CUBE
  16167. case 0x8dcc: // INT_SAMPLER_CUBE
  16168. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16169. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  16170. return setValueT6Array;
  16171. }
  16172. }
  16173. // --- Uniform Classes ---
  16174. function SingleUniform( id, activeInfo, addr ) {
  16175. this.id = id;
  16176. this.addr = addr;
  16177. this.cache = [];
  16178. this.setValue = getSingularSetter( activeInfo.type );
  16179. // this.path = activeInfo.name; // DEBUG
  16180. }
  16181. function PureArrayUniform( id, activeInfo, addr ) {
  16182. this.id = id;
  16183. this.addr = addr;
  16184. this.cache = [];
  16185. this.size = activeInfo.size;
  16186. this.setValue = getPureArraySetter( activeInfo.type );
  16187. // this.path = activeInfo.name; // DEBUG
  16188. }
  16189. PureArrayUniform.prototype.updateCache = function ( data ) {
  16190. var cache = this.cache;
  16191. if ( data instanceof Float32Array && cache.length !== data.length ) {
  16192. this.cache = new Float32Array( data.length );
  16193. }
  16194. copyArray( cache, data );
  16195. };
  16196. function StructuredUniform( id ) {
  16197. this.id = id;
  16198. this.seq = [];
  16199. this.map = {};
  16200. }
  16201. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  16202. var seq = this.seq;
  16203. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16204. var u = seq[ i ];
  16205. u.setValue( gl, value[ u.id ], textures );
  16206. }
  16207. };
  16208. // --- Top-level ---
  16209. // Parser - builds up the property tree from the path strings
  16210. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  16211. // extracts
  16212. // - the identifier (member name or array index)
  16213. // - followed by an optional right bracket (found when array index)
  16214. // - followed by an optional left bracket or dot (type of subscript)
  16215. //
  16216. // Note: These portions can be read in a non-overlapping fashion and
  16217. // allow straightforward parsing of the hierarchy that WebGL encodes
  16218. // in the uniform names.
  16219. function addUniform( container, uniformObject ) {
  16220. container.seq.push( uniformObject );
  16221. container.map[ uniformObject.id ] = uniformObject;
  16222. }
  16223. function parseUniform( activeInfo, addr, container ) {
  16224. var path = activeInfo.name,
  16225. pathLength = path.length;
  16226. // reset RegExp object, because of the early exit of a previous run
  16227. RePathPart.lastIndex = 0;
  16228. while ( true ) {
  16229. var match = RePathPart.exec( path ),
  16230. matchEnd = RePathPart.lastIndex;
  16231. var id = match[ 1 ],
  16232. idIsIndex = match[ 2 ] === ']',
  16233. subscript = match[ 3 ];
  16234. if ( idIsIndex ) { id = id | 0; } // convert to integer
  16235. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  16236. // bare name or "pure" bottom-level array "[0]" suffix
  16237. addUniform( container, subscript === undefined ?
  16238. new SingleUniform( id, activeInfo, addr ) :
  16239. new PureArrayUniform( id, activeInfo, addr ) );
  16240. break;
  16241. } else {
  16242. // step into inner node / create it in case it doesn't exist
  16243. var map = container.map;
  16244. var next = map[ id ];
  16245. if ( next === undefined ) {
  16246. next = new StructuredUniform( id );
  16247. addUniform( container, next );
  16248. }
  16249. container = next;
  16250. }
  16251. }
  16252. }
  16253. // Root Container
  16254. function WebGLUniforms( gl, program ) {
  16255. this.seq = [];
  16256. this.map = {};
  16257. var n = gl.getProgramParameter( program, 35718 );
  16258. for ( var i = 0; i < n; ++ i ) {
  16259. var info = gl.getActiveUniform( program, i ),
  16260. addr = gl.getUniformLocation( program, info.name );
  16261. parseUniform( info, addr, this );
  16262. }
  16263. }
  16264. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  16265. var u = this.map[ name ];
  16266. if ( u !== undefined ) { u.setValue( gl, value, textures ); }
  16267. };
  16268. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  16269. var v = object[ name ];
  16270. if ( v !== undefined ) { this.setValue( gl, name, v ); }
  16271. };
  16272. // Static interface
  16273. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  16274. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16275. var u = seq[ i ],
  16276. v = values[ u.id ];
  16277. if ( v.needsUpdate !== false ) {
  16278. // note: always updating when .needsUpdate is undefined
  16279. u.setValue( gl, v.value, textures );
  16280. }
  16281. }
  16282. };
  16283. WebGLUniforms.seqWithValue = function ( seq, values ) {
  16284. var r = [];
  16285. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16286. var u = seq[ i ];
  16287. if ( u.id in values ) { r.push( u ); }
  16288. }
  16289. return r;
  16290. };
  16291. function WebGLShader( gl, type, string ) {
  16292. var shader = gl.createShader( type );
  16293. gl.shaderSource( shader, string );
  16294. gl.compileShader( shader );
  16295. return shader;
  16296. }
  16297. var programIdCount = 0;
  16298. function addLineNumbers( string ) {
  16299. var lines = string.split( '\n' );
  16300. for ( var i = 0; i < lines.length; i ++ ) {
  16301. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16302. }
  16303. return lines.join( '\n' );
  16304. }
  16305. function getEncodingComponents( encoding ) {
  16306. switch ( encoding ) {
  16307. case LinearEncoding:
  16308. return [ 'Linear', '( value )' ];
  16309. case sRGBEncoding:
  16310. return [ 'sRGB', '( value )' ];
  16311. case RGBEEncoding:
  16312. return [ 'RGBE', '( value )' ];
  16313. case RGBM7Encoding:
  16314. return [ 'RGBM', '( value, 7.0 )' ];
  16315. case RGBM16Encoding:
  16316. return [ 'RGBM', '( value, 16.0 )' ];
  16317. case RGBDEncoding:
  16318. return [ 'RGBD', '( value, 256.0 )' ];
  16319. case GammaEncoding:
  16320. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  16321. case LogLuvEncoding:
  16322. return [ 'LogLuv', '( value )' ];
  16323. default:
  16324. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  16325. return [ 'Linear', '( value )' ];
  16326. }
  16327. }
  16328. function getShaderErrors( gl, shader, type ) {
  16329. var status = gl.getShaderParameter( shader, 35713 );
  16330. var log = gl.getShaderInfoLog( shader ).trim();
  16331. if ( status && log === '' ) { return ''; }
  16332. // --enable-privileged-webgl-extension
  16333. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16334. var source = gl.getShaderSource( shader );
  16335. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  16336. }
  16337. function getTexelDecodingFunction( functionName, encoding ) {
  16338. var components = getEncodingComponents( encoding );
  16339. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  16340. }
  16341. function getTexelEncodingFunction( functionName, encoding ) {
  16342. var components = getEncodingComponents( encoding );
  16343. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  16344. }
  16345. function getToneMappingFunction( functionName, toneMapping ) {
  16346. var toneMappingName;
  16347. switch ( toneMapping ) {
  16348. case LinearToneMapping:
  16349. toneMappingName = 'Linear';
  16350. break;
  16351. case ReinhardToneMapping:
  16352. toneMappingName = 'Reinhard';
  16353. break;
  16354. case CineonToneMapping:
  16355. toneMappingName = 'OptimizedCineon';
  16356. break;
  16357. case ACESFilmicToneMapping:
  16358. toneMappingName = 'ACESFilmic';
  16359. break;
  16360. case CustomToneMapping:
  16361. toneMappingName = 'Custom';
  16362. break;
  16363. default:
  16364. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  16365. toneMappingName = 'Linear';
  16366. }
  16367. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16368. }
  16369. function generateExtensions( parameters ) {
  16370. var chunks = [
  16371. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  16372. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  16373. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  16374. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  16375. ];
  16376. return chunks.filter( filterEmptyLine ).join( '\n' );
  16377. }
  16378. function generateDefines( defines ) {
  16379. var chunks = [];
  16380. for ( var name in defines ) {
  16381. var value = defines[ name ];
  16382. if ( value === false ) { continue; }
  16383. chunks.push( '#define ' + name + ' ' + value );
  16384. }
  16385. return chunks.join( '\n' );
  16386. }
  16387. function fetchAttributeLocations( gl, program ) {
  16388. var attributes = {};
  16389. var n = gl.getProgramParameter( program, 35721 );
  16390. for ( var i = 0; i < n; i ++ ) {
  16391. var info = gl.getActiveAttrib( program, i );
  16392. var name = info.name;
  16393. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16394. attributes[ name ] = gl.getAttribLocation( program, name );
  16395. }
  16396. return attributes;
  16397. }
  16398. function filterEmptyLine( string ) {
  16399. return string !== '';
  16400. }
  16401. function replaceLightNums( string, parameters ) {
  16402. return string
  16403. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  16404. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  16405. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  16406. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  16407. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  16408. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  16409. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  16410. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  16411. }
  16412. function replaceClippingPlaneNums( string, parameters ) {
  16413. return string
  16414. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  16415. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  16416. }
  16417. // Resolve Includes
  16418. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16419. function resolveIncludes( string ) {
  16420. return string.replace( includePattern, includeReplacer );
  16421. }
  16422. function includeReplacer( match, include ) {
  16423. var string = ShaderChunk[ include ];
  16424. if ( string === undefined ) {
  16425. throw new Error( 'Can not resolve #include <' + include + '>' );
  16426. }
  16427. return resolveIncludes( string );
  16428. }
  16429. // Unroll Loops
  16430. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16431. var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
  16432. function unrollLoops( string ) {
  16433. return string
  16434. .replace( unrollLoopPattern, loopReplacer )
  16435. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  16436. }
  16437. function deprecatedLoopReplacer( match, start, end, snippet ) {
  16438. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  16439. return loopReplacer( match, start, end, snippet );
  16440. }
  16441. function loopReplacer( match, start, end, snippet ) {
  16442. var string = '';
  16443. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  16444. string += snippet
  16445. .replace( /\[ i \]/g, '[ ' + i + ' ]' )
  16446. .replace( /UNROLLED_LOOP_INDEX/g, i );
  16447. }
  16448. return string;
  16449. }
  16450. //
  16451. function generatePrecision( parameters ) {
  16452. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  16453. if ( parameters.precision === "highp" ) {
  16454. precisionstring += "\n#define HIGH_PRECISION";
  16455. } else if ( parameters.precision === "mediump" ) {
  16456. precisionstring += "\n#define MEDIUM_PRECISION";
  16457. } else if ( parameters.precision === "lowp" ) {
  16458. precisionstring += "\n#define LOW_PRECISION";
  16459. }
  16460. return precisionstring;
  16461. }
  16462. function generateShadowMapTypeDefine( parameters ) {
  16463. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16464. if ( parameters.shadowMapType === PCFShadowMap ) {
  16465. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16466. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  16467. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16468. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  16469. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16470. }
  16471. return shadowMapTypeDefine;
  16472. }
  16473. function generateEnvMapTypeDefine( parameters ) {
  16474. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16475. if ( parameters.envMap ) {
  16476. switch ( parameters.envMapMode ) {
  16477. case CubeReflectionMapping:
  16478. case CubeRefractionMapping:
  16479. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16480. break;
  16481. case CubeUVReflectionMapping:
  16482. case CubeUVRefractionMapping:
  16483. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16484. break;
  16485. case EquirectangularReflectionMapping:
  16486. case EquirectangularRefractionMapping:
  16487. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  16488. break;
  16489. }
  16490. }
  16491. return envMapTypeDefine;
  16492. }
  16493. function generateEnvMapModeDefine( parameters ) {
  16494. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16495. if ( parameters.envMap ) {
  16496. switch ( parameters.envMapMode ) {
  16497. case CubeRefractionMapping:
  16498. case EquirectangularRefractionMapping:
  16499. case CubeUVRefractionMapping:
  16500. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16501. break;
  16502. }
  16503. }
  16504. return envMapModeDefine;
  16505. }
  16506. function generateEnvMapBlendingDefine( parameters ) {
  16507. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16508. if ( parameters.envMap ) {
  16509. switch ( parameters.combine ) {
  16510. case MultiplyOperation:
  16511. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16512. break;
  16513. case MixOperation:
  16514. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16515. break;
  16516. case AddOperation:
  16517. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16518. break;
  16519. }
  16520. }
  16521. return envMapBlendingDefine;
  16522. }
  16523. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  16524. var gl = renderer.getContext();
  16525. var defines = parameters.defines;
  16526. var vertexShader = parameters.vertexShader;
  16527. var fragmentShader = parameters.fragmentShader;
  16528. var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  16529. var envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  16530. var envMapModeDefine = generateEnvMapModeDefine( parameters );
  16531. var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  16532. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  16533. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  16534. var customDefines = generateDefines( defines );
  16535. var program = gl.createProgram();
  16536. var prefixVertex, prefixFragment;
  16537. if ( parameters.isRawShaderMaterial ) {
  16538. prefixVertex = [
  16539. customDefines
  16540. ].filter( filterEmptyLine ).join( '\n' );
  16541. if ( prefixVertex.length > 0 ) {
  16542. prefixVertex += '\n';
  16543. }
  16544. prefixFragment = [
  16545. customExtensions,
  16546. customDefines
  16547. ].filter( filterEmptyLine ).join( '\n' );
  16548. if ( prefixFragment.length > 0 ) {
  16549. prefixFragment += '\n';
  16550. }
  16551. } else {
  16552. prefixVertex = [
  16553. generatePrecision( parameters ),
  16554. '#define SHADER_NAME ' + parameters.shaderName,
  16555. customDefines,
  16556. parameters.instancing ? '#define USE_INSTANCING' : '',
  16557. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  16558. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16559. '#define MAX_BONES ' + parameters.maxBones,
  16560. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16561. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16562. parameters.map ? '#define USE_MAP' : '',
  16563. parameters.envMap ? '#define USE_ENVMAP' : '',
  16564. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16565. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16566. parameters.aoMap ? '#define USE_AOMAP' : '',
  16567. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16568. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16569. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16570. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16571. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16572. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  16573. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  16574. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16575. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  16576. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16577. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16578. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16579. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16580. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  16581. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16582. parameters.vertexColors ? '#define USE_COLOR' : '',
  16583. parameters.vertexUvs ? '#define USE_UV' : '',
  16584. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  16585. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16586. parameters.skinning ? '#define USE_SKINNING' : '',
  16587. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  16588. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  16589. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  16590. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16591. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16592. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16593. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16594. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  16595. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16596. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16597. 'uniform mat4 modelMatrix;',
  16598. 'uniform mat4 modelViewMatrix;',
  16599. 'uniform mat4 projectionMatrix;',
  16600. 'uniform mat4 viewMatrix;',
  16601. 'uniform mat3 normalMatrix;',
  16602. 'uniform vec3 cameraPosition;',
  16603. 'uniform bool isOrthographic;',
  16604. '#ifdef USE_INSTANCING',
  16605. ' attribute mat4 instanceMatrix;',
  16606. '#endif',
  16607. 'attribute vec3 position;',
  16608. 'attribute vec3 normal;',
  16609. 'attribute vec2 uv;',
  16610. '#ifdef USE_TANGENT',
  16611. ' attribute vec4 tangent;',
  16612. '#endif',
  16613. '#ifdef USE_COLOR',
  16614. ' attribute vec3 color;',
  16615. '#endif',
  16616. '#ifdef USE_MORPHTARGETS',
  16617. ' attribute vec3 morphTarget0;',
  16618. ' attribute vec3 morphTarget1;',
  16619. ' attribute vec3 morphTarget2;',
  16620. ' attribute vec3 morphTarget3;',
  16621. ' #ifdef USE_MORPHNORMALS',
  16622. ' attribute vec3 morphNormal0;',
  16623. ' attribute vec3 morphNormal1;',
  16624. ' attribute vec3 morphNormal2;',
  16625. ' attribute vec3 morphNormal3;',
  16626. ' #else',
  16627. ' attribute vec3 morphTarget4;',
  16628. ' attribute vec3 morphTarget5;',
  16629. ' attribute vec3 morphTarget6;',
  16630. ' attribute vec3 morphTarget7;',
  16631. ' #endif',
  16632. '#endif',
  16633. '#ifdef USE_SKINNING',
  16634. ' attribute vec4 skinIndex;',
  16635. ' attribute vec4 skinWeight;',
  16636. '#endif',
  16637. '\n'
  16638. ].filter( filterEmptyLine ).join( '\n' );
  16639. prefixFragment = [
  16640. customExtensions,
  16641. generatePrecision( parameters ),
  16642. '#define SHADER_NAME ' + parameters.shaderName,
  16643. customDefines,
  16644. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  16645. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16646. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16647. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16648. parameters.map ? '#define USE_MAP' : '',
  16649. parameters.matcap ? '#define USE_MATCAP' : '',
  16650. parameters.envMap ? '#define USE_ENVMAP' : '',
  16651. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  16652. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16653. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  16654. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16655. parameters.aoMap ? '#define USE_AOMAP' : '',
  16656. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16657. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16658. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16659. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16660. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16661. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  16662. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  16663. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16664. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16665. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16666. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16667. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16668. parameters.sheen ? '#define USE_SHEEN' : '',
  16669. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  16670. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16671. parameters.vertexColors ? '#define USE_COLOR' : '',
  16672. parameters.vertexUvs ? '#define USE_UV' : '',
  16673. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  16674. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  16675. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16676. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16677. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16678. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16679. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16680. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  16681. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  16682. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16683. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16684. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  16685. 'uniform mat4 viewMatrix;',
  16686. 'uniform vec3 cameraPosition;',
  16687. 'uniform bool isOrthographic;',
  16688. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  16689. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  16690. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  16691. parameters.dithering ? '#define DITHERING' : '',
  16692. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  16693. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  16694. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  16695. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  16696. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  16697. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  16698. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  16699. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  16700. '\n'
  16701. ].filter( filterEmptyLine ).join( '\n' );
  16702. }
  16703. vertexShader = resolveIncludes( vertexShader );
  16704. vertexShader = replaceLightNums( vertexShader, parameters );
  16705. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  16706. fragmentShader = resolveIncludes( fragmentShader );
  16707. fragmentShader = replaceLightNums( fragmentShader, parameters );
  16708. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  16709. vertexShader = unrollLoops( vertexShader );
  16710. fragmentShader = unrollLoops( fragmentShader );
  16711. if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) {
  16712. // GLSL 3.0 conversion
  16713. prefixVertex = [
  16714. '#version 300 es\n',
  16715. '#define attribute in',
  16716. '#define varying out',
  16717. '#define texture2D texture'
  16718. ].join( '\n' ) + '\n' + prefixVertex;
  16719. prefixFragment = [
  16720. '#version 300 es\n',
  16721. '#define varying in',
  16722. 'out highp vec4 pc_fragColor;',
  16723. '#define gl_FragColor pc_fragColor',
  16724. '#define gl_FragDepthEXT gl_FragDepth',
  16725. '#define texture2D texture',
  16726. '#define textureCube texture',
  16727. '#define texture2DProj textureProj',
  16728. '#define texture2DLodEXT textureLod',
  16729. '#define texture2DProjLodEXT textureProjLod',
  16730. '#define textureCubeLodEXT textureLod',
  16731. '#define texture2DGradEXT textureGrad',
  16732. '#define texture2DProjGradEXT textureProjGrad',
  16733. '#define textureCubeGradEXT textureGrad'
  16734. ].join( '\n' ) + '\n' + prefixFragment;
  16735. }
  16736. var vertexGlsl = prefixVertex + vertexShader;
  16737. var fragmentGlsl = prefixFragment + fragmentShader;
  16738. // console.log( '*VERTEX*', vertexGlsl );
  16739. // console.log( '*FRAGMENT*', fragmentGlsl );
  16740. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  16741. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  16742. gl.attachShader( program, glVertexShader );
  16743. gl.attachShader( program, glFragmentShader );
  16744. // Force a particular attribute to index 0.
  16745. if ( parameters.index0AttributeName !== undefined ) {
  16746. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  16747. } else if ( parameters.morphTargets === true ) {
  16748. // programs with morphTargets displace position out of attribute 0
  16749. gl.bindAttribLocation( program, 0, 'position' );
  16750. }
  16751. gl.linkProgram( program );
  16752. // check for link errors
  16753. if ( renderer.debug.checkShaderErrors ) {
  16754. var programLog = gl.getProgramInfoLog( program ).trim();
  16755. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  16756. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  16757. var runnable = true;
  16758. var haveDiagnostics = true;
  16759. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  16760. runnable = false;
  16761. var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  16762. var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  16763. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  16764. } else if ( programLog !== '' ) {
  16765. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  16766. } else if ( vertexLog === '' || fragmentLog === '' ) {
  16767. haveDiagnostics = false;
  16768. }
  16769. if ( haveDiagnostics ) {
  16770. this.diagnostics = {
  16771. runnable: runnable,
  16772. programLog: programLog,
  16773. vertexShader: {
  16774. log: vertexLog,
  16775. prefix: prefixVertex
  16776. },
  16777. fragmentShader: {
  16778. log: fragmentLog,
  16779. prefix: prefixFragment
  16780. }
  16781. };
  16782. }
  16783. }
  16784. // Clean up
  16785. // Crashes in iOS9 and iOS10. #18402
  16786. // gl.detachShader( program, glVertexShader );
  16787. // gl.detachShader( program, glFragmentShader );
  16788. gl.deleteShader( glVertexShader );
  16789. gl.deleteShader( glFragmentShader );
  16790. // set up caching for uniform locations
  16791. var cachedUniforms;
  16792. this.getUniforms = function () {
  16793. if ( cachedUniforms === undefined ) {
  16794. cachedUniforms = new WebGLUniforms( gl, program );
  16795. }
  16796. return cachedUniforms;
  16797. };
  16798. // set up caching for attribute locations
  16799. var cachedAttributes;
  16800. this.getAttributes = function () {
  16801. if ( cachedAttributes === undefined ) {
  16802. cachedAttributes = fetchAttributeLocations( gl, program );
  16803. }
  16804. return cachedAttributes;
  16805. };
  16806. // free resource
  16807. this.destroy = function () {
  16808. bindingStates.releaseStatesOfProgram( this );
  16809. gl.deleteProgram( program );
  16810. this.program = undefined;
  16811. };
  16812. //
  16813. this.name = parameters.shaderName;
  16814. this.id = programIdCount ++;
  16815. this.cacheKey = cacheKey;
  16816. this.usedTimes = 1;
  16817. this.program = program;
  16818. this.vertexShader = glVertexShader;
  16819. this.fragmentShader = glFragmentShader;
  16820. return this;
  16821. }
  16822. function WebGLPrograms( renderer, extensions, capabilities, bindingStates ) {
  16823. var programs = [];
  16824. var isWebGL2 = capabilities.isWebGL2;
  16825. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  16826. var floatVertexTextures = capabilities.floatVertexTextures;
  16827. var maxVertexUniforms = capabilities.maxVertexUniforms;
  16828. var vertexTextures = capabilities.vertexTextures;
  16829. var precision = capabilities.precision;
  16830. var shaderIDs = {
  16831. MeshDepthMaterial: 'depth',
  16832. MeshDistanceMaterial: 'distanceRGBA',
  16833. MeshNormalMaterial: 'normal',
  16834. MeshBasicMaterial: 'basic',
  16835. MeshLambertMaterial: 'lambert',
  16836. MeshPhongMaterial: 'phong',
  16837. MeshToonMaterial: 'toon',
  16838. MeshStandardMaterial: 'physical',
  16839. MeshPhysicalMaterial: 'physical',
  16840. MeshMatcapMaterial: 'matcap',
  16841. LineBasicMaterial: 'basic',
  16842. LineDashedMaterial: 'dashed',
  16843. PointsMaterial: 'points',
  16844. ShadowMaterial: 'shadow',
  16845. SpriteMaterial: 'sprite'
  16846. };
  16847. var parameterNames = [
  16848. "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing",
  16849. "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
  16850. "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap",
  16851. "roughnessMap", "metalnessMap", "gradientMap",
  16852. "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
  16853. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  16854. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  16855. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  16856. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  16857. "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
  16858. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  16859. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
  16860. "sheen", "transmissionMap"
  16861. ];
  16862. function allocateBones( object ) {
  16863. var skeleton = object.skeleton;
  16864. var bones = skeleton.bones;
  16865. if ( floatVertexTextures ) {
  16866. return 1024;
  16867. } else {
  16868. // default for when object is not specified
  16869. // ( for example when prebuilding shader to be used with multiple objects )
  16870. //
  16871. // - leave some extra space for other uniforms
  16872. // - limit here is ANGLE's 254 max uniform vectors
  16873. // (up to 54 should be safe)
  16874. var nVertexUniforms = maxVertexUniforms;
  16875. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  16876. var maxBones = Math.min( nVertexMatrices, bones.length );
  16877. if ( maxBones < bones.length ) {
  16878. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  16879. return 0;
  16880. }
  16881. return maxBones;
  16882. }
  16883. }
  16884. function getTextureEncodingFromMap( map ) {
  16885. var encoding;
  16886. if ( ! map ) {
  16887. encoding = LinearEncoding;
  16888. } else if ( map.isTexture ) {
  16889. encoding = map.encoding;
  16890. } else if ( map.isWebGLRenderTarget ) {
  16891. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  16892. encoding = map.texture.encoding;
  16893. }
  16894. return encoding;
  16895. }
  16896. function getParameters( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) {
  16897. var fog = scene.fog;
  16898. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  16899. var envMap = material.envMap || environment;
  16900. var shaderID = shaderIDs[ material.type ];
  16901. // heuristics to create shader parameters according to lights in the scene
  16902. // (not to blow over maxLights budget)
  16903. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  16904. if ( material.precision !== null ) {
  16905. precision = capabilities.getMaxPrecision( material.precision );
  16906. if ( precision !== material.precision ) {
  16907. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  16908. }
  16909. }
  16910. var vertexShader, fragmentShader;
  16911. if ( shaderID ) {
  16912. var shader = ShaderLib[ shaderID ];
  16913. vertexShader = shader.vertexShader;
  16914. fragmentShader = shader.fragmentShader;
  16915. } else {
  16916. vertexShader = material.vertexShader;
  16917. fragmentShader = material.fragmentShader;
  16918. }
  16919. var currentRenderTarget = renderer.getRenderTarget();
  16920. var parameters = {
  16921. isWebGL2: isWebGL2,
  16922. shaderID: shaderID,
  16923. shaderName: material.type,
  16924. vertexShader: vertexShader,
  16925. fragmentShader: fragmentShader,
  16926. defines: material.defines,
  16927. isRawShaderMaterial: material.isRawShaderMaterial,
  16928. isShaderMaterial: material.isShaderMaterial,
  16929. precision: precision,
  16930. instancing: object.isInstancedMesh === true,
  16931. supportsVertexTextures: vertexTextures,
  16932. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  16933. map: !! material.map,
  16934. mapEncoding: getTextureEncodingFromMap( material.map ),
  16935. matcap: !! material.matcap,
  16936. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  16937. envMap: !! envMap,
  16938. envMapMode: envMap && envMap.mapping,
  16939. envMapEncoding: getTextureEncodingFromMap( envMap ),
  16940. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  16941. lightMap: !! material.lightMap,
  16942. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  16943. aoMap: !! material.aoMap,
  16944. emissiveMap: !! material.emissiveMap,
  16945. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  16946. bumpMap: !! material.bumpMap,
  16947. normalMap: !! material.normalMap,
  16948. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  16949. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  16950. clearcoatMap: !! material.clearcoatMap,
  16951. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  16952. clearcoatNormalMap: !! material.clearcoatNormalMap,
  16953. displacementMap: !! material.displacementMap,
  16954. roughnessMap: !! material.roughnessMap,
  16955. metalnessMap: !! material.metalnessMap,
  16956. specularMap: !! material.specularMap,
  16957. alphaMap: !! material.alphaMap,
  16958. gradientMap: !! material.gradientMap,
  16959. sheen: !! material.sheen,
  16960. transmissionMap: !! material.transmissionMap,
  16961. combine: material.combine,
  16962. vertexTangents: ( material.normalMap && material.vertexTangents ),
  16963. vertexColors: material.vertexColors,
  16964. 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,
  16965. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  16966. fog: !! fog,
  16967. useFog: material.fog,
  16968. fogExp2: ( fog && fog.isFogExp2 ),
  16969. flatShading: material.flatShading,
  16970. sizeAttenuation: material.sizeAttenuation,
  16971. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16972. skinning: material.skinning && maxBones > 0,
  16973. maxBones: maxBones,
  16974. useVertexTexture: floatVertexTextures,
  16975. morphTargets: material.morphTargets,
  16976. morphNormals: material.morphNormals,
  16977. maxMorphTargets: renderer.maxMorphTargets,
  16978. maxMorphNormals: renderer.maxMorphNormals,
  16979. numDirLights: lights.directional.length,
  16980. numPointLights: lights.point.length,
  16981. numSpotLights: lights.spot.length,
  16982. numRectAreaLights: lights.rectArea.length,
  16983. numHemiLights: lights.hemi.length,
  16984. numDirLightShadows: lights.directionalShadowMap.length,
  16985. numPointLightShadows: lights.pointShadowMap.length,
  16986. numSpotLightShadows: lights.spotShadowMap.length,
  16987. numClippingPlanes: nClipPlanes,
  16988. numClipIntersection: nClipIntersection,
  16989. dithering: material.dithering,
  16990. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  16991. shadowMapType: renderer.shadowMap.type,
  16992. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  16993. physicallyCorrectLights: renderer.physicallyCorrectLights,
  16994. premultipliedAlpha: material.premultipliedAlpha,
  16995. alphaTest: material.alphaTest,
  16996. doubleSided: material.side === DoubleSide,
  16997. flipSided: material.side === BackSide,
  16998. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  16999. index0AttributeName: material.index0AttributeName,
  17000. extensionDerivatives: material.extensions && material.extensions.derivatives,
  17001. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  17002. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  17003. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  17004. rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null,
  17005. rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null,
  17006. rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null,
  17007. customProgramCacheKey: material.customProgramCacheKey()
  17008. };
  17009. return parameters;
  17010. }
  17011. function getProgramCacheKey( parameters ) {
  17012. var array = [];
  17013. if ( parameters.shaderID ) {
  17014. array.push( parameters.shaderID );
  17015. } else {
  17016. array.push( parameters.fragmentShader );
  17017. array.push( parameters.vertexShader );
  17018. }
  17019. if ( parameters.defines !== undefined ) {
  17020. for ( var name in parameters.defines ) {
  17021. array.push( name );
  17022. array.push( parameters.defines[ name ] );
  17023. }
  17024. }
  17025. if ( parameters.isRawShaderMaterial === undefined ) {
  17026. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17027. array.push( parameters[ parameterNames[ i ] ] );
  17028. }
  17029. array.push( renderer.outputEncoding );
  17030. array.push( renderer.gammaFactor );
  17031. }
  17032. array.push( parameters.customProgramCacheKey );
  17033. return array.join();
  17034. }
  17035. function getUniforms( material ) {
  17036. var shaderID = shaderIDs[ material.type ];
  17037. var uniforms;
  17038. if ( shaderID ) {
  17039. var shader = ShaderLib[ shaderID ];
  17040. uniforms = UniformsUtils.clone( shader.uniforms );
  17041. } else {
  17042. uniforms = material.uniforms;
  17043. }
  17044. return uniforms;
  17045. }
  17046. function acquireProgram( parameters, cacheKey ) {
  17047. var program;
  17048. // Check if code has been already compiled
  17049. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17050. var preexistingProgram = programs[ p ];
  17051. if ( preexistingProgram.cacheKey === cacheKey ) {
  17052. program = preexistingProgram;
  17053. ++ program.usedTimes;
  17054. break;
  17055. }
  17056. }
  17057. if ( program === undefined ) {
  17058. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  17059. programs.push( program );
  17060. }
  17061. return program;
  17062. }
  17063. function releaseProgram( program ) {
  17064. if ( -- program.usedTimes === 0 ) {
  17065. // Remove from unordered set
  17066. var i = programs.indexOf( program );
  17067. programs[ i ] = programs[ programs.length - 1 ];
  17068. programs.pop();
  17069. // Free WebGL resources
  17070. program.destroy();
  17071. }
  17072. }
  17073. return {
  17074. getParameters: getParameters,
  17075. getProgramCacheKey: getProgramCacheKey,
  17076. getUniforms: getUniforms,
  17077. acquireProgram: acquireProgram,
  17078. releaseProgram: releaseProgram,
  17079. // Exposed for resource monitoring & error feedback via renderer.info:
  17080. programs: programs
  17081. };
  17082. }
  17083. function WebGLProperties() {
  17084. var properties = new WeakMap();
  17085. function get( object ) {
  17086. var map = properties.get( object );
  17087. if ( map === undefined ) {
  17088. map = {};
  17089. properties.set( object, map );
  17090. }
  17091. return map;
  17092. }
  17093. function remove( object ) {
  17094. properties.delete( object );
  17095. }
  17096. function update( object, key, value ) {
  17097. properties.get( object )[ key ] = value;
  17098. }
  17099. function dispose() {
  17100. properties = new WeakMap();
  17101. }
  17102. return {
  17103. get: get,
  17104. remove: remove,
  17105. update: update,
  17106. dispose: dispose
  17107. };
  17108. }
  17109. function painterSortStable( a, b ) {
  17110. if ( a.groupOrder !== b.groupOrder ) {
  17111. return a.groupOrder - b.groupOrder;
  17112. } else if ( a.renderOrder !== b.renderOrder ) {
  17113. return a.renderOrder - b.renderOrder;
  17114. } else if ( a.program !== b.program ) {
  17115. return a.program.id - b.program.id;
  17116. } else if ( a.material.id !== b.material.id ) {
  17117. return a.material.id - b.material.id;
  17118. } else if ( a.z !== b.z ) {
  17119. return a.z - b.z;
  17120. } else {
  17121. return a.id - b.id;
  17122. }
  17123. }
  17124. function reversePainterSortStable( a, b ) {
  17125. if ( a.groupOrder !== b.groupOrder ) {
  17126. return a.groupOrder - b.groupOrder;
  17127. } else if ( a.renderOrder !== b.renderOrder ) {
  17128. return a.renderOrder - b.renderOrder;
  17129. } else if ( a.z !== b.z ) {
  17130. return b.z - a.z;
  17131. } else {
  17132. return a.id - b.id;
  17133. }
  17134. }
  17135. function WebGLRenderList( properties ) {
  17136. var renderItems = [];
  17137. var renderItemsIndex = 0;
  17138. var opaque = [];
  17139. var transparent = [];
  17140. var defaultProgram = { id: - 1 };
  17141. function init() {
  17142. renderItemsIndex = 0;
  17143. opaque.length = 0;
  17144. transparent.length = 0;
  17145. }
  17146. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  17147. var renderItem = renderItems[ renderItemsIndex ];
  17148. var materialProperties = properties.get( material );
  17149. if ( renderItem === undefined ) {
  17150. renderItem = {
  17151. id: object.id,
  17152. object: object,
  17153. geometry: geometry,
  17154. material: material,
  17155. program: materialProperties.program || defaultProgram,
  17156. groupOrder: groupOrder,
  17157. renderOrder: object.renderOrder,
  17158. z: z,
  17159. group: group
  17160. };
  17161. renderItems[ renderItemsIndex ] = renderItem;
  17162. } else {
  17163. renderItem.id = object.id;
  17164. renderItem.object = object;
  17165. renderItem.geometry = geometry;
  17166. renderItem.material = material;
  17167. renderItem.program = materialProperties.program || defaultProgram;
  17168. renderItem.groupOrder = groupOrder;
  17169. renderItem.renderOrder = object.renderOrder;
  17170. renderItem.z = z;
  17171. renderItem.group = group;
  17172. }
  17173. renderItemsIndex ++;
  17174. return renderItem;
  17175. }
  17176. function push( object, geometry, material, groupOrder, z, group ) {
  17177. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  17178. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  17179. }
  17180. function unshift( object, geometry, material, groupOrder, z, group ) {
  17181. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  17182. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  17183. }
  17184. function sort( customOpaqueSort, customTransparentSort ) {
  17185. if ( opaque.length > 1 ) { opaque.sort( customOpaqueSort || painterSortStable ); }
  17186. if ( transparent.length > 1 ) { transparent.sort( customTransparentSort || reversePainterSortStable ); }
  17187. }
  17188. function finish() {
  17189. // Clear references from inactive renderItems in the list
  17190. for ( var i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  17191. var renderItem = renderItems[ i ];
  17192. if ( renderItem.id === null ) { break; }
  17193. renderItem.id = null;
  17194. renderItem.object = null;
  17195. renderItem.geometry = null;
  17196. renderItem.material = null;
  17197. renderItem.program = null;
  17198. renderItem.group = null;
  17199. }
  17200. }
  17201. return {
  17202. opaque: opaque,
  17203. transparent: transparent,
  17204. init: init,
  17205. push: push,
  17206. unshift: unshift,
  17207. finish: finish,
  17208. sort: sort
  17209. };
  17210. }
  17211. function WebGLRenderLists( properties ) {
  17212. var lists = new WeakMap();
  17213. function onSceneDispose( event ) {
  17214. var scene = event.target;
  17215. scene.removeEventListener( 'dispose', onSceneDispose );
  17216. lists.delete( scene );
  17217. }
  17218. function get( scene, camera ) {
  17219. var cameras = lists.get( scene );
  17220. var list;
  17221. if ( cameras === undefined ) {
  17222. list = new WebGLRenderList( properties );
  17223. lists.set( scene, new WeakMap() );
  17224. lists.get( scene ).set( camera, list );
  17225. scene.addEventListener( 'dispose', onSceneDispose );
  17226. } else {
  17227. list = cameras.get( camera );
  17228. if ( list === undefined ) {
  17229. list = new WebGLRenderList( properties );
  17230. cameras.set( camera, list );
  17231. }
  17232. }
  17233. return list;
  17234. }
  17235. function dispose() {
  17236. lists = new WeakMap();
  17237. }
  17238. return {
  17239. get: get,
  17240. dispose: dispose
  17241. };
  17242. }
  17243. function UniformsCache() {
  17244. var lights = {};
  17245. return {
  17246. get: function ( light ) {
  17247. if ( lights[ light.id ] !== undefined ) {
  17248. return lights[ light.id ];
  17249. }
  17250. var uniforms;
  17251. switch ( light.type ) {
  17252. case 'DirectionalLight':
  17253. uniforms = {
  17254. direction: new Vector3(),
  17255. color: new Color()
  17256. };
  17257. break;
  17258. case 'SpotLight':
  17259. uniforms = {
  17260. position: new Vector3(),
  17261. direction: new Vector3(),
  17262. color: new Color(),
  17263. distance: 0,
  17264. coneCos: 0,
  17265. penumbraCos: 0,
  17266. decay: 0
  17267. };
  17268. break;
  17269. case 'PointLight':
  17270. uniforms = {
  17271. position: new Vector3(),
  17272. color: new Color(),
  17273. distance: 0,
  17274. decay: 0
  17275. };
  17276. break;
  17277. case 'HemisphereLight':
  17278. uniforms = {
  17279. direction: new Vector3(),
  17280. skyColor: new Color(),
  17281. groundColor: new Color()
  17282. };
  17283. break;
  17284. case 'RectAreaLight':
  17285. uniforms = {
  17286. color: new Color(),
  17287. position: new Vector3(),
  17288. halfWidth: new Vector3(),
  17289. halfHeight: new Vector3()
  17290. };
  17291. break;
  17292. }
  17293. lights[ light.id ] = uniforms;
  17294. return uniforms;
  17295. }
  17296. };
  17297. }
  17298. function ShadowUniformsCache() {
  17299. var lights = {};
  17300. return {
  17301. get: function ( light ) {
  17302. if ( lights[ light.id ] !== undefined ) {
  17303. return lights[ light.id ];
  17304. }
  17305. var uniforms;
  17306. switch ( light.type ) {
  17307. case 'DirectionalLight':
  17308. uniforms = {
  17309. shadowBias: 0,
  17310. shadowNormalBias: 0,
  17311. shadowRadius: 1,
  17312. shadowMapSize: new Vector2()
  17313. };
  17314. break;
  17315. case 'SpotLight':
  17316. uniforms = {
  17317. shadowBias: 0,
  17318. shadowNormalBias: 0,
  17319. shadowRadius: 1,
  17320. shadowMapSize: new Vector2()
  17321. };
  17322. break;
  17323. case 'PointLight':
  17324. uniforms = {
  17325. shadowBias: 0,
  17326. shadowNormalBias: 0,
  17327. shadowRadius: 1,
  17328. shadowMapSize: new Vector2(),
  17329. shadowCameraNear: 1,
  17330. shadowCameraFar: 1000
  17331. };
  17332. break;
  17333. // TODO (abelnation): set RectAreaLight shadow uniforms
  17334. }
  17335. lights[ light.id ] = uniforms;
  17336. return uniforms;
  17337. }
  17338. };
  17339. }
  17340. var nextVersion = 0;
  17341. function shadowCastingLightsFirst( lightA, lightB ) {
  17342. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  17343. }
  17344. function WebGLLights() {
  17345. var cache = new UniformsCache();
  17346. var shadowCache = ShadowUniformsCache();
  17347. var state = {
  17348. version: 0,
  17349. hash: {
  17350. directionalLength: - 1,
  17351. pointLength: - 1,
  17352. spotLength: - 1,
  17353. rectAreaLength: - 1,
  17354. hemiLength: - 1,
  17355. numDirectionalShadows: - 1,
  17356. numPointShadows: - 1,
  17357. numSpotShadows: - 1
  17358. },
  17359. ambient: [ 0, 0, 0 ],
  17360. probe: [],
  17361. directional: [],
  17362. directionalShadow: [],
  17363. directionalShadowMap: [],
  17364. directionalShadowMatrix: [],
  17365. spot: [],
  17366. spotShadow: [],
  17367. spotShadowMap: [],
  17368. spotShadowMatrix: [],
  17369. rectArea: [],
  17370. point: [],
  17371. pointShadow: [],
  17372. pointShadowMap: [],
  17373. pointShadowMatrix: [],
  17374. hemi: []
  17375. };
  17376. for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); }
  17377. var vector3 = new Vector3();
  17378. var matrix4 = new Matrix4();
  17379. var matrix42 = new Matrix4();
  17380. function setup( lights, shadows, camera ) {
  17381. var r = 0, g = 0, b = 0;
  17382. for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); }
  17383. var directionalLength = 0;
  17384. var pointLength = 0;
  17385. var spotLength = 0;
  17386. var rectAreaLength = 0;
  17387. var hemiLength = 0;
  17388. var numDirectionalShadows = 0;
  17389. var numPointShadows = 0;
  17390. var numSpotShadows = 0;
  17391. var viewMatrix = camera.matrixWorldInverse;
  17392. lights.sort( shadowCastingLightsFirst );
  17393. for ( var i$1 = 0, l = lights.length; i$1 < l; i$1 ++ ) {
  17394. var light = lights[ i$1 ];
  17395. var color = light.color;
  17396. var intensity = light.intensity;
  17397. var distance = light.distance;
  17398. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  17399. if ( light.isAmbientLight ) {
  17400. r += color.r * intensity;
  17401. g += color.g * intensity;
  17402. b += color.b * intensity;
  17403. } else if ( light.isLightProbe ) {
  17404. for ( var j = 0; j < 9; j ++ ) {
  17405. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  17406. }
  17407. } else if ( light.isDirectionalLight ) {
  17408. var uniforms = cache.get( light );
  17409. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17410. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17411. vector3.setFromMatrixPosition( light.target.matrixWorld );
  17412. uniforms.direction.sub( vector3 );
  17413. uniforms.direction.transformDirection( viewMatrix );
  17414. if ( light.castShadow ) {
  17415. var shadow = light.shadow;
  17416. var shadowUniforms = shadowCache.get( light );
  17417. shadowUniforms.shadowBias = shadow.bias;
  17418. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17419. shadowUniforms.shadowRadius = shadow.radius;
  17420. shadowUniforms.shadowMapSize = shadow.mapSize;
  17421. state.directionalShadow[ directionalLength ] = shadowUniforms;
  17422. state.directionalShadowMap[ directionalLength ] = shadowMap;
  17423. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  17424. numDirectionalShadows ++;
  17425. }
  17426. state.directional[ directionalLength ] = uniforms;
  17427. directionalLength ++;
  17428. } else if ( light.isSpotLight ) {
  17429. var uniforms$1 = cache.get( light );
  17430. uniforms$1.position.setFromMatrixPosition( light.matrixWorld );
  17431. uniforms$1.position.applyMatrix4( viewMatrix );
  17432. uniforms$1.color.copy( color ).multiplyScalar( intensity );
  17433. uniforms$1.distance = distance;
  17434. uniforms$1.direction.setFromMatrixPosition( light.matrixWorld );
  17435. vector3.setFromMatrixPosition( light.target.matrixWorld );
  17436. uniforms$1.direction.sub( vector3 );
  17437. uniforms$1.direction.transformDirection( viewMatrix );
  17438. uniforms$1.coneCos = Math.cos( light.angle );
  17439. uniforms$1.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17440. uniforms$1.decay = light.decay;
  17441. if ( light.castShadow ) {
  17442. var shadow$1 = light.shadow;
  17443. var shadowUniforms$1 = shadowCache.get( light );
  17444. shadowUniforms$1.shadowBias = shadow$1.bias;
  17445. shadowUniforms$1.shadowNormalBias = shadow$1.normalBias;
  17446. shadowUniforms$1.shadowRadius = shadow$1.radius;
  17447. shadowUniforms$1.shadowMapSize = shadow$1.mapSize;
  17448. state.spotShadow[ spotLength ] = shadowUniforms$1;
  17449. state.spotShadowMap[ spotLength ] = shadowMap;
  17450. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  17451. numSpotShadows ++;
  17452. }
  17453. state.spot[ spotLength ] = uniforms$1;
  17454. spotLength ++;
  17455. } else if ( light.isRectAreaLight ) {
  17456. var uniforms$2 = cache.get( light );
  17457. // (a) intensity is the total visible light emitted
  17458. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17459. // (b) intensity is the brightness of the light
  17460. uniforms$2.color.copy( color ).multiplyScalar( intensity );
  17461. uniforms$2.position.setFromMatrixPosition( light.matrixWorld );
  17462. uniforms$2.position.applyMatrix4( viewMatrix );
  17463. // extract local rotation of light to derive width/height half vectors
  17464. matrix42.identity();
  17465. matrix4.copy( light.matrixWorld );
  17466. matrix4.premultiply( viewMatrix );
  17467. matrix42.extractRotation( matrix4 );
  17468. uniforms$2.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  17469. uniforms$2.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  17470. uniforms$2.halfWidth.applyMatrix4( matrix42 );
  17471. uniforms$2.halfHeight.applyMatrix4( matrix42 );
  17472. // TODO (abelnation): RectAreaLight distance?
  17473. // uniforms.distance = distance;
  17474. state.rectArea[ rectAreaLength ] = uniforms$2;
  17475. rectAreaLength ++;
  17476. } else if ( light.isPointLight ) {
  17477. var uniforms$3 = cache.get( light );
  17478. uniforms$3.position.setFromMatrixPosition( light.matrixWorld );
  17479. uniforms$3.position.applyMatrix4( viewMatrix );
  17480. uniforms$3.color.copy( light.color ).multiplyScalar( light.intensity );
  17481. uniforms$3.distance = light.distance;
  17482. uniforms$3.decay = light.decay;
  17483. if ( light.castShadow ) {
  17484. var shadow$2 = light.shadow;
  17485. var shadowUniforms$2 = shadowCache.get( light );
  17486. shadowUniforms$2.shadowBias = shadow$2.bias;
  17487. shadowUniforms$2.shadowNormalBias = shadow$2.normalBias;
  17488. shadowUniforms$2.shadowRadius = shadow$2.radius;
  17489. shadowUniforms$2.shadowMapSize = shadow$2.mapSize;
  17490. shadowUniforms$2.shadowCameraNear = shadow$2.camera.near;
  17491. shadowUniforms$2.shadowCameraFar = shadow$2.camera.far;
  17492. state.pointShadow[ pointLength ] = shadowUniforms$2;
  17493. state.pointShadowMap[ pointLength ] = shadowMap;
  17494. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  17495. numPointShadows ++;
  17496. }
  17497. state.point[ pointLength ] = uniforms$3;
  17498. pointLength ++;
  17499. } else if ( light.isHemisphereLight ) {
  17500. var uniforms$4 = cache.get( light );
  17501. uniforms$4.direction.setFromMatrixPosition( light.matrixWorld );
  17502. uniforms$4.direction.transformDirection( viewMatrix );
  17503. uniforms$4.direction.normalize();
  17504. uniforms$4.skyColor.copy( light.color ).multiplyScalar( intensity );
  17505. uniforms$4.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17506. state.hemi[ hemiLength ] = uniforms$4;
  17507. hemiLength ++;
  17508. }
  17509. }
  17510. state.ambient[ 0 ] = r;
  17511. state.ambient[ 1 ] = g;
  17512. state.ambient[ 2 ] = b;
  17513. var hash = state.hash;
  17514. if ( hash.directionalLength !== directionalLength ||
  17515. hash.pointLength !== pointLength ||
  17516. hash.spotLength !== spotLength ||
  17517. hash.rectAreaLength !== rectAreaLength ||
  17518. hash.hemiLength !== hemiLength ||
  17519. hash.numDirectionalShadows !== numDirectionalShadows ||
  17520. hash.numPointShadows !== numPointShadows ||
  17521. hash.numSpotShadows !== numSpotShadows ) {
  17522. state.directional.length = directionalLength;
  17523. state.spot.length = spotLength;
  17524. state.rectArea.length = rectAreaLength;
  17525. state.point.length = pointLength;
  17526. state.hemi.length = hemiLength;
  17527. state.directionalShadow.length = numDirectionalShadows;
  17528. state.directionalShadowMap.length = numDirectionalShadows;
  17529. state.pointShadow.length = numPointShadows;
  17530. state.pointShadowMap.length = numPointShadows;
  17531. state.spotShadow.length = numSpotShadows;
  17532. state.spotShadowMap.length = numSpotShadows;
  17533. state.directionalShadowMatrix.length = numDirectionalShadows;
  17534. state.pointShadowMatrix.length = numPointShadows;
  17535. state.spotShadowMatrix.length = numSpotShadows;
  17536. hash.directionalLength = directionalLength;
  17537. hash.pointLength = pointLength;
  17538. hash.spotLength = spotLength;
  17539. hash.rectAreaLength = rectAreaLength;
  17540. hash.hemiLength = hemiLength;
  17541. hash.numDirectionalShadows = numDirectionalShadows;
  17542. hash.numPointShadows = numPointShadows;
  17543. hash.numSpotShadows = numSpotShadows;
  17544. state.version = nextVersion ++;
  17545. }
  17546. }
  17547. return {
  17548. setup: setup,
  17549. state: state
  17550. };
  17551. }
  17552. function WebGLRenderState() {
  17553. var lights = new WebGLLights();
  17554. var lightsArray = [];
  17555. var shadowsArray = [];
  17556. function init() {
  17557. lightsArray.length = 0;
  17558. shadowsArray.length = 0;
  17559. }
  17560. function pushLight( light ) {
  17561. lightsArray.push( light );
  17562. }
  17563. function pushShadow( shadowLight ) {
  17564. shadowsArray.push( shadowLight );
  17565. }
  17566. function setupLights( camera ) {
  17567. lights.setup( lightsArray, shadowsArray, camera );
  17568. }
  17569. var state = {
  17570. lightsArray: lightsArray,
  17571. shadowsArray: shadowsArray,
  17572. lights: lights
  17573. };
  17574. return {
  17575. init: init,
  17576. state: state,
  17577. setupLights: setupLights,
  17578. pushLight: pushLight,
  17579. pushShadow: pushShadow
  17580. };
  17581. }
  17582. function WebGLRenderStates() {
  17583. var renderStates = new WeakMap();
  17584. function onSceneDispose( event ) {
  17585. var scene = event.target;
  17586. scene.removeEventListener( 'dispose', onSceneDispose );
  17587. renderStates.delete( scene );
  17588. }
  17589. function get( scene, camera ) {
  17590. var renderState;
  17591. if ( renderStates.has( scene ) === false ) {
  17592. renderState = new WebGLRenderState();
  17593. renderStates.set( scene, new WeakMap() );
  17594. renderStates.get( scene ).set( camera, renderState );
  17595. scene.addEventListener( 'dispose', onSceneDispose );
  17596. } else {
  17597. if ( renderStates.get( scene ).has( camera ) === false ) {
  17598. renderState = new WebGLRenderState();
  17599. renderStates.get( scene ).set( camera, renderState );
  17600. } else {
  17601. renderState = renderStates.get( scene ).get( camera );
  17602. }
  17603. }
  17604. return renderState;
  17605. }
  17606. function dispose() {
  17607. renderStates = new WeakMap();
  17608. }
  17609. return {
  17610. get: get,
  17611. dispose: dispose
  17612. };
  17613. }
  17614. /**
  17615. * parameters = {
  17616. *
  17617. * opacity: <float>,
  17618. *
  17619. * map: new THREE.Texture( <Image> ),
  17620. *
  17621. * alphaMap: new THREE.Texture( <Image> ),
  17622. *
  17623. * displacementMap: new THREE.Texture( <Image> ),
  17624. * displacementScale: <float>,
  17625. * displacementBias: <float>,
  17626. *
  17627. * wireframe: <boolean>,
  17628. * wireframeLinewidth: <float>
  17629. * }
  17630. */
  17631. function MeshDepthMaterial( parameters ) {
  17632. Material.call( this );
  17633. this.type = 'MeshDepthMaterial';
  17634. this.depthPacking = BasicDepthPacking;
  17635. this.skinning = false;
  17636. this.morphTargets = false;
  17637. this.map = null;
  17638. this.alphaMap = null;
  17639. this.displacementMap = null;
  17640. this.displacementScale = 1;
  17641. this.displacementBias = 0;
  17642. this.wireframe = false;
  17643. this.wireframeLinewidth = 1;
  17644. this.fog = false;
  17645. this.setValues( parameters );
  17646. }
  17647. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  17648. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17649. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17650. MeshDepthMaterial.prototype.copy = function ( source ) {
  17651. Material.prototype.copy.call( this, source );
  17652. this.depthPacking = source.depthPacking;
  17653. this.skinning = source.skinning;
  17654. this.morphTargets = source.morphTargets;
  17655. this.map = source.map;
  17656. this.alphaMap = source.alphaMap;
  17657. this.displacementMap = source.displacementMap;
  17658. this.displacementScale = source.displacementScale;
  17659. this.displacementBias = source.displacementBias;
  17660. this.wireframe = source.wireframe;
  17661. this.wireframeLinewidth = source.wireframeLinewidth;
  17662. return this;
  17663. };
  17664. /**
  17665. * parameters = {
  17666. *
  17667. * referencePosition: <float>,
  17668. * nearDistance: <float>,
  17669. * farDistance: <float>,
  17670. *
  17671. * skinning: <bool>,
  17672. * morphTargets: <bool>,
  17673. *
  17674. * map: new THREE.Texture( <Image> ),
  17675. *
  17676. * alphaMap: new THREE.Texture( <Image> ),
  17677. *
  17678. * displacementMap: new THREE.Texture( <Image> ),
  17679. * displacementScale: <float>,
  17680. * displacementBias: <float>
  17681. *
  17682. * }
  17683. */
  17684. function MeshDistanceMaterial( parameters ) {
  17685. Material.call( this );
  17686. this.type = 'MeshDistanceMaterial';
  17687. this.referencePosition = new Vector3();
  17688. this.nearDistance = 1;
  17689. this.farDistance = 1000;
  17690. this.skinning = false;
  17691. this.morphTargets = false;
  17692. this.map = null;
  17693. this.alphaMap = null;
  17694. this.displacementMap = null;
  17695. this.displacementScale = 1;
  17696. this.displacementBias = 0;
  17697. this.fog = false;
  17698. this.setValues( parameters );
  17699. }
  17700. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  17701. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  17702. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  17703. MeshDistanceMaterial.prototype.copy = function ( source ) {
  17704. Material.prototype.copy.call( this, source );
  17705. this.referencePosition.copy( source.referencePosition );
  17706. this.nearDistance = source.nearDistance;
  17707. this.farDistance = source.farDistance;
  17708. this.skinning = source.skinning;
  17709. this.morphTargets = source.morphTargets;
  17710. this.map = source.map;
  17711. this.alphaMap = source.alphaMap;
  17712. this.displacementMap = source.displacementMap;
  17713. this.displacementScale = source.displacementScale;
  17714. this.displacementBias = source.displacementBias;
  17715. return this;
  17716. };
  17717. var vsm_frag = /* glsl */"\nuniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n\n#include <packing>\n\nvoid main() {\n\n float mean = 0.0;\n float squared_mean = 0.0;\n\n\t// This seems totally useless but it's a crazy work around for a Adreno compiler bug\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\n #ifdef HORIZONAL_PASS\n\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\n #else\n\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n\n #endif\n\n }\n\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n\n float std_dev = sqrt( squared_mean - mean * mean );\n\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n\n}\n";
  17718. var vsm_vert = /* glsl */"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}\n";
  17719. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  17720. var _frustum = new Frustum();
  17721. var _shadowMapSize = new Vector2(),
  17722. _viewportSize = new Vector2(),
  17723. _viewport = new Vector4(),
  17724. _depthMaterials = [],
  17725. _distanceMaterials = [],
  17726. _materialCache = {};
  17727. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  17728. var shadowMaterialVertical = new ShaderMaterial( {
  17729. defines: {
  17730. SAMPLE_RATE: 2.0 / 8.0,
  17731. HALF_SAMPLE_RATE: 1.0 / 8.0
  17732. },
  17733. uniforms: {
  17734. shadow_pass: { value: null },
  17735. resolution: { value: new Vector2() },
  17736. radius: { value: 4.0 }
  17737. },
  17738. vertexShader: vsm_vert,
  17739. fragmentShader: vsm_frag
  17740. } );
  17741. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  17742. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  17743. var fullScreenTri = new BufferGeometry();
  17744. fullScreenTri.setAttribute(
  17745. "position",
  17746. new BufferAttribute(
  17747. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  17748. 3
  17749. )
  17750. );
  17751. var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  17752. var scope = this;
  17753. this.enabled = false;
  17754. this.autoUpdate = true;
  17755. this.needsUpdate = false;
  17756. this.type = PCFShadowMap;
  17757. this.render = function ( lights, scene, camera ) {
  17758. if ( scope.enabled === false ) { return; }
  17759. if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; }
  17760. if ( lights.length === 0 ) { return; }
  17761. var currentRenderTarget = _renderer.getRenderTarget();
  17762. var activeCubeFace = _renderer.getActiveCubeFace();
  17763. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  17764. var _state = _renderer.state;
  17765. // Set GL state for depth map.
  17766. _state.setBlending( NoBlending );
  17767. _state.buffers.color.setClear( 1, 1, 1, 1 );
  17768. _state.buffers.depth.setTest( true );
  17769. _state.setScissorTest( false );
  17770. // render depth map
  17771. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  17772. var light = lights[ i ];
  17773. var shadow = light.shadow;
  17774. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) { continue; }
  17775. if ( shadow === undefined ) {
  17776. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  17777. continue;
  17778. }
  17779. _shadowMapSize.copy( shadow.mapSize );
  17780. var shadowFrameExtents = shadow.getFrameExtents();
  17781. _shadowMapSize.multiply( shadowFrameExtents );
  17782. _viewportSize.copy( shadow.mapSize );
  17783. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  17784. if ( _shadowMapSize.x > maxTextureSize ) {
  17785. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  17786. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  17787. shadow.mapSize.x = _viewportSize.x;
  17788. }
  17789. if ( _shadowMapSize.y > maxTextureSize ) {
  17790. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  17791. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  17792. shadow.mapSize.y = _viewportSize.y;
  17793. }
  17794. }
  17795. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17796. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat, stencilBuffer: false };
  17797. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17798. shadow.map.texture.name = light.name + ".shadowMap";
  17799. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17800. shadow.camera.updateProjectionMatrix();
  17801. }
  17802. if ( shadow.map === null ) {
  17803. var pars$1 = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat, stencilBuffer: false };
  17804. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars$1 );
  17805. shadow.map.texture.name = light.name + ".shadowMap";
  17806. shadow.camera.updateProjectionMatrix();
  17807. }
  17808. _renderer.setRenderTarget( shadow.map );
  17809. _renderer.clear();
  17810. var viewportCount = shadow.getViewportCount();
  17811. for ( var vp = 0; vp < viewportCount; vp ++ ) {
  17812. var viewport = shadow.getViewport( vp );
  17813. _viewport.set(
  17814. _viewportSize.x * viewport.x,
  17815. _viewportSize.y * viewport.y,
  17816. _viewportSize.x * viewport.z,
  17817. _viewportSize.y * viewport.w
  17818. );
  17819. _state.viewport( _viewport );
  17820. shadow.updateMatrices( light, vp );
  17821. _frustum = shadow.getFrustum();
  17822. renderObject( scene, camera, shadow.camera, light, this.type );
  17823. }
  17824. // do blur pass for VSM
  17825. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17826. VSMPass( shadow, camera );
  17827. }
  17828. shadow.needsUpdate = false;
  17829. }
  17830. scope.needsUpdate = false;
  17831. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  17832. };
  17833. function VSMPass( shadow, camera ) {
  17834. var geometry = _objects.update( fullScreenMesh );
  17835. // vertical pass
  17836. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  17837. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  17838. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  17839. _renderer.setRenderTarget( shadow.mapPass );
  17840. _renderer.clear();
  17841. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  17842. // horizonal pass
  17843. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  17844. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  17845. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  17846. _renderer.setRenderTarget( shadow.map );
  17847. _renderer.clear();
  17848. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );
  17849. }
  17850. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  17851. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17852. var material = _depthMaterials[ index ];
  17853. if ( material === undefined ) {
  17854. material = new MeshDepthMaterial( {
  17855. depthPacking: RGBADepthPacking,
  17856. morphTargets: useMorphing,
  17857. skinning: useSkinning
  17858. } );
  17859. _depthMaterials[ index ] = material;
  17860. }
  17861. return material;
  17862. }
  17863. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  17864. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17865. var material = _distanceMaterials[ index ];
  17866. if ( material === undefined ) {
  17867. material = new MeshDistanceMaterial( {
  17868. morphTargets: useMorphing,
  17869. skinning: useSkinning
  17870. } );
  17871. _distanceMaterials[ index ] = material;
  17872. }
  17873. return material;
  17874. }
  17875. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  17876. var result = null;
  17877. var getMaterialVariant = getDepthMaterialVariant;
  17878. var customMaterial = object.customDepthMaterial;
  17879. if ( light.isPointLight === true ) {
  17880. getMaterialVariant = getDistanceMaterialVariant;
  17881. customMaterial = object.customDistanceMaterial;
  17882. }
  17883. if ( customMaterial === undefined ) {
  17884. var useMorphing = false;
  17885. if ( material.morphTargets === true ) {
  17886. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  17887. }
  17888. var useSkinning = false;
  17889. if ( object.isSkinnedMesh === true ) {
  17890. if ( material.skinning === true ) {
  17891. useSkinning = true;
  17892. } else {
  17893. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  17894. }
  17895. }
  17896. var useInstancing = object.isInstancedMesh === true;
  17897. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  17898. } else {
  17899. result = customMaterial;
  17900. }
  17901. if ( _renderer.localClippingEnabled &&
  17902. material.clipShadows === true &&
  17903. material.clippingPlanes.length !== 0 ) {
  17904. // in this case we need a unique material instance reflecting the
  17905. // appropriate state
  17906. var keyA = result.uuid, keyB = material.uuid;
  17907. var materialsForVariant = _materialCache[ keyA ];
  17908. if ( materialsForVariant === undefined ) {
  17909. materialsForVariant = {};
  17910. _materialCache[ keyA ] = materialsForVariant;
  17911. }
  17912. var cachedMaterial = materialsForVariant[ keyB ];
  17913. if ( cachedMaterial === undefined ) {
  17914. cachedMaterial = result.clone();
  17915. materialsForVariant[ keyB ] = cachedMaterial;
  17916. }
  17917. result = cachedMaterial;
  17918. }
  17919. result.visible = material.visible;
  17920. result.wireframe = material.wireframe;
  17921. if ( type === VSMShadowMap ) {
  17922. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  17923. } else {
  17924. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  17925. }
  17926. result.clipShadows = material.clipShadows;
  17927. result.clippingPlanes = material.clippingPlanes;
  17928. result.clipIntersection = material.clipIntersection;
  17929. result.wireframeLinewidth = material.wireframeLinewidth;
  17930. result.linewidth = material.linewidth;
  17931. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  17932. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  17933. result.nearDistance = shadowCameraNear;
  17934. result.farDistance = shadowCameraFar;
  17935. }
  17936. return result;
  17937. }
  17938. function renderObject( object, camera, shadowCamera, light, type ) {
  17939. if ( object.visible === false ) { return; }
  17940. var visible = object.layers.test( camera.layers );
  17941. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  17942. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  17943. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17944. var geometry = _objects.update( object );
  17945. var material = object.material;
  17946. if ( Array.isArray( material ) ) {
  17947. var groups = geometry.groups;
  17948. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17949. var group = groups[ k ];
  17950. var groupMaterial = material[ group.materialIndex ];
  17951. if ( groupMaterial && groupMaterial.visible ) {
  17952. var depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  17953. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17954. }
  17955. }
  17956. } else if ( material.visible ) {
  17957. var depthMaterial$1 = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  17958. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial$1, object, null );
  17959. }
  17960. }
  17961. }
  17962. var children = object.children;
  17963. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17964. renderObject( children[ i ], camera, shadowCamera, light, type );
  17965. }
  17966. }
  17967. }
  17968. function WebGLState( gl, extensions, capabilities ) {
  17969. var isWebGL2 = capabilities.isWebGL2;
  17970. function ColorBuffer() {
  17971. var locked = false;
  17972. var color = new Vector4();
  17973. var currentColorMask = null;
  17974. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  17975. return {
  17976. setMask: function ( colorMask ) {
  17977. if ( currentColorMask !== colorMask && ! locked ) {
  17978. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  17979. currentColorMask = colorMask;
  17980. }
  17981. },
  17982. setLocked: function ( lock ) {
  17983. locked = lock;
  17984. },
  17985. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  17986. if ( premultipliedAlpha === true ) {
  17987. r *= a; g *= a; b *= a;
  17988. }
  17989. color.set( r, g, b, a );
  17990. if ( currentColorClear.equals( color ) === false ) {
  17991. gl.clearColor( r, g, b, a );
  17992. currentColorClear.copy( color );
  17993. }
  17994. },
  17995. reset: function () {
  17996. locked = false;
  17997. currentColorMask = null;
  17998. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  17999. }
  18000. };
  18001. }
  18002. function DepthBuffer() {
  18003. var locked = false;
  18004. var currentDepthMask = null;
  18005. var currentDepthFunc = null;
  18006. var currentDepthClear = null;
  18007. return {
  18008. setTest: function ( depthTest ) {
  18009. if ( depthTest ) {
  18010. enable( 2929 );
  18011. } else {
  18012. disable( 2929 );
  18013. }
  18014. },
  18015. setMask: function ( depthMask ) {
  18016. if ( currentDepthMask !== depthMask && ! locked ) {
  18017. gl.depthMask( depthMask );
  18018. currentDepthMask = depthMask;
  18019. }
  18020. },
  18021. setFunc: function ( depthFunc ) {
  18022. if ( currentDepthFunc !== depthFunc ) {
  18023. if ( depthFunc ) {
  18024. switch ( depthFunc ) {
  18025. case NeverDepth:
  18026. gl.depthFunc( 512 );
  18027. break;
  18028. case AlwaysDepth:
  18029. gl.depthFunc( 519 );
  18030. break;
  18031. case LessDepth:
  18032. gl.depthFunc( 513 );
  18033. break;
  18034. case LessEqualDepth:
  18035. gl.depthFunc( 515 );
  18036. break;
  18037. case EqualDepth:
  18038. gl.depthFunc( 514 );
  18039. break;
  18040. case GreaterEqualDepth:
  18041. gl.depthFunc( 518 );
  18042. break;
  18043. case GreaterDepth:
  18044. gl.depthFunc( 516 );
  18045. break;
  18046. case NotEqualDepth:
  18047. gl.depthFunc( 517 );
  18048. break;
  18049. default:
  18050. gl.depthFunc( 515 );
  18051. }
  18052. } else {
  18053. gl.depthFunc( 515 );
  18054. }
  18055. currentDepthFunc = depthFunc;
  18056. }
  18057. },
  18058. setLocked: function ( lock ) {
  18059. locked = lock;
  18060. },
  18061. setClear: function ( depth ) {
  18062. if ( currentDepthClear !== depth ) {
  18063. gl.clearDepth( depth );
  18064. currentDepthClear = depth;
  18065. }
  18066. },
  18067. reset: function () {
  18068. locked = false;
  18069. currentDepthMask = null;
  18070. currentDepthFunc = null;
  18071. currentDepthClear = null;
  18072. }
  18073. };
  18074. }
  18075. function StencilBuffer() {
  18076. var locked = false;
  18077. var currentStencilMask = null;
  18078. var currentStencilFunc = null;
  18079. var currentStencilRef = null;
  18080. var currentStencilFuncMask = null;
  18081. var currentStencilFail = null;
  18082. var currentStencilZFail = null;
  18083. var currentStencilZPass = null;
  18084. var currentStencilClear = null;
  18085. return {
  18086. setTest: function ( stencilTest ) {
  18087. if ( ! locked ) {
  18088. if ( stencilTest ) {
  18089. enable( 2960 );
  18090. } else {
  18091. disable( 2960 );
  18092. }
  18093. }
  18094. },
  18095. setMask: function ( stencilMask ) {
  18096. if ( currentStencilMask !== stencilMask && ! locked ) {
  18097. gl.stencilMask( stencilMask );
  18098. currentStencilMask = stencilMask;
  18099. }
  18100. },
  18101. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  18102. if ( currentStencilFunc !== stencilFunc ||
  18103. currentStencilRef !== stencilRef ||
  18104. currentStencilFuncMask !== stencilMask ) {
  18105. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18106. currentStencilFunc = stencilFunc;
  18107. currentStencilRef = stencilRef;
  18108. currentStencilFuncMask = stencilMask;
  18109. }
  18110. },
  18111. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  18112. if ( currentStencilFail !== stencilFail ||
  18113. currentStencilZFail !== stencilZFail ||
  18114. currentStencilZPass !== stencilZPass ) {
  18115. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18116. currentStencilFail = stencilFail;
  18117. currentStencilZFail = stencilZFail;
  18118. currentStencilZPass = stencilZPass;
  18119. }
  18120. },
  18121. setLocked: function ( lock ) {
  18122. locked = lock;
  18123. },
  18124. setClear: function ( stencil ) {
  18125. if ( currentStencilClear !== stencil ) {
  18126. gl.clearStencil( stencil );
  18127. currentStencilClear = stencil;
  18128. }
  18129. },
  18130. reset: function () {
  18131. locked = false;
  18132. currentStencilMask = null;
  18133. currentStencilFunc = null;
  18134. currentStencilRef = null;
  18135. currentStencilFuncMask = null;
  18136. currentStencilFail = null;
  18137. currentStencilZFail = null;
  18138. currentStencilZPass = null;
  18139. currentStencilClear = null;
  18140. }
  18141. };
  18142. }
  18143. //
  18144. var colorBuffer = new ColorBuffer();
  18145. var depthBuffer = new DepthBuffer();
  18146. var stencilBuffer = new StencilBuffer();
  18147. var enabledCapabilities = {};
  18148. var currentProgram = null;
  18149. var currentBlendingEnabled = null;
  18150. var currentBlending = null;
  18151. var currentBlendEquation = null;
  18152. var currentBlendSrc = null;
  18153. var currentBlendDst = null;
  18154. var currentBlendEquationAlpha = null;
  18155. var currentBlendSrcAlpha = null;
  18156. var currentBlendDstAlpha = null;
  18157. var currentPremultipledAlpha = false;
  18158. var currentFlipSided = null;
  18159. var currentCullFace = null;
  18160. var currentLineWidth = null;
  18161. var currentPolygonOffsetFactor = null;
  18162. var currentPolygonOffsetUnits = null;
  18163. var maxTextures = gl.getParameter( 35661 );
  18164. var lineWidthAvailable = false;
  18165. var version = 0;
  18166. var glVersion = gl.getParameter( 7938 );
  18167. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  18168. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  18169. lineWidthAvailable = ( version >= 1.0 );
  18170. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  18171. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  18172. lineWidthAvailable = ( version >= 2.0 );
  18173. }
  18174. var currentTextureSlot = null;
  18175. var currentBoundTextures = {};
  18176. var currentScissor = new Vector4();
  18177. var currentViewport = new Vector4();
  18178. function createTexture( type, target, count ) {
  18179. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  18180. var texture = gl.createTexture();
  18181. gl.bindTexture( type, texture );
  18182. gl.texParameteri( type, 10241, 9728 );
  18183. gl.texParameteri( type, 10240, 9728 );
  18184. for ( var i = 0; i < count; i ++ ) {
  18185. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  18186. }
  18187. return texture;
  18188. }
  18189. var emptyTextures = {};
  18190. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  18191. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  18192. // init
  18193. colorBuffer.setClear( 0, 0, 0, 1 );
  18194. depthBuffer.setClear( 1 );
  18195. stencilBuffer.setClear( 0 );
  18196. enable( 2929 );
  18197. depthBuffer.setFunc( LessEqualDepth );
  18198. setFlipSided( false );
  18199. setCullFace( CullFaceBack );
  18200. enable( 2884 );
  18201. setBlending( NoBlending );
  18202. //
  18203. function enable( id ) {
  18204. if ( enabledCapabilities[ id ] !== true ) {
  18205. gl.enable( id );
  18206. enabledCapabilities[ id ] = true;
  18207. }
  18208. }
  18209. function disable( id ) {
  18210. if ( enabledCapabilities[ id ] !== false ) {
  18211. gl.disable( id );
  18212. enabledCapabilities[ id ] = false;
  18213. }
  18214. }
  18215. function useProgram( program ) {
  18216. if ( currentProgram !== program ) {
  18217. gl.useProgram( program );
  18218. currentProgram = program;
  18219. return true;
  18220. }
  18221. return false;
  18222. }
  18223. var equationToGL = {};
  18224. equationToGL[ AddEquation ] = 32774;
  18225. equationToGL[ SubtractEquation ] = 32778;
  18226. equationToGL[ ReverseSubtractEquation ] = 32779;
  18227. if ( isWebGL2 ) {
  18228. equationToGL[ MinEquation ] = 32775;
  18229. equationToGL[ MaxEquation ] = 32776;
  18230. } else {
  18231. var extension = extensions.get( 'EXT_blend_minmax' );
  18232. if ( extension !== null ) {
  18233. equationToGL[ MinEquation ] = extension.MIN_EXT;
  18234. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  18235. }
  18236. }
  18237. var factorToGL = {};
  18238. factorToGL[ ZeroFactor ] = 0;
  18239. factorToGL[ OneFactor ] = 1;
  18240. factorToGL[ SrcColorFactor ] = 768;
  18241. factorToGL[ SrcAlphaFactor ] = 770;
  18242. factorToGL[ SrcAlphaSaturateFactor ] = 776;
  18243. factorToGL[ DstColorFactor ] = 774;
  18244. factorToGL[ DstAlphaFactor ] = 772;
  18245. factorToGL[ OneMinusSrcColorFactor ] = 769;
  18246. factorToGL[ OneMinusSrcAlphaFactor ] = 771;
  18247. factorToGL[ OneMinusDstColorFactor ] = 775;
  18248. factorToGL[ OneMinusDstAlphaFactor ] = 773;
  18249. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18250. if ( blending === NoBlending ) {
  18251. if ( currentBlendingEnabled ) {
  18252. disable( 3042 );
  18253. currentBlendingEnabled = false;
  18254. }
  18255. return;
  18256. }
  18257. if ( ! currentBlendingEnabled ) {
  18258. enable( 3042 );
  18259. currentBlendingEnabled = true;
  18260. }
  18261. if ( blending !== CustomBlending ) {
  18262. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  18263. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  18264. gl.blendEquation( 32774 );
  18265. currentBlendEquation = AddEquation;
  18266. currentBlendEquationAlpha = AddEquation;
  18267. }
  18268. if ( premultipliedAlpha ) {
  18269. switch ( blending ) {
  18270. case NormalBlending:
  18271. gl.blendFuncSeparate( 1, 771, 1, 771 );
  18272. break;
  18273. case AdditiveBlending:
  18274. gl.blendFunc( 1, 1 );
  18275. break;
  18276. case SubtractiveBlending:
  18277. gl.blendFuncSeparate( 0, 0, 769, 771 );
  18278. break;
  18279. case MultiplyBlending:
  18280. gl.blendFuncSeparate( 0, 768, 0, 770 );
  18281. break;
  18282. default:
  18283. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18284. break;
  18285. }
  18286. } else {
  18287. switch ( blending ) {
  18288. case NormalBlending:
  18289. gl.blendFuncSeparate( 770, 771, 1, 771 );
  18290. break;
  18291. case AdditiveBlending:
  18292. gl.blendFunc( 770, 1 );
  18293. break;
  18294. case SubtractiveBlending:
  18295. gl.blendFunc( 0, 769 );
  18296. break;
  18297. case MultiplyBlending:
  18298. gl.blendFunc( 0, 768 );
  18299. break;
  18300. default:
  18301. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18302. break;
  18303. }
  18304. }
  18305. currentBlendSrc = null;
  18306. currentBlendDst = null;
  18307. currentBlendSrcAlpha = null;
  18308. currentBlendDstAlpha = null;
  18309. currentBlending = blending;
  18310. currentPremultipledAlpha = premultipliedAlpha;
  18311. }
  18312. return;
  18313. }
  18314. // custom blending
  18315. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18316. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18317. blendDstAlpha = blendDstAlpha || blendDst;
  18318. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18319. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18320. currentBlendEquation = blendEquation;
  18321. currentBlendEquationAlpha = blendEquationAlpha;
  18322. }
  18323. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18324. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18325. currentBlendSrc = blendSrc;
  18326. currentBlendDst = blendDst;
  18327. currentBlendSrcAlpha = blendSrcAlpha;
  18328. currentBlendDstAlpha = blendDstAlpha;
  18329. }
  18330. currentBlending = blending;
  18331. currentPremultipledAlpha = null;
  18332. }
  18333. function setMaterial( material, frontFaceCW ) {
  18334. material.side === DoubleSide
  18335. ? disable( 2884 )
  18336. : enable( 2884 );
  18337. var flipSided = ( material.side === BackSide );
  18338. if ( frontFaceCW ) { flipSided = ! flipSided; }
  18339. setFlipSided( flipSided );
  18340. ( material.blending === NormalBlending && material.transparent === false )
  18341. ? setBlending( NoBlending )
  18342. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  18343. depthBuffer.setFunc( material.depthFunc );
  18344. depthBuffer.setTest( material.depthTest );
  18345. depthBuffer.setMask( material.depthWrite );
  18346. colorBuffer.setMask( material.colorWrite );
  18347. var stencilWrite = material.stencilWrite;
  18348. stencilBuffer.setTest( stencilWrite );
  18349. if ( stencilWrite ) {
  18350. stencilBuffer.setMask( material.stencilWriteMask );
  18351. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  18352. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  18353. }
  18354. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  18355. }
  18356. //
  18357. function setFlipSided( flipSided ) {
  18358. if ( currentFlipSided !== flipSided ) {
  18359. if ( flipSided ) {
  18360. gl.frontFace( 2304 );
  18361. } else {
  18362. gl.frontFace( 2305 );
  18363. }
  18364. currentFlipSided = flipSided;
  18365. }
  18366. }
  18367. function setCullFace( cullFace ) {
  18368. if ( cullFace !== CullFaceNone ) {
  18369. enable( 2884 );
  18370. if ( cullFace !== currentCullFace ) {
  18371. if ( cullFace === CullFaceBack ) {
  18372. gl.cullFace( 1029 );
  18373. } else if ( cullFace === CullFaceFront ) {
  18374. gl.cullFace( 1028 );
  18375. } else {
  18376. gl.cullFace( 1032 );
  18377. }
  18378. }
  18379. } else {
  18380. disable( 2884 );
  18381. }
  18382. currentCullFace = cullFace;
  18383. }
  18384. function setLineWidth( width ) {
  18385. if ( width !== currentLineWidth ) {
  18386. if ( lineWidthAvailable ) { gl.lineWidth( width ); }
  18387. currentLineWidth = width;
  18388. }
  18389. }
  18390. function setPolygonOffset( polygonOffset, factor, units ) {
  18391. if ( polygonOffset ) {
  18392. enable( 32823 );
  18393. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  18394. gl.polygonOffset( factor, units );
  18395. currentPolygonOffsetFactor = factor;
  18396. currentPolygonOffsetUnits = units;
  18397. }
  18398. } else {
  18399. disable( 32823 );
  18400. }
  18401. }
  18402. function setScissorTest( scissorTest ) {
  18403. if ( scissorTest ) {
  18404. enable( 3089 );
  18405. } else {
  18406. disable( 3089 );
  18407. }
  18408. }
  18409. // texture
  18410. function activeTexture( webglSlot ) {
  18411. if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; }
  18412. if ( currentTextureSlot !== webglSlot ) {
  18413. gl.activeTexture( webglSlot );
  18414. currentTextureSlot = webglSlot;
  18415. }
  18416. }
  18417. function bindTexture( webglType, webglTexture ) {
  18418. if ( currentTextureSlot === null ) {
  18419. activeTexture();
  18420. }
  18421. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18422. if ( boundTexture === undefined ) {
  18423. boundTexture = { type: undefined, texture: undefined };
  18424. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18425. }
  18426. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18427. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  18428. boundTexture.type = webglType;
  18429. boundTexture.texture = webglTexture;
  18430. }
  18431. }
  18432. function unbindTexture() {
  18433. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18434. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  18435. gl.bindTexture( boundTexture.type, null );
  18436. boundTexture.type = undefined;
  18437. boundTexture.texture = undefined;
  18438. }
  18439. }
  18440. function compressedTexImage2D() {
  18441. try {
  18442. gl.compressedTexImage2D.apply( gl, arguments );
  18443. } catch ( error ) {
  18444. console.error( 'THREE.WebGLState:', error );
  18445. }
  18446. }
  18447. function texImage2D() {
  18448. try {
  18449. gl.texImage2D.apply( gl, arguments );
  18450. } catch ( error ) {
  18451. console.error( 'THREE.WebGLState:', error );
  18452. }
  18453. }
  18454. function texImage3D() {
  18455. try {
  18456. gl.texImage3D.apply( gl, arguments );
  18457. } catch ( error ) {
  18458. console.error( 'THREE.WebGLState:', error );
  18459. }
  18460. }
  18461. //
  18462. function scissor( scissor ) {
  18463. if ( currentScissor.equals( scissor ) === false ) {
  18464. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  18465. currentScissor.copy( scissor );
  18466. }
  18467. }
  18468. function viewport( viewport ) {
  18469. if ( currentViewport.equals( viewport ) === false ) {
  18470. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  18471. currentViewport.copy( viewport );
  18472. }
  18473. }
  18474. //
  18475. function reset() {
  18476. enabledCapabilities = {};
  18477. currentTextureSlot = null;
  18478. currentBoundTextures = {};
  18479. currentProgram = null;
  18480. currentBlending = null;
  18481. currentFlipSided = null;
  18482. currentCullFace = null;
  18483. colorBuffer.reset();
  18484. depthBuffer.reset();
  18485. stencilBuffer.reset();
  18486. }
  18487. return {
  18488. buffers: {
  18489. color: colorBuffer,
  18490. depth: depthBuffer,
  18491. stencil: stencilBuffer
  18492. },
  18493. enable: enable,
  18494. disable: disable,
  18495. useProgram: useProgram,
  18496. setBlending: setBlending,
  18497. setMaterial: setMaterial,
  18498. setFlipSided: setFlipSided,
  18499. setCullFace: setCullFace,
  18500. setLineWidth: setLineWidth,
  18501. setPolygonOffset: setPolygonOffset,
  18502. setScissorTest: setScissorTest,
  18503. activeTexture: activeTexture,
  18504. bindTexture: bindTexture,
  18505. unbindTexture: unbindTexture,
  18506. compressedTexImage2D: compressedTexImage2D,
  18507. texImage2D: texImage2D,
  18508. texImage3D: texImage3D,
  18509. scissor: scissor,
  18510. viewport: viewport,
  18511. reset: reset
  18512. };
  18513. }
  18514. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  18515. var isWebGL2 = capabilities.isWebGL2;
  18516. var maxTextures = capabilities.maxTextures;
  18517. var maxCubemapSize = capabilities.maxCubemapSize;
  18518. var maxTextureSize = capabilities.maxTextureSize;
  18519. var maxSamples = capabilities.maxSamples;
  18520. var _videoTextures = new WeakMap();
  18521. var _canvas;
  18522. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18523. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18524. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18525. var useOffscreenCanvas = false;
  18526. try {
  18527. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  18528. && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;
  18529. } catch ( err ) {
  18530. // Ignore any errors
  18531. }
  18532. function createCanvas( width, height ) {
  18533. // Use OffscreenCanvas when available. Specially needed in web workers
  18534. return useOffscreenCanvas ?
  18535. new OffscreenCanvas( width, height ) :
  18536. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  18537. }
  18538. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  18539. var scale = 1;
  18540. // handle case if texture exceeds max size
  18541. if ( image.width > maxSize || image.height > maxSize ) {
  18542. scale = maxSize / Math.max( image.width, image.height );
  18543. }
  18544. // only perform resize if necessary
  18545. if ( scale < 1 || needsPowerOfTwo === true ) {
  18546. // only perform resize for certain image types
  18547. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  18548. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  18549. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  18550. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  18551. var width = floor( scale * image.width );
  18552. var height = floor( scale * image.height );
  18553. if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); }
  18554. // cube textures can't reuse the same canvas
  18555. var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  18556. canvas.width = width;
  18557. canvas.height = height;
  18558. var context = canvas.getContext( '2d' );
  18559. context.drawImage( image, 0, 0, width, height );
  18560. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  18561. return canvas;
  18562. } else {
  18563. if ( 'data' in image ) {
  18564. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  18565. }
  18566. return image;
  18567. }
  18568. }
  18569. return image;
  18570. }
  18571. function isPowerOfTwo( image ) {
  18572. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  18573. }
  18574. function textureNeedsPowerOfTwo( texture ) {
  18575. if ( isWebGL2 ) { return false; }
  18576. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  18577. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  18578. }
  18579. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  18580. return texture.generateMipmaps && supportsMips &&
  18581. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18582. }
  18583. function generateMipmap( target, texture, width, height ) {
  18584. _gl.generateMipmap( target );
  18585. var textureProperties = properties.get( texture );
  18586. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18587. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  18588. }
  18589. function getInternalFormat( internalFormatName, glFormat, glType ) {
  18590. if ( isWebGL2 === false ) { return glFormat; }
  18591. if ( internalFormatName !== null ) {
  18592. if ( _gl[ internalFormatName ] !== undefined ) { return _gl[ internalFormatName ]; }
  18593. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  18594. }
  18595. var internalFormat = glFormat;
  18596. if ( glFormat === 6403 ) {
  18597. if ( glType === 5126 ) { internalFormat = 33326; }
  18598. if ( glType === 5131 ) { internalFormat = 33325; }
  18599. if ( glType === 5121 ) { internalFormat = 33321; }
  18600. }
  18601. if ( glFormat === 6407 ) {
  18602. if ( glType === 5126 ) { internalFormat = 34837; }
  18603. if ( glType === 5131 ) { internalFormat = 34843; }
  18604. if ( glType === 5121 ) { internalFormat = 32849; }
  18605. }
  18606. if ( glFormat === 6408 ) {
  18607. if ( glType === 5126 ) { internalFormat = 34836; }
  18608. if ( glType === 5131 ) { internalFormat = 34842; }
  18609. if ( glType === 5121 ) { internalFormat = 32856; }
  18610. }
  18611. if ( internalFormat === 33325 || internalFormat === 33326 ||
  18612. internalFormat === 34842 || internalFormat === 34836 ) {
  18613. extensions.get( 'EXT_color_buffer_float' );
  18614. }
  18615. return internalFormat;
  18616. }
  18617. // Fallback filters for non-power-of-2 textures
  18618. function filterFallback( f ) {
  18619. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18620. return 9728;
  18621. }
  18622. return 9729;
  18623. }
  18624. //
  18625. function onTextureDispose( event ) {
  18626. var texture = event.target;
  18627. texture.removeEventListener( 'dispose', onTextureDispose );
  18628. deallocateTexture( texture );
  18629. if ( texture.isVideoTexture ) {
  18630. _videoTextures.delete( texture );
  18631. }
  18632. info.memory.textures --;
  18633. }
  18634. function onRenderTargetDispose( event ) {
  18635. var renderTarget = event.target;
  18636. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  18637. deallocateRenderTarget( renderTarget );
  18638. info.memory.textures --;
  18639. }
  18640. //
  18641. function deallocateTexture( texture ) {
  18642. var textureProperties = properties.get( texture );
  18643. if ( textureProperties.__webglInit === undefined ) { return; }
  18644. _gl.deleteTexture( textureProperties.__webglTexture );
  18645. properties.remove( texture );
  18646. }
  18647. function deallocateRenderTarget( renderTarget ) {
  18648. var renderTargetProperties = properties.get( renderTarget );
  18649. var textureProperties = properties.get( renderTarget.texture );
  18650. if ( ! renderTarget ) { return; }
  18651. if ( textureProperties.__webglTexture !== undefined ) {
  18652. _gl.deleteTexture( textureProperties.__webglTexture );
  18653. }
  18654. if ( renderTarget.depthTexture ) {
  18655. renderTarget.depthTexture.dispose();
  18656. }
  18657. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18658. for ( var i = 0; i < 6; i ++ ) {
  18659. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  18660. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); }
  18661. }
  18662. } else {
  18663. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  18664. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); }
  18665. if ( renderTargetProperties.__webglMultisampledFramebuffer ) { _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); }
  18666. if ( renderTargetProperties.__webglColorRenderbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); }
  18667. if ( renderTargetProperties.__webglDepthRenderbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); }
  18668. }
  18669. properties.remove( renderTarget.texture );
  18670. properties.remove( renderTarget );
  18671. }
  18672. //
  18673. var textureUnits = 0;
  18674. function resetTextureUnits() {
  18675. textureUnits = 0;
  18676. }
  18677. function allocateTextureUnit() {
  18678. var textureUnit = textureUnits;
  18679. if ( textureUnit >= maxTextures ) {
  18680. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  18681. }
  18682. textureUnits += 1;
  18683. return textureUnit;
  18684. }
  18685. //
  18686. function setTexture2D( texture, slot ) {
  18687. var textureProperties = properties.get( texture );
  18688. if ( texture.isVideoTexture ) { updateVideoTexture( texture ); }
  18689. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18690. var image = texture.image;
  18691. if ( image === undefined ) {
  18692. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  18693. } else if ( image.complete === false ) {
  18694. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  18695. } else {
  18696. uploadTexture( textureProperties, texture, slot );
  18697. return;
  18698. }
  18699. }
  18700. state.activeTexture( 33984 + slot );
  18701. state.bindTexture( 3553, textureProperties.__webglTexture );
  18702. }
  18703. function setTexture2DArray( texture, slot ) {
  18704. var textureProperties = properties.get( texture );
  18705. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18706. uploadTexture( textureProperties, texture, slot );
  18707. return;
  18708. }
  18709. state.activeTexture( 33984 + slot );
  18710. state.bindTexture( 35866, textureProperties.__webglTexture );
  18711. }
  18712. function setTexture3D( texture, slot ) {
  18713. var textureProperties = properties.get( texture );
  18714. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18715. uploadTexture( textureProperties, texture, slot );
  18716. return;
  18717. }
  18718. state.activeTexture( 33984 + slot );
  18719. state.bindTexture( 32879, textureProperties.__webglTexture );
  18720. }
  18721. function setTextureCube( texture, slot ) {
  18722. if ( texture.image.length !== 6 ) { return; }
  18723. var textureProperties = properties.get( texture );
  18724. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18725. initTexture( textureProperties, texture );
  18726. state.activeTexture( 33984 + slot );
  18727. state.bindTexture( 34067, textureProperties.__webglTexture );
  18728. _gl.pixelStorei( 37440, texture.flipY );
  18729. var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  18730. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  18731. var cubeImage = [];
  18732. for ( var i = 0; i < 6; i ++ ) {
  18733. if ( ! isCompressed && ! isDataTexture ) {
  18734. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  18735. } else {
  18736. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  18737. }
  18738. }
  18739. var image = cubeImage[ 0 ],
  18740. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  18741. glFormat = utils.convert( texture.format ),
  18742. glType = utils.convert( texture.type ),
  18743. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  18744. setTextureParameters( 34067, texture, supportsMips );
  18745. var mipmaps;
  18746. if ( isCompressed ) {
  18747. for ( var i$1 = 0; i$1 < 6; i$1 ++ ) {
  18748. mipmaps = cubeImage[ i$1 ].mipmaps;
  18749. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18750. var mipmap = mipmaps[ j ];
  18751. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18752. if ( glFormat !== null ) {
  18753. state.compressedTexImage2D( 34069 + i$1, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18754. } else {
  18755. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  18756. }
  18757. } else {
  18758. state.texImage2D( 34069 + i$1, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18759. }
  18760. }
  18761. }
  18762. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18763. } else {
  18764. mipmaps = texture.mipmaps;
  18765. for ( var i$2 = 0; i$2 < 6; i$2 ++ ) {
  18766. if ( isDataTexture ) {
  18767. state.texImage2D( 34069 + i$2, 0, glInternalFormat, cubeImage[ i$2 ].width, cubeImage[ i$2 ].height, 0, glFormat, glType, cubeImage[ i$2 ].data );
  18768. for ( var j$1 = 0; j$1 < mipmaps.length; j$1 ++ ) {
  18769. var mipmap$1 = mipmaps[ j$1 ];
  18770. var mipmapImage = mipmap$1.image[ i$2 ].image;
  18771. state.texImage2D( 34069 + i$2, j$1 + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  18772. }
  18773. } else {
  18774. state.texImage2D( 34069 + i$2, 0, glInternalFormat, glFormat, glType, cubeImage[ i$2 ] );
  18775. for ( var j$2 = 0; j$2 < mipmaps.length; j$2 ++ ) {
  18776. var mipmap$2 = mipmaps[ j$2 ];
  18777. state.texImage2D( 34069 + i$2, j$2 + 1, glInternalFormat, glFormat, glType, mipmap$2.image[ i$2 ] );
  18778. }
  18779. }
  18780. }
  18781. textureProperties.__maxMipLevel = mipmaps.length;
  18782. }
  18783. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18784. // We assume images for cube map have the same size.
  18785. generateMipmap( 34067, texture, image.width, image.height );
  18786. }
  18787. textureProperties.__version = texture.version;
  18788. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18789. } else {
  18790. state.activeTexture( 33984 + slot );
  18791. state.bindTexture( 34067, textureProperties.__webglTexture );
  18792. }
  18793. }
  18794. function setTextureCubeDynamic( texture, slot ) {
  18795. state.activeTexture( 33984 + slot );
  18796. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  18797. }
  18798. var wrappingToGL = {};
  18799. wrappingToGL[ RepeatWrapping ] = 10497;
  18800. wrappingToGL[ ClampToEdgeWrapping ] = 33071;
  18801. wrappingToGL[ MirroredRepeatWrapping ] = 33648;
  18802. var filterToGL = {};
  18803. filterToGL[ NearestFilter ] = 9728;
  18804. filterToGL[ NearestMipmapNearestFilter ] = 9984;
  18805. filterToGL[ NearestMipmapLinearFilter ] = 9986;
  18806. filterToGL[ LinearFilter ] = 9729;
  18807. filterToGL[ LinearMipmapNearestFilter ] = 9985;
  18808. filterToGL[ LinearMipmapLinearFilter ] = 9987;
  18809. function setTextureParameters( textureType, texture, supportsMips ) {
  18810. if ( supportsMips ) {
  18811. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  18812. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  18813. if ( textureType === 32879 || textureType === 35866 ) {
  18814. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  18815. }
  18816. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  18817. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  18818. } else {
  18819. _gl.texParameteri( textureType, 10242, 33071 );
  18820. _gl.texParameteri( textureType, 10243, 33071 );
  18821. if ( textureType === 32879 || textureType === 35866 ) {
  18822. _gl.texParameteri( textureType, 32882, 33071 );
  18823. }
  18824. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  18825. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  18826. }
  18827. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  18828. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  18829. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  18830. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  18831. }
  18832. }
  18833. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  18834. if ( extension ) {
  18835. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; }
  18836. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; }
  18837. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  18838. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  18839. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  18840. }
  18841. }
  18842. }
  18843. function initTexture( textureProperties, texture ) {
  18844. if ( textureProperties.__webglInit === undefined ) {
  18845. textureProperties.__webglInit = true;
  18846. texture.addEventListener( 'dispose', onTextureDispose );
  18847. textureProperties.__webglTexture = _gl.createTexture();
  18848. info.memory.textures ++;
  18849. }
  18850. }
  18851. function uploadTexture( textureProperties, texture, slot ) {
  18852. var textureType = 3553;
  18853. if ( texture.isDataTexture2DArray ) { textureType = 35866; }
  18854. if ( texture.isDataTexture3D ) { textureType = 32879; }
  18855. initTexture( textureProperties, texture );
  18856. state.activeTexture( 33984 + slot );
  18857. state.bindTexture( textureType, textureProperties.__webglTexture );
  18858. _gl.pixelStorei( 37440, texture.flipY );
  18859. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  18860. _gl.pixelStorei( 3317, texture.unpackAlignment );
  18861. var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  18862. var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  18863. var supportsMips = isPowerOfTwo( image ) || isWebGL2,
  18864. glFormat = utils.convert( texture.format );
  18865. var glType = utils.convert( texture.type ),
  18866. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  18867. setTextureParameters( textureType, texture, supportsMips );
  18868. var mipmap;
  18869. var mipmaps = texture.mipmaps;
  18870. if ( texture.isDepthTexture ) {
  18871. // populate depth texture with dummy data
  18872. glInternalFormat = 6402;
  18873. if ( isWebGL2 ) {
  18874. if ( texture.type === FloatType ) {
  18875. glInternalFormat = 36012;
  18876. } else if ( texture.type === UnsignedIntType ) {
  18877. glInternalFormat = 33190;
  18878. } else if ( texture.type === UnsignedInt248Type ) {
  18879. glInternalFormat = 35056;
  18880. } else {
  18881. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  18882. }
  18883. } else {
  18884. if ( texture.type === FloatType ) {
  18885. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  18886. }
  18887. }
  18888. // validation checks for WebGL 1
  18889. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  18890. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18891. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  18892. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18893. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  18894. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  18895. texture.type = UnsignedShortType;
  18896. glType = utils.convert( texture.type );
  18897. }
  18898. }
  18899. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  18900. // Depth stencil textures need the DEPTH_STENCIL internal format
  18901. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18902. glInternalFormat = 34041;
  18903. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18904. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  18905. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18906. if ( texture.type !== UnsignedInt248Type ) {
  18907. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  18908. texture.type = UnsignedInt248Type;
  18909. glType = utils.convert( texture.type );
  18910. }
  18911. }
  18912. //
  18913. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  18914. } else if ( texture.isDataTexture ) {
  18915. // use manually created mipmaps if available
  18916. // if there are no manual mipmaps
  18917. // set 0 level mipmap and then use GL to generate other mipmap levels
  18918. if ( mipmaps.length > 0 && supportsMips ) {
  18919. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18920. mipmap = mipmaps[ i ];
  18921. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18922. }
  18923. texture.generateMipmaps = false;
  18924. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18925. } else {
  18926. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  18927. textureProperties.__maxMipLevel = 0;
  18928. }
  18929. } else if ( texture.isCompressedTexture ) {
  18930. for ( var i$1 = 0, il$1 = mipmaps.length; i$1 < il$1; i$1 ++ ) {
  18931. mipmap = mipmaps[ i$1 ];
  18932. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18933. if ( glFormat !== null ) {
  18934. state.compressedTexImage2D( 3553, i$1, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18935. } else {
  18936. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  18937. }
  18938. } else {
  18939. state.texImage2D( 3553, i$1, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18940. }
  18941. }
  18942. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18943. } else if ( texture.isDataTexture2DArray ) {
  18944. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18945. textureProperties.__maxMipLevel = 0;
  18946. } else if ( texture.isDataTexture3D ) {
  18947. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18948. textureProperties.__maxMipLevel = 0;
  18949. } else {
  18950. // regular Texture (image, video, canvas)
  18951. // use manually created mipmaps if available
  18952. // if there are no manual mipmaps
  18953. // set 0 level mipmap and then use GL to generate other mipmap levels
  18954. if ( mipmaps.length > 0 && supportsMips ) {
  18955. for ( var i$2 = 0, il$2 = mipmaps.length; i$2 < il$2; i$2 ++ ) {
  18956. mipmap = mipmaps[ i$2 ];
  18957. state.texImage2D( 3553, i$2, glInternalFormat, glFormat, glType, mipmap );
  18958. }
  18959. texture.generateMipmaps = false;
  18960. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18961. } else {
  18962. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  18963. textureProperties.__maxMipLevel = 0;
  18964. }
  18965. }
  18966. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18967. generateMipmap( textureType, texture, image.width, image.height );
  18968. }
  18969. textureProperties.__version = texture.version;
  18970. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18971. }
  18972. // Render targets
  18973. // Setup storage for target texture and bind it to correct framebuffer
  18974. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  18975. var glFormat = utils.convert( renderTarget.texture.format );
  18976. var glType = utils.convert( renderTarget.texture.type );
  18977. var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  18978. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  18979. _gl.bindFramebuffer( 36160, framebuffer );
  18980. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  18981. _gl.bindFramebuffer( 36160, null );
  18982. }
  18983. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  18984. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  18985. _gl.bindRenderbuffer( 36161, renderbuffer );
  18986. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  18987. var glInternalFormat = 33189;
  18988. if ( isMultisample ) {
  18989. var depthTexture = renderTarget.depthTexture;
  18990. if ( depthTexture && depthTexture.isDepthTexture ) {
  18991. if ( depthTexture.type === FloatType ) {
  18992. glInternalFormat = 36012;
  18993. } else if ( depthTexture.type === UnsignedIntType ) {
  18994. glInternalFormat = 33190;
  18995. }
  18996. }
  18997. var samples = getRenderTargetSamples( renderTarget );
  18998. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18999. } else {
  19000. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  19001. }
  19002. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  19003. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  19004. if ( isMultisample ) {
  19005. var samples$1 = getRenderTargetSamples( renderTarget );
  19006. _gl.renderbufferStorageMultisample( 36161, samples$1, 35056, renderTarget.width, renderTarget.height );
  19007. } else {
  19008. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  19009. }
  19010. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  19011. } else {
  19012. var glFormat = utils.convert( renderTarget.texture.format );
  19013. var glType = utils.convert( renderTarget.texture.type );
  19014. var glInternalFormat$1 = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  19015. if ( isMultisample ) {
  19016. var samples$2 = getRenderTargetSamples( renderTarget );
  19017. _gl.renderbufferStorageMultisample( 36161, samples$2, glInternalFormat$1, renderTarget.width, renderTarget.height );
  19018. } else {
  19019. _gl.renderbufferStorage( 36161, glInternalFormat$1, renderTarget.width, renderTarget.height );
  19020. }
  19021. }
  19022. _gl.bindRenderbuffer( 36161, null );
  19023. }
  19024. // Setup resources for a Depth Texture for a FBO (needs an extension)
  19025. function setupDepthTexture( framebuffer, renderTarget ) {
  19026. var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  19027. if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); }
  19028. _gl.bindFramebuffer( 36160, framebuffer );
  19029. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  19030. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  19031. }
  19032. // upload an empty depth texture with framebuffer size
  19033. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  19034. renderTarget.depthTexture.image.width !== renderTarget.width ||
  19035. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  19036. renderTarget.depthTexture.image.width = renderTarget.width;
  19037. renderTarget.depthTexture.image.height = renderTarget.height;
  19038. renderTarget.depthTexture.needsUpdate = true;
  19039. }
  19040. setTexture2D( renderTarget.depthTexture, 0 );
  19041. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  19042. if ( renderTarget.depthTexture.format === DepthFormat ) {
  19043. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  19044. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  19045. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  19046. } else {
  19047. throw new Error( 'Unknown depthTexture format' );
  19048. }
  19049. }
  19050. // Setup GL resources for a non-texture depth buffer
  19051. function setupDepthRenderbuffer( renderTarget ) {
  19052. var renderTargetProperties = properties.get( renderTarget );
  19053. var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  19054. if ( renderTarget.depthTexture ) {
  19055. if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); }
  19056. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  19057. } else {
  19058. if ( isCube ) {
  19059. renderTargetProperties.__webglDepthbuffer = [];
  19060. for ( var i = 0; i < 6; i ++ ) {
  19061. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  19062. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  19063. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  19064. }
  19065. } else {
  19066. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  19067. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  19068. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  19069. }
  19070. }
  19071. _gl.bindFramebuffer( 36160, null );
  19072. }
  19073. // Set up GL resources for the render target
  19074. function setupRenderTarget( renderTarget ) {
  19075. var renderTargetProperties = properties.get( renderTarget );
  19076. var textureProperties = properties.get( renderTarget.texture );
  19077. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  19078. textureProperties.__webglTexture = _gl.createTexture();
  19079. info.memory.textures ++;
  19080. var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  19081. var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  19082. var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  19083. // Handles WebGL2 RGBFormat fallback - #18858
  19084. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  19085. renderTarget.texture.format = RGBAFormat;
  19086. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  19087. }
  19088. // Setup framebuffer
  19089. if ( isCube ) {
  19090. renderTargetProperties.__webglFramebuffer = [];
  19091. for ( var i = 0; i < 6; i ++ ) {
  19092. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  19093. }
  19094. } else {
  19095. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  19096. if ( isMultisample ) {
  19097. if ( isWebGL2 ) {
  19098. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  19099. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  19100. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  19101. var glFormat = utils.convert( renderTarget.texture.format );
  19102. var glType = utils.convert( renderTarget.texture.type );
  19103. var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  19104. var samples = getRenderTargetSamples( renderTarget );
  19105. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  19106. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  19107. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  19108. _gl.bindRenderbuffer( 36161, null );
  19109. if ( renderTarget.depthBuffer ) {
  19110. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  19111. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  19112. }
  19113. _gl.bindFramebuffer( 36160, null );
  19114. } else {
  19115. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  19116. }
  19117. }
  19118. }
  19119. // Setup color buffer
  19120. if ( isCube ) {
  19121. state.bindTexture( 34067, textureProperties.__webglTexture );
  19122. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  19123. for ( var i$1 = 0; i$1 < 6; i$1 ++ ) {
  19124. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i$1 ], renderTarget, 36064, 34069 + i$1 );
  19125. }
  19126. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  19127. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  19128. }
  19129. state.bindTexture( 34067, null );
  19130. } else {
  19131. state.bindTexture( 3553, textureProperties.__webglTexture );
  19132. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  19133. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  19134. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  19135. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  19136. }
  19137. state.bindTexture( 3553, null );
  19138. }
  19139. // Setup depth and stencil buffers
  19140. if ( renderTarget.depthBuffer ) {
  19141. setupDepthRenderbuffer( renderTarget );
  19142. }
  19143. }
  19144. function updateRenderTargetMipmap( renderTarget ) {
  19145. var texture = renderTarget.texture;
  19146. var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  19147. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  19148. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  19149. var webglTexture = properties.get( texture ).__webglTexture;
  19150. state.bindTexture( target, webglTexture );
  19151. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  19152. state.bindTexture( target, null );
  19153. }
  19154. }
  19155. function updateMultisampleRenderTarget( renderTarget ) {
  19156. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  19157. if ( isWebGL2 ) {
  19158. var renderTargetProperties = properties.get( renderTarget );
  19159. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  19160. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  19161. var width = renderTarget.width;
  19162. var height = renderTarget.height;
  19163. var mask = 16384;
  19164. if ( renderTarget.depthBuffer ) { mask |= 256; }
  19165. if ( renderTarget.stencilBuffer ) { mask |= 1024; }
  19166. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  19167. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  19168. } else {
  19169. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  19170. }
  19171. }
  19172. }
  19173. function getRenderTargetSamples( renderTarget ) {
  19174. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  19175. Math.min( maxSamples, renderTarget.samples ) : 0;
  19176. }
  19177. function updateVideoTexture( texture ) {
  19178. var frame = info.render.frame;
  19179. // Check the last frame we updated the VideoTexture
  19180. if ( _videoTextures.get( texture ) !== frame ) {
  19181. _videoTextures.set( texture, frame );
  19182. texture.update();
  19183. }
  19184. }
  19185. // backwards compatibility
  19186. var warnedTexture2D = false;
  19187. var warnedTextureCube = false;
  19188. function safeSetTexture2D( texture, slot ) {
  19189. if ( texture && texture.isWebGLRenderTarget ) {
  19190. if ( warnedTexture2D === false ) {
  19191. console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
  19192. warnedTexture2D = true;
  19193. }
  19194. texture = texture.texture;
  19195. }
  19196. setTexture2D( texture, slot );
  19197. }
  19198. function safeSetTextureCube( texture, slot ) {
  19199. if ( texture && texture.isWebGLCubeRenderTarget ) {
  19200. if ( warnedTextureCube === false ) {
  19201. console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  19202. warnedTextureCube = true;
  19203. }
  19204. texture = texture.texture;
  19205. }
  19206. // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  19207. // TODO: unify these code paths
  19208. if ( ( texture && texture.isCubeTexture ) ||
  19209. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  19210. // CompressedTexture can have Array in image :/
  19211. // this function alone should take care of cube textures
  19212. setTextureCube( texture, slot );
  19213. } else {
  19214. // assumed: texture property of THREE.WebGLCubeRenderTarget
  19215. setTextureCubeDynamic( texture, slot );
  19216. }
  19217. }
  19218. //
  19219. this.allocateTextureUnit = allocateTextureUnit;
  19220. this.resetTextureUnits = resetTextureUnits;
  19221. this.setTexture2D = setTexture2D;
  19222. this.setTexture2DArray = setTexture2DArray;
  19223. this.setTexture3D = setTexture3D;
  19224. this.setTextureCube = setTextureCube;
  19225. this.setTextureCubeDynamic = setTextureCubeDynamic;
  19226. this.setupRenderTarget = setupRenderTarget;
  19227. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19228. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19229. this.safeSetTexture2D = safeSetTexture2D;
  19230. this.safeSetTextureCube = safeSetTextureCube;
  19231. }
  19232. function WebGLUtils( gl, extensions, capabilities ) {
  19233. var isWebGL2 = capabilities.isWebGL2;
  19234. function convert( p ) {
  19235. var extension;
  19236. if ( p === UnsignedByteType ) { return 5121; }
  19237. if ( p === UnsignedShort4444Type ) { return 32819; }
  19238. if ( p === UnsignedShort5551Type ) { return 32820; }
  19239. if ( p === UnsignedShort565Type ) { return 33635; }
  19240. if ( p === ByteType ) { return 5120; }
  19241. if ( p === ShortType ) { return 5122; }
  19242. if ( p === UnsignedShortType ) { return 5123; }
  19243. if ( p === IntType ) { return 5124; }
  19244. if ( p === UnsignedIntType ) { return 5125; }
  19245. if ( p === FloatType ) { return 5126; }
  19246. if ( p === HalfFloatType ) {
  19247. if ( isWebGL2 ) { return 5131; }
  19248. extension = extensions.get( 'OES_texture_half_float' );
  19249. if ( extension !== null ) {
  19250. return extension.HALF_FLOAT_OES;
  19251. } else {
  19252. return null;
  19253. }
  19254. }
  19255. if ( p === AlphaFormat ) { return 6406; }
  19256. if ( p === RGBFormat ) { return 6407; }
  19257. if ( p === RGBAFormat ) { return 6408; }
  19258. if ( p === LuminanceFormat ) { return 6409; }
  19259. if ( p === LuminanceAlphaFormat ) { return 6410; }
  19260. if ( p === DepthFormat ) { return 6402; }
  19261. if ( p === DepthStencilFormat ) { return 34041; }
  19262. if ( p === RedFormat ) { return 6403; }
  19263. // WebGL2 formats.
  19264. if ( p === RedIntegerFormat ) { return 36244; }
  19265. if ( p === RGFormat ) { return 33319; }
  19266. if ( p === RGIntegerFormat ) { return 33320; }
  19267. if ( p === RGBIntegerFormat ) { return 36248; }
  19268. if ( p === RGBAIntegerFormat ) { return 36249; }
  19269. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  19270. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  19271. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19272. if ( extension !== null ) {
  19273. if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; }
  19274. if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; }
  19275. if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; }
  19276. if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; }
  19277. } else {
  19278. return null;
  19279. }
  19280. }
  19281. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  19282. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  19283. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19284. if ( extension !== null ) {
  19285. if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; }
  19286. if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; }
  19287. if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; }
  19288. if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; }
  19289. } else {
  19290. return null;
  19291. }
  19292. }
  19293. if ( p === RGB_ETC1_Format ) {
  19294. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  19295. if ( extension !== null ) {
  19296. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19297. } else {
  19298. return null;
  19299. }
  19300. }
  19301. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  19302. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  19303. if ( extension !== null ) {
  19304. if ( p === RGB_ETC2_Format ) { return extension.COMPRESSED_RGB8_ETC2; }
  19305. if ( p === RGBA_ETC2_EAC_Format ) { return extension.COMPRESSED_RGBA8_ETC2_EAC; }
  19306. }
  19307. }
  19308. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  19309. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  19310. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  19311. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  19312. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  19313. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  19314. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  19315. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  19316. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  19317. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  19318. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  19319. if ( extension !== null ) {
  19320. // TODO Complete?
  19321. return p;
  19322. } else {
  19323. return null;
  19324. }
  19325. }
  19326. if ( p === RGBA_BPTC_Format ) {
  19327. extension = extensions.get( 'EXT_texture_compression_bptc' );
  19328. if ( extension !== null ) {
  19329. // TODO Complete?
  19330. return p;
  19331. } else {
  19332. return null;
  19333. }
  19334. }
  19335. if ( p === UnsignedInt248Type ) {
  19336. if ( isWebGL2 ) { return 34042; }
  19337. extension = extensions.get( 'WEBGL_depth_texture' );
  19338. if ( extension !== null ) {
  19339. return extension.UNSIGNED_INT_24_8_WEBGL;
  19340. } else {
  19341. return null;
  19342. }
  19343. }
  19344. }
  19345. return { convert: convert };
  19346. }
  19347. function Group() {
  19348. Object3D.call( this );
  19349. this.type = 'Group';
  19350. }
  19351. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19352. constructor: Group,
  19353. isGroup: true
  19354. } );
  19355. function ArrayCamera( array ) {
  19356. PerspectiveCamera.call( this );
  19357. this.cameras = array || [];
  19358. }
  19359. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  19360. constructor: ArrayCamera,
  19361. isArrayCamera: true
  19362. } );
  19363. /**
  19364. * @author jsantell / https://www.jsantell.com/
  19365. * @author mrdoob / http://mrdoob.com/
  19366. */
  19367. var cameraLPos = new Vector3();
  19368. var cameraRPos = new Vector3();
  19369. /**
  19370. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19371. * the cameras' projection and world matrices have already been set.
  19372. * And that near and far planes are identical for both cameras.
  19373. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19374. */
  19375. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  19376. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  19377. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  19378. var ipd = cameraLPos.distanceTo( cameraRPos );
  19379. var projL = cameraL.projectionMatrix.elements;
  19380. var projR = cameraR.projectionMatrix.elements;
  19381. // VR systems will have identical far and near planes, and
  19382. // most likely identical top and bottom frustum extents.
  19383. // Use the left camera for these values.
  19384. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  19385. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  19386. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  19387. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  19388. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  19389. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  19390. var left = near * leftFov;
  19391. var right = near * rightFov;
  19392. // Calculate the new camera's position offset from the
  19393. // left camera. xOffset should be roughly half `ipd`.
  19394. var zOffset = ipd / ( - leftFov + rightFov );
  19395. var xOffset = zOffset * - leftFov;
  19396. // TODO: Better way to apply this offset?
  19397. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  19398. camera.translateX( xOffset );
  19399. camera.translateZ( zOffset );
  19400. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  19401. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19402. // Find the union of the frustum values of the cameras and scale
  19403. // the values so that the near plane's position does not change in world space,
  19404. // although must now be relative to the new union camera.
  19405. var near2 = near + zOffset;
  19406. var far2 = far + zOffset;
  19407. var left2 = left - xOffset;
  19408. var right2 = right + ( ipd - xOffset );
  19409. var top2 = topFov * far / far2 * near2;
  19410. var bottom2 = bottomFov * far / far2 * near2;
  19411. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  19412. }
  19413. /**
  19414. * @author mrdoob / http://mrdoob.com/
  19415. */
  19416. function WebVRManager( renderer ) {
  19417. var renderWidth, renderHeight;
  19418. var scope = this;
  19419. var device = null;
  19420. var frameData = null;
  19421. var poseTarget = null;
  19422. var controllers = [];
  19423. var standingMatrix = new Matrix4();
  19424. var standingMatrixInverse = new Matrix4();
  19425. var framebufferScaleFactor = 1.0;
  19426. var referenceSpaceType = 'local-floor';
  19427. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  19428. frameData = new window.VRFrameData();
  19429. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  19430. }
  19431. var matrixWorldInverse = new Matrix4();
  19432. var tempQuaternion = new Quaternion();
  19433. var tempPosition = new Vector3();
  19434. var cameraL = new PerspectiveCamera();
  19435. cameraL.viewport = new Vector4();
  19436. cameraL.layers.enable( 1 );
  19437. var cameraR = new PerspectiveCamera();
  19438. cameraR.viewport = new Vector4();
  19439. cameraR.layers.enable( 2 );
  19440. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  19441. cameraVR.layers.enable( 1 );
  19442. cameraVR.layers.enable( 2 );
  19443. var currentSize = new Vector2(), currentPixelRatio;
  19444. function onVRDisplayPresentChange() {
  19445. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19446. if ( isPresenting ) {
  19447. var eyeParameters = device.getEyeParameters( 'left' );
  19448. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19449. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19450. currentPixelRatio = renderer.getPixelRatio();
  19451. renderer.getSize( currentSize );
  19452. renderer.setDrawingBufferSize( renderWidth, renderHeight, 1 );
  19453. cameraL.viewport.set( 0, 0, renderWidth / 2, renderHeight );
  19454. cameraR.viewport.set( renderWidth / 2, 0, renderWidth / 2, renderHeight );
  19455. animation.start();
  19456. scope.dispatchEvent( { type: 'sessionstart' } );
  19457. } else {
  19458. if ( scope.enabled ) {
  19459. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  19460. }
  19461. animation.stop();
  19462. scope.dispatchEvent( { type: 'sessionend' } );
  19463. }
  19464. }
  19465. //
  19466. var triggers = [];
  19467. var grips = [];
  19468. function findGamepad( id ) {
  19469. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19470. for ( var i = 0, l = gamepads.length; i < l; i ++ ) {
  19471. var gamepad = gamepads[ i ];
  19472. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  19473. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  19474. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  19475. gamepad.id.startsWith( 'HTC Vive Focus' ) ||
  19476. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  19477. var hand = gamepad.hand;
  19478. if ( id === 0 && ( hand === '' || hand === 'right' ) ) { return gamepad; }
  19479. if ( id === 1 && ( hand === 'left' ) ) { return gamepad; }
  19480. }
  19481. }
  19482. }
  19483. function updateControllers() {
  19484. for ( var i = 0; i < controllers.length; i ++ ) {
  19485. var controller = controllers[ i ];
  19486. var gamepad = findGamepad( i );
  19487. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  19488. if ( gamepad.pose === null ) { return; }
  19489. // Pose
  19490. var pose = gamepad.pose;
  19491. if ( pose.hasPosition === false ) { controller.position.set( 0.2, - 0.6, - 0.05 ); }
  19492. if ( pose.position !== null ) { controller.position.fromArray( pose.position ); }
  19493. if ( pose.orientation !== null ) { controller.quaternion.fromArray( pose.orientation ); }
  19494. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  19495. controller.matrix.premultiply( standingMatrix );
  19496. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  19497. controller.matrixWorldNeedsUpdate = true;
  19498. controller.visible = true;
  19499. // Trigger
  19500. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19501. if ( triggers[ i ] === undefined ) { triggers[ i ] = false; }
  19502. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  19503. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  19504. if ( triggers[ i ] === true ) {
  19505. controller.dispatchEvent( { type: 'selectstart' } );
  19506. } else {
  19507. controller.dispatchEvent( { type: 'selectend' } );
  19508. controller.dispatchEvent( { type: 'select' } );
  19509. }
  19510. }
  19511. // Grip
  19512. buttonId = 2;
  19513. if ( grips[ i ] === undefined ) { grips[ i ] = false; }
  19514. // Skip if the grip button doesn't exist on this controller
  19515. if ( gamepad.buttons[ buttonId ] !== undefined ) {
  19516. if ( grips[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  19517. grips[ i ] = gamepad.buttons[ buttonId ].pressed;
  19518. if ( grips[ i ] === true ) {
  19519. controller.dispatchEvent( { type: 'squeezestart' } );
  19520. } else {
  19521. controller.dispatchEvent( { type: 'squeezeend' } );
  19522. controller.dispatchEvent( { type: 'squeeze' } );
  19523. }
  19524. }
  19525. }
  19526. } else {
  19527. controller.visible = false;
  19528. }
  19529. }
  19530. }
  19531. function updateViewportFromBounds( viewport, bounds ) {
  19532. if ( bounds !== null && bounds.length === 4 ) {
  19533. viewport.set( bounds[ 0 ] * renderWidth, bounds[ 1 ] * renderHeight, bounds[ 2 ] * renderWidth, bounds[ 3 ] * renderHeight );
  19534. }
  19535. }
  19536. //
  19537. this.enabled = false;
  19538. this.getController = function ( id ) {
  19539. var controller = controllers[ id ];
  19540. if ( controller === undefined ) {
  19541. controller = new Group();
  19542. controller.matrixAutoUpdate = false;
  19543. controller.visible = false;
  19544. controllers[ id ] = controller;
  19545. }
  19546. return controller;
  19547. };
  19548. this.getDevice = function () {
  19549. return device;
  19550. };
  19551. this.setDevice = function ( value ) {
  19552. if ( value !== undefined ) { device = value; }
  19553. animation.setContext( value );
  19554. };
  19555. this.setFramebufferScaleFactor = function ( value ) {
  19556. framebufferScaleFactor = value;
  19557. };
  19558. this.setReferenceSpaceType = function ( value ) {
  19559. referenceSpaceType = value;
  19560. };
  19561. this.setPoseTarget = function ( object ) {
  19562. if ( object !== undefined ) { poseTarget = object; }
  19563. };
  19564. this.getCamera = function ( camera ) {
  19565. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19566. device.depthNear = camera.near;
  19567. device.depthFar = camera.far;
  19568. device.getFrameData( frameData );
  19569. //
  19570. if ( referenceSpaceType === 'local-floor' ) {
  19571. var stageParameters = device.stageParameters;
  19572. if ( stageParameters ) {
  19573. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  19574. } else {
  19575. standingMatrix.makeTranslation( 0, userHeight, 0 );
  19576. }
  19577. }
  19578. var pose = frameData.pose;
  19579. var poseObject = poseTarget !== null ? poseTarget : camera;
  19580. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19581. poseObject.matrix.copy( standingMatrix );
  19582. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  19583. if ( pose.orientation !== null ) {
  19584. tempQuaternion.fromArray( pose.orientation );
  19585. poseObject.quaternion.multiply( tempQuaternion );
  19586. }
  19587. if ( pose.position !== null ) {
  19588. tempQuaternion.setFromRotationMatrix( standingMatrix );
  19589. tempPosition.fromArray( pose.position );
  19590. tempPosition.applyQuaternion( tempQuaternion );
  19591. poseObject.position.add( tempPosition );
  19592. }
  19593. poseObject.updateMatrixWorld();
  19594. var children = poseObject.children;
  19595. for ( var i = 0, l = children.length; i < l; i ++ ) {
  19596. children[ i ].updateMatrixWorld( true );
  19597. }
  19598. //
  19599. cameraL.near = camera.near;
  19600. cameraR.near = camera.near;
  19601. cameraL.far = camera.far;
  19602. cameraR.far = camera.far;
  19603. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  19604. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  19605. // TODO (mrdoob) Double check this code
  19606. standingMatrixInverse.getInverse( standingMatrix );
  19607. if ( referenceSpaceType === 'local-floor' ) {
  19608. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  19609. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  19610. }
  19611. var parent = poseObject.parent;
  19612. if ( parent !== null ) {
  19613. matrixWorldInverse.getInverse( parent.matrixWorld );
  19614. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  19615. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  19616. }
  19617. // envMap and Mirror needs camera.matrixWorld
  19618. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  19619. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  19620. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  19621. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  19622. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  19623. //
  19624. var layers = device.getLayers();
  19625. if ( layers.length ) {
  19626. var layer = layers[ 0 ];
  19627. updateViewportFromBounds( cameraL.viewport, layer.leftBounds );
  19628. updateViewportFromBounds( cameraR.viewport, layer.rightBounds );
  19629. }
  19630. updateControllers();
  19631. return cameraVR;
  19632. };
  19633. this.getStandingMatrix = function () {
  19634. return standingMatrix;
  19635. };
  19636. this.isPresenting = false;
  19637. // Animation Loop
  19638. var animation = new WebGLAnimation();
  19639. this.setAnimationLoop = function ( callback ) {
  19640. animation.setAnimationLoop( callback );
  19641. if ( this.isPresenting ) { animation.start(); }
  19642. };
  19643. this.submitFrame = function () {
  19644. if ( this.isPresenting ) { device.submitFrame(); }
  19645. };
  19646. this.dispose = function () {
  19647. if ( typeof window !== 'undefined' ) {
  19648. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  19649. }
  19650. };
  19651. // DEPRECATED
  19652. this.setFrameOfReferenceType = function () {
  19653. console.warn( 'THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.' );
  19654. };
  19655. }
  19656. Object.assign( WebVRManager.prototype, EventDispatcher.prototype );
  19657. function WebXRController() {
  19658. this._targetRay = null;
  19659. this._grip = null;
  19660. this._hand = null;
  19661. }
  19662. Object.assign( WebXRController.prototype, {
  19663. constructor: WebXRController,
  19664. getHandSpace: function () {
  19665. if ( this._hand === null ) {
  19666. this._hand = new Group();
  19667. this._hand.matrixAutoUpdate = false;
  19668. this._hand.visible = false;
  19669. this._hand.joints = [];
  19670. this._hand.inputState = { pinching: false };
  19671. if ( window.XRHand ) {
  19672. for ( var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  19673. // The transform of this joint will be updated with the joint pose on each frame
  19674. var joint = new Group();
  19675. joint.matrixAutoUpdate = false;
  19676. joint.visible = false;
  19677. this._hand.joints.push( joint );
  19678. // ??
  19679. this._hand.add( joint );
  19680. }
  19681. }
  19682. }
  19683. return this._hand;
  19684. },
  19685. getTargetRaySpace: function () {
  19686. if ( this._targetRay === null ) {
  19687. this._targetRay = new Group();
  19688. this._targetRay.matrixAutoUpdate = false;
  19689. this._targetRay.visible = false;
  19690. }
  19691. return this._targetRay;
  19692. },
  19693. getGripSpace: function () {
  19694. if ( this._grip === null ) {
  19695. this._grip = new Group();
  19696. this._grip.matrixAutoUpdate = false;
  19697. this._grip.visible = false;
  19698. }
  19699. return this._grip;
  19700. },
  19701. dispatchEvent: function ( event ) {
  19702. if ( this._targetRay !== null ) {
  19703. this._targetRay.dispatchEvent( event );
  19704. }
  19705. if ( this._grip !== null ) {
  19706. this._grip.dispatchEvent( event );
  19707. }
  19708. if ( this._hand !== null ) {
  19709. this._hand.dispatchEvent( event );
  19710. }
  19711. return this;
  19712. },
  19713. disconnect: function ( inputSource ) {
  19714. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19715. if ( this._targetRay !== null ) {
  19716. this._targetRay.visible = false;
  19717. }
  19718. if ( this._grip !== null ) {
  19719. this._grip.visible = false;
  19720. }
  19721. if ( this._hand !== null ) {
  19722. this._hand.visible = false;
  19723. }
  19724. return this;
  19725. },
  19726. update: function ( inputSource, frame, referenceSpace ) {
  19727. var inputPose = null;
  19728. var gripPose = null;
  19729. var handPose = null;
  19730. var targetRay = this._targetRay;
  19731. var grip = this._grip;
  19732. var hand = this._hand;
  19733. if ( inputSource ) {
  19734. if ( inputSource.hand ) {
  19735. handPose = true;
  19736. for ( var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  19737. if ( inputSource.hand[ i ] ) {
  19738. // Update the joints groups with the XRJoint poses
  19739. var jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  19740. var joint = hand.joints[ i ];
  19741. if ( jointPose !== null ) {
  19742. joint.matrix.fromArray( jointPose.transform.matrix );
  19743. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  19744. joint.jointRadius = jointPose.radius;
  19745. }
  19746. joint.visible = jointPose !== null;
  19747. // Custom events
  19748. // Check pinch
  19749. var indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  19750. var thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  19751. var distance = indexTip.position.distanceTo( thumbTip.position );
  19752. var distanceToPinch = 0.02;
  19753. var threshold = 0.005;
  19754. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  19755. hand.inputState.pinching = false;
  19756. this.dispatchEvent( {
  19757. type: "pinchend",
  19758. handedness: inputSource.handedness,
  19759. target: this
  19760. } );
  19761. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  19762. hand.inputState.pinching = true;
  19763. this.dispatchEvent( {
  19764. type: "pinchstart",
  19765. handedness: inputSource.handedness,
  19766. target: this
  19767. } );
  19768. }
  19769. }
  19770. }
  19771. } else {
  19772. if ( targetRay !== null ) {
  19773. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  19774. if ( inputPose !== null ) {
  19775. targetRay.matrix.fromArray( inputPose.transform.matrix );
  19776. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  19777. }
  19778. }
  19779. if ( grip !== null && inputSource.gripSpace ) {
  19780. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  19781. if ( gripPose !== null ) {
  19782. grip.matrix.fromArray( gripPose.transform.matrix );
  19783. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  19784. }
  19785. }
  19786. }
  19787. }
  19788. if ( targetRay !== null ) {
  19789. targetRay.visible = ( inputPose !== null );
  19790. }
  19791. if ( grip !== null ) {
  19792. grip.visible = ( gripPose !== null );
  19793. }
  19794. if ( hand !== null ) {
  19795. hand.visible = ( handPose !== null );
  19796. }
  19797. return this;
  19798. }
  19799. } );
  19800. function WebXRManager( renderer, gl ) {
  19801. var scope = this;
  19802. var session = null;
  19803. var framebufferScaleFactor = 1.0;
  19804. var referenceSpace = null;
  19805. var referenceSpaceType = 'local-floor';
  19806. var pose = null;
  19807. var poseTarget = null;
  19808. var controllers = [];
  19809. var inputSourcesMap = new Map();
  19810. //
  19811. var cameraL = new PerspectiveCamera();
  19812. cameraL.layers.enable( 1 );
  19813. cameraL.viewport = new Vector4();
  19814. var cameraR = new PerspectiveCamera();
  19815. cameraR.layers.enable( 2 );
  19816. cameraR.viewport = new Vector4();
  19817. var cameras = [ cameraL, cameraR ];
  19818. var cameraVR = new ArrayCamera();
  19819. cameraVR.layers.enable( 1 );
  19820. cameraVR.layers.enable( 2 );
  19821. var _currentDepthNear = null;
  19822. var _currentDepthFar = null;
  19823. //
  19824. this.enabled = false;
  19825. this.isPresenting = false;
  19826. this.getCameraPose = function ( ) {
  19827. return pose;
  19828. };
  19829. this.getController = function ( id ) {
  19830. var controller = controllers[ index ];
  19831. if ( controller === undefined ) {
  19832. controller = new WebXRController();
  19833. controllers[ index ] = controller;
  19834. }
  19835. return controller.getTargetRaySpace();
  19836. };
  19837. this.getControllerGrip = function ( index ) {
  19838. var controller = controllers[ index ];
  19839. if ( controller === undefined ) {
  19840. controller = new WebXRController();
  19841. controllers[ index ] = controller;
  19842. }
  19843. return controller.getGripSpace();
  19844. };
  19845. this.getHand = function ( index ) {
  19846. var controller = controllers[ index ];
  19847. if ( controller === undefined ) {
  19848. controller = new WebXRController();
  19849. controllers[ index ] = controller;
  19850. }
  19851. return controller.getHandSpace();
  19852. };
  19853. //
  19854. function onSessionEvent( event ) {
  19855. var controller = inputSourcesMap.get( event.inputSource );
  19856. if ( controller ) {
  19857. controller.dispatchEvent( { type: event.type } );
  19858. }
  19859. }
  19860. function onSessionEnd() {
  19861. inputSourcesMap.forEach( function ( controller, inputSource ) {
  19862. controller.disconnect( inputSource );
  19863. } );
  19864. inputSourcesMap.clear();
  19865. //
  19866. renderer.setFramebuffer( null );
  19867. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  19868. animation.stop();
  19869. scope.isPresenting = false;
  19870. scope.dispatchEvent( { type: 'sessionend' } );
  19871. }
  19872. function onRequestReferenceSpace( value ) {
  19873. referenceSpace = value;
  19874. animation.setContext( session );
  19875. animation.start();
  19876. scope.isPresenting = true;
  19877. scope.dispatchEvent( { type: 'sessionstart' } );
  19878. }
  19879. this.setFramebufferScaleFactor = function ( value ) {
  19880. framebufferScaleFactor = value;
  19881. if ( scope.isPresenting === true ) {
  19882. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  19883. }
  19884. };
  19885. this.setReferenceSpaceType = function ( value ) {
  19886. referenceSpaceType = value;
  19887. if ( scope.isPresenting === true ) {
  19888. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  19889. }
  19890. };
  19891. this.getReferenceSpace = function () {
  19892. return referenceSpace;
  19893. };
  19894. this.getSession = function () {
  19895. return session;
  19896. };
  19897. this.setSession = function ( value ) {
  19898. session = value;
  19899. if ( session !== null ) {
  19900. session.addEventListener( 'select', onSessionEvent );
  19901. session.addEventListener( 'selectstart', onSessionEvent );
  19902. session.addEventListener( 'selectend', onSessionEvent );
  19903. session.addEventListener( 'squeeze', onSessionEvent );
  19904. session.addEventListener( 'squeezestart', onSessionEvent );
  19905. session.addEventListener( 'squeezeend', onSessionEvent );
  19906. session.addEventListener( 'end', onSessionEnd );
  19907. var attributes = gl.getContextAttributes();
  19908. if ( attributes.xrCompatible !== true ) {
  19909. gl.makeXRCompatible();
  19910. }
  19911. var layerInit = {
  19912. antialias: attributes.antialias,
  19913. alpha: attributes.alpha,
  19914. depth: attributes.depth,
  19915. stencil: attributes.stencil,
  19916. framebufferScaleFactor: framebufferScaleFactor
  19917. };
  19918. // eslint-disable-next-line no-undef
  19919. var baseLayer = new XRWebGLLayer( session, gl, layerInit );
  19920. session.updateRenderState( { baseLayer: baseLayer } );
  19921. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  19922. //
  19923. session.addEventListener( 'inputsourceschange', updateInputSources );
  19924. }
  19925. };
  19926. function updateInputSources( event ) {
  19927. var inputSources = session.inputSources;
  19928. // Assign inputSources to available controllers
  19929. for ( var i = 0; i < controllers.length; i ++ ) {
  19930. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  19931. }
  19932. // Notify disconnected
  19933. for ( var i$1 = 0; i$1 < event.removed.length; i$1 ++ ) {
  19934. var inputSource = event.removed[ i$1 ];
  19935. var controller = inputSourcesMap.get( inputSource );
  19936. if ( controller ) {
  19937. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19938. inputSourcesMap.delete( inputSource );
  19939. }
  19940. }
  19941. // Notify connected
  19942. for ( var i$2 = 0; i$2 < event.added.length; i$2 ++ ) {
  19943. var inputSource$1 = event.added[ i$2 ];
  19944. var controller$1 = inputSourcesMap.get( inputSource$1 );
  19945. if ( controller$1 ) {
  19946. controller$1.dispatchEvent( { type: 'connected', data: inputSource$1 } );
  19947. }
  19948. }
  19949. }
  19950. //
  19951. var cameraLPos = new Vector3();
  19952. var cameraRPos = new Vector3();
  19953. /**
  19954. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19955. * the cameras' projection and world matrices have already been set.
  19956. * And that near and far planes are identical for both cameras.
  19957. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19958. */
  19959. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  19960. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  19961. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  19962. var ipd = cameraLPos.distanceTo( cameraRPos );
  19963. var projL = cameraL.projectionMatrix.elements;
  19964. var projR = cameraR.projectionMatrix.elements;
  19965. // VR systems will have identical far and near planes, and
  19966. // most likely identical top and bottom frustum extents.
  19967. // Use the left camera for these values.
  19968. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  19969. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  19970. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  19971. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  19972. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  19973. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  19974. var left = near * leftFov;
  19975. var right = near * rightFov;
  19976. // Calculate the new camera's position offset from the
  19977. // left camera. xOffset should be roughly half `ipd`.
  19978. var zOffset = ipd / ( - leftFov + rightFov );
  19979. var xOffset = zOffset * - leftFov;
  19980. // TODO: Better way to apply this offset?
  19981. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  19982. camera.translateX( xOffset );
  19983. camera.translateZ( zOffset );
  19984. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  19985. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19986. // Find the union of the frustum values of the cameras and scale
  19987. // the values so that the near plane's position does not change in world space,
  19988. // although must now be relative to the new union camera.
  19989. var near2 = near + zOffset;
  19990. var far2 = far + zOffset;
  19991. var left2 = left - xOffset;
  19992. var right2 = right + ( ipd - xOffset );
  19993. var top2 = topFov * far / far2 * near2;
  19994. var bottom2 = bottomFov * far / far2 * near2;
  19995. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  19996. }
  19997. function updateCamera( camera, parent ) {
  19998. if ( parent === null ) {
  19999. camera.matrixWorld.copy( camera.matrix );
  20000. } else {
  20001. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  20002. }
  20003. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20004. }
  20005. this.setPoseTarget = function ( object ) {
  20006. if ( object !== undefined ) { poseTarget = object; }
  20007. };
  20008. this.getCamera = function ( camera ) {
  20009. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  20010. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  20011. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  20012. // Note that the new renderState won't apply until the next frame. See #18320
  20013. session.updateRenderState( {
  20014. depthNear: cameraVR.near,
  20015. depthFar: cameraVR.far
  20016. } );
  20017. _currentDepthNear = cameraVR.near;
  20018. _currentDepthFar = cameraVR.far;
  20019. }
  20020. var parent = camera.parent;
  20021. var cameras = cameraVR.cameras;
  20022. var object = poseTarget || camera;
  20023. updateCamera( cameraVR, parent );
  20024. for ( var i = 0; i < cameras.length; i ++ ) {
  20025. updateCamera( cameras[ i ], parent );
  20026. }
  20027. // update camera and its children
  20028. object.matrixWorld.copy( cameraVR.matrixWorld );
  20029. var children = object.children;
  20030. for ( var i$1 = 0, l = children.length; i$1 < l; i$1 ++ ) {
  20031. children[ i$1 ].updateMatrixWorld( true );
  20032. }
  20033. // update projection matrix for proper view frustum culling
  20034. if ( cameras.length === 2 ) {
  20035. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  20036. } else {
  20037. // assume single camera setup (AR)
  20038. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  20039. }
  20040. return cameraVR;
  20041. };
  20042. // Animation Loop
  20043. var onAnimationFrameCallback = null;
  20044. function onAnimationFrame( time, frame ) {
  20045. pose = frame.getViewerPose( referenceSpace );
  20046. if ( pose !== null ) {
  20047. var views = pose.views;
  20048. var baseLayer = session.renderState.baseLayer;
  20049. renderer.setFramebuffer( baseLayer.framebuffer );
  20050. var cameraVRNeedsUpdate = false;
  20051. // check if it's necessary to rebuild cameraVR's camera list
  20052. if ( views.length !== cameraVR.cameras.length ) {
  20053. cameraVR.cameras.length = 0;
  20054. cameraVRNeedsUpdate = true;
  20055. }
  20056. for ( var i = 0; i < views.length; i ++ ) {
  20057. var view = views[ i ];
  20058. var viewport = baseLayer.getViewport( view );
  20059. var camera = cameras[ i ];
  20060. camera.matrix.fromArray( view.transform.matrix );
  20061. camera.projectionMatrix.fromArray( view.projectionMatrix );
  20062. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  20063. if ( i === 0 ) {
  20064. cameraVR.matrix.copy( camera.matrix );
  20065. }
  20066. if ( cameraVRNeedsUpdate === true ) {
  20067. cameraVR.cameras.push( camera );
  20068. }
  20069. }
  20070. }
  20071. //
  20072. var inputSources = session.inputSources;
  20073. for ( var i$1 = 0; i$1 < controllers.length; i$1 ++ ) {
  20074. var controller = controllers[ i$1 ];
  20075. var inputSource = inputSources[ i$1 ];
  20076. controller.update( inputSource, frame, referenceSpace );
  20077. }
  20078. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame ); }
  20079. }
  20080. var animation = new WebGLAnimation();
  20081. animation.setAnimationLoop( onAnimationFrame );
  20082. this.setAnimationLoop = function ( callback ) {
  20083. onAnimationFrameCallback = callback;
  20084. };
  20085. this.dispose = function () {};
  20086. }
  20087. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  20088. function WebGLMaterials( properties ) {
  20089. function refreshFogUniforms( uniforms, fog ) {
  20090. uniforms.fogColor.value.copy( fog.color );
  20091. if ( fog.isFog ) {
  20092. uniforms.fogNear.value = fog.near;
  20093. uniforms.fogFar.value = fog.far;
  20094. } else if ( fog.isFogExp2 ) {
  20095. uniforms.fogDensity.value = fog.density;
  20096. }
  20097. }
  20098. function refreshMaterialUniforms( uniforms, material, environment, pixelRatio, height ) {
  20099. if ( material.isMeshBasicMaterial ) {
  20100. refreshUniformsCommon( uniforms, material );
  20101. } else if ( material.isMeshLambertMaterial ) {
  20102. refreshUniformsCommon( uniforms, material );
  20103. refreshUniformsLambert( uniforms, material );
  20104. } else if ( material.isMeshToonMaterial ) {
  20105. refreshUniformsCommon( uniforms, material );
  20106. refreshUniformsToon( uniforms, material );
  20107. } else if ( material.isMeshPhongMaterial ) {
  20108. refreshUniformsCommon( uniforms, material );
  20109. refreshUniformsPhong( uniforms, material );
  20110. } else if ( material.isMeshStandardMaterial ) {
  20111. refreshUniformsCommon( uniforms, material, environment );
  20112. if ( material.isMeshPhysicalMaterial ) {
  20113. refreshUniformsPhysical( uniforms, material, environment );
  20114. } else {
  20115. refreshUniformsStandard( uniforms, material, environment );
  20116. }
  20117. } else if ( material.isMeshMatcapMaterial ) {
  20118. refreshUniformsCommon( uniforms, material );
  20119. refreshUniformsMatcap( uniforms, material );
  20120. } else if ( material.isMeshDepthMaterial ) {
  20121. refreshUniformsCommon( uniforms, material );
  20122. refreshUniformsDepth( uniforms, material );
  20123. } else if ( material.isMeshDistanceMaterial ) {
  20124. refreshUniformsCommon( uniforms, material );
  20125. refreshUniformsDistance( uniforms, material );
  20126. } else if ( material.isMeshNormalMaterial ) {
  20127. refreshUniformsCommon( uniforms, material );
  20128. refreshUniformsNormal( uniforms, material );
  20129. } else if ( material.isLineBasicMaterial ) {
  20130. refreshUniformsLine( uniforms, material );
  20131. if ( material.isLineDashedMaterial ) {
  20132. refreshUniformsDash( uniforms, material );
  20133. }
  20134. } else if ( material.isPointsMaterial ) {
  20135. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  20136. } else if ( material.isSpriteMaterial ) {
  20137. refreshUniformsSprites( uniforms, material );
  20138. } else if ( material.isShadowMaterial ) {
  20139. uniforms.color.value.copy( material.color );
  20140. uniforms.opacity.value = material.opacity;
  20141. } else if ( material.isShaderMaterial ) {
  20142. material.uniformsNeedUpdate = false; // #15581
  20143. }
  20144. }
  20145. function refreshUniformsCommon( uniforms, material, environment ) {
  20146. uniforms.opacity.value = material.opacity;
  20147. if ( material.color ) {
  20148. uniforms.diffuse.value.copy( material.color );
  20149. }
  20150. if ( material.emissive ) {
  20151. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  20152. }
  20153. if ( material.map ) {
  20154. uniforms.map.value = material.map;
  20155. }
  20156. if ( material.alphaMap ) {
  20157. uniforms.alphaMap.value = material.alphaMap;
  20158. }
  20159. if ( material.specularMap ) {
  20160. uniforms.specularMap.value = material.specularMap;
  20161. }
  20162. var envMap = material.envMap || environment;
  20163. if ( envMap ) {
  20164. uniforms.envMap.value = envMap;
  20165. uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;
  20166. uniforms.reflectivity.value = material.reflectivity;
  20167. uniforms.refractionRatio.value = material.refractionRatio;
  20168. var maxMipLevel = properties.get( envMap ).__maxMipLevel;
  20169. if ( maxMipLevel !== undefined ) {
  20170. uniforms.maxMipLevel.value = maxMipLevel;
  20171. }
  20172. }
  20173. if ( material.lightMap ) {
  20174. uniforms.lightMap.value = material.lightMap;
  20175. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  20176. }
  20177. if ( material.aoMap ) {
  20178. uniforms.aoMap.value = material.aoMap;
  20179. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  20180. }
  20181. // uv repeat and offset setting priorities
  20182. // 1. color map
  20183. // 2. specular map
  20184. // 3. normal map
  20185. // 4. bump map
  20186. // 5. alpha map
  20187. // 6. emissive map
  20188. var uvScaleMap;
  20189. if ( material.map ) {
  20190. uvScaleMap = material.map;
  20191. } else if ( material.specularMap ) {
  20192. uvScaleMap = material.specularMap;
  20193. } else if ( material.displacementMap ) {
  20194. uvScaleMap = material.displacementMap;
  20195. } else if ( material.normalMap ) {
  20196. uvScaleMap = material.normalMap;
  20197. } else if ( material.bumpMap ) {
  20198. uvScaleMap = material.bumpMap;
  20199. } else if ( material.roughnessMap ) {
  20200. uvScaleMap = material.roughnessMap;
  20201. } else if ( material.metalnessMap ) {
  20202. uvScaleMap = material.metalnessMap;
  20203. } else if ( material.alphaMap ) {
  20204. uvScaleMap = material.alphaMap;
  20205. } else if ( material.emissiveMap ) {
  20206. uvScaleMap = material.emissiveMap;
  20207. }
  20208. if ( uvScaleMap !== undefined ) {
  20209. // backwards compatibility
  20210. if ( uvScaleMap.isWebGLRenderTarget ) {
  20211. uvScaleMap = uvScaleMap.texture;
  20212. }
  20213. if ( uvScaleMap.matrixAutoUpdate === true ) {
  20214. uvScaleMap.updateMatrix();
  20215. }
  20216. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  20217. }
  20218. // uv repeat and offset setting priorities for uv2
  20219. // 1. ao map
  20220. // 2. light map
  20221. var uv2ScaleMap;
  20222. if ( material.aoMap ) {
  20223. uv2ScaleMap = material.aoMap;
  20224. } else if ( material.lightMap ) {
  20225. uv2ScaleMap = material.lightMap;
  20226. }
  20227. if ( uv2ScaleMap !== undefined ) {
  20228. // backwards compatibility
  20229. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  20230. uv2ScaleMap = uv2ScaleMap.texture;
  20231. }
  20232. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  20233. uv2ScaleMap.updateMatrix();
  20234. }
  20235. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  20236. }
  20237. }
  20238. function refreshUniformsLine( uniforms, material ) {
  20239. uniforms.diffuse.value.copy( material.color );
  20240. uniforms.opacity.value = material.opacity;
  20241. }
  20242. function refreshUniformsDash( uniforms, material ) {
  20243. uniforms.dashSize.value = material.dashSize;
  20244. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20245. uniforms.scale.value = material.scale;
  20246. }
  20247. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  20248. uniforms.diffuse.value.copy( material.color );
  20249. uniforms.opacity.value = material.opacity;
  20250. uniforms.size.value = material.size * pixelRatio;
  20251. uniforms.scale.value = height * 0.5;
  20252. if ( material.map ) {
  20253. uniforms.map.value = material.map;
  20254. }
  20255. if ( material.alphaMap ) {
  20256. uniforms.alphaMap.value = material.alphaMap;
  20257. }
  20258. // uv repeat and offset setting priorities
  20259. // 1. color map
  20260. // 2. alpha map
  20261. var uvScaleMap;
  20262. if ( material.map ) {
  20263. uvScaleMap = material.map;
  20264. } else if ( material.alphaMap ) {
  20265. uvScaleMap = material.alphaMap;
  20266. }
  20267. if ( uvScaleMap !== undefined ) {
  20268. if ( uvScaleMap.matrixAutoUpdate === true ) {
  20269. uvScaleMap.updateMatrix();
  20270. }
  20271. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  20272. }
  20273. }
  20274. function refreshUniformsSprites( uniforms, material ) {
  20275. uniforms.diffuse.value.copy( material.color );
  20276. uniforms.opacity.value = material.opacity;
  20277. uniforms.rotation.value = material.rotation;
  20278. if ( material.map ) {
  20279. uniforms.map.value = material.map;
  20280. }
  20281. if ( material.alphaMap ) {
  20282. uniforms.alphaMap.value = material.alphaMap;
  20283. }
  20284. // uv repeat and offset setting priorities
  20285. // 1. color map
  20286. // 2. alpha map
  20287. var uvScaleMap;
  20288. if ( material.map ) {
  20289. uvScaleMap = material.map;
  20290. } else if ( material.alphaMap ) {
  20291. uvScaleMap = material.alphaMap;
  20292. }
  20293. if ( uvScaleMap !== undefined ) {
  20294. if ( uvScaleMap.matrixAutoUpdate === true ) {
  20295. uvScaleMap.updateMatrix();
  20296. }
  20297. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  20298. }
  20299. }
  20300. function refreshUniformsLambert( uniforms, material ) {
  20301. if ( material.emissiveMap ) {
  20302. uniforms.emissiveMap.value = material.emissiveMap;
  20303. }
  20304. }
  20305. function refreshUniformsPhong( uniforms, material ) {
  20306. uniforms.specular.value.copy( material.specular );
  20307. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  20308. if ( material.emissiveMap ) {
  20309. uniforms.emissiveMap.value = material.emissiveMap;
  20310. }
  20311. if ( material.bumpMap ) {
  20312. uniforms.bumpMap.value = material.bumpMap;
  20313. uniforms.bumpScale.value = material.bumpScale;
  20314. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20315. }
  20316. if ( material.normalMap ) {
  20317. uniforms.normalMap.value = material.normalMap;
  20318. uniforms.normalScale.value.copy( material.normalScale );
  20319. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20320. }
  20321. if ( material.displacementMap ) {
  20322. uniforms.displacementMap.value = material.displacementMap;
  20323. uniforms.displacementScale.value = material.displacementScale;
  20324. uniforms.displacementBias.value = material.displacementBias;
  20325. }
  20326. }
  20327. function refreshUniformsToon( uniforms, material ) {
  20328. if ( material.gradientMap ) {
  20329. uniforms.gradientMap.value = material.gradientMap;
  20330. }
  20331. if ( material.emissiveMap ) {
  20332. uniforms.emissiveMap.value = material.emissiveMap;
  20333. }
  20334. if ( material.bumpMap ) {
  20335. uniforms.bumpMap.value = material.bumpMap;
  20336. uniforms.bumpScale.value = material.bumpScale;
  20337. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20338. }
  20339. if ( material.normalMap ) {
  20340. uniforms.normalMap.value = material.normalMap;
  20341. uniforms.normalScale.value.copy( material.normalScale );
  20342. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20343. }
  20344. if ( material.displacementMap ) {
  20345. uniforms.displacementMap.value = material.displacementMap;
  20346. uniforms.displacementScale.value = material.displacementScale;
  20347. uniforms.displacementBias.value = material.displacementBias;
  20348. }
  20349. }
  20350. function refreshUniformsStandard( uniforms, material, environment ) {
  20351. uniforms.roughness.value = material.roughness;
  20352. uniforms.metalness.value = material.metalness;
  20353. if ( material.roughnessMap ) {
  20354. uniforms.roughnessMap.value = material.roughnessMap;
  20355. }
  20356. if ( material.metalnessMap ) {
  20357. uniforms.metalnessMap.value = material.metalnessMap;
  20358. }
  20359. if ( material.emissiveMap ) {
  20360. uniforms.emissiveMap.value = material.emissiveMap;
  20361. }
  20362. if ( material.bumpMap ) {
  20363. uniforms.bumpMap.value = material.bumpMap;
  20364. uniforms.bumpScale.value = material.bumpScale;
  20365. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20366. }
  20367. if ( material.normalMap ) {
  20368. uniforms.normalMap.value = material.normalMap;
  20369. uniforms.normalScale.value.copy( material.normalScale );
  20370. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20371. }
  20372. if ( material.displacementMap ) {
  20373. uniforms.displacementMap.value = material.displacementMap;
  20374. uniforms.displacementScale.value = material.displacementScale;
  20375. uniforms.displacementBias.value = material.displacementBias;
  20376. }
  20377. if ( material.envMap || environment ) {
  20378. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20379. uniforms.envMapIntensity.value = material.envMapIntensity;
  20380. }
  20381. }
  20382. function refreshUniformsPhysical( uniforms, material, environment ) {
  20383. refreshUniformsStandard( uniforms, material, environment );
  20384. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  20385. uniforms.clearcoat.value = material.clearcoat;
  20386. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20387. if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); }
  20388. if ( material.clearcoatMap ) {
  20389. uniforms.clearcoatMap.value = material.clearcoatMap;
  20390. }
  20391. if ( material.clearcoatRoughnessMap ) {
  20392. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  20393. }
  20394. if ( material.clearcoatNormalMap ) {
  20395. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  20396. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20397. if ( material.side === BackSide ) {
  20398. uniforms.clearcoatNormalScale.value.negate();
  20399. }
  20400. }
  20401. uniforms.transmission.value = material.transmission;
  20402. if ( material.transmissionMap ) {
  20403. uniforms.transmissionMap.value = material.transmissionMap;
  20404. }
  20405. }
  20406. function refreshUniformsMatcap( uniforms, material ) {
  20407. if ( material.matcap ) {
  20408. uniforms.matcap.value = material.matcap;
  20409. }
  20410. if ( material.bumpMap ) {
  20411. uniforms.bumpMap.value = material.bumpMap;
  20412. uniforms.bumpScale.value = material.bumpScale;
  20413. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20414. }
  20415. if ( material.normalMap ) {
  20416. uniforms.normalMap.value = material.normalMap;
  20417. uniforms.normalScale.value.copy( material.normalScale );
  20418. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20419. }
  20420. if ( material.displacementMap ) {
  20421. uniforms.displacementMap.value = material.displacementMap;
  20422. uniforms.displacementScale.value = material.displacementScale;
  20423. uniforms.displacementBias.value = material.displacementBias;
  20424. }
  20425. }
  20426. function refreshUniformsDepth( uniforms, material ) {
  20427. if ( material.displacementMap ) {
  20428. uniforms.displacementMap.value = material.displacementMap;
  20429. uniforms.displacementScale.value = material.displacementScale;
  20430. uniforms.displacementBias.value = material.displacementBias;
  20431. }
  20432. }
  20433. function refreshUniformsDistance( uniforms, material ) {
  20434. if ( material.displacementMap ) {
  20435. uniforms.displacementMap.value = material.displacementMap;
  20436. uniforms.displacementScale.value = material.displacementScale;
  20437. uniforms.displacementBias.value = material.displacementBias;
  20438. }
  20439. uniforms.referencePosition.value.copy( material.referencePosition );
  20440. uniforms.nearDistance.value = material.nearDistance;
  20441. uniforms.farDistance.value = material.farDistance;
  20442. }
  20443. function refreshUniformsNormal( uniforms, material ) {
  20444. if ( material.bumpMap ) {
  20445. uniforms.bumpMap.value = material.bumpMap;
  20446. uniforms.bumpScale.value = material.bumpScale;
  20447. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20448. }
  20449. if ( material.normalMap ) {
  20450. uniforms.normalMap.value = material.normalMap;
  20451. uniforms.normalScale.value.copy( material.normalScale );
  20452. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20453. }
  20454. if ( material.displacementMap ) {
  20455. uniforms.displacementMap.value = material.displacementMap;
  20456. uniforms.displacementScale.value = material.displacementScale;
  20457. uniforms.displacementBias.value = material.displacementBias;
  20458. }
  20459. }
  20460. return {
  20461. refreshFogUniforms: refreshFogUniforms,
  20462. refreshMaterialUniforms: refreshMaterialUniforms
  20463. };
  20464. }
  20465. function WebGLRenderer( parameters ) {
  20466. parameters = parameters || {};
  20467. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  20468. _context = parameters.context !== undefined ? parameters.context : null,
  20469. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  20470. _depth = parameters.depth !== undefined ? parameters.depth : true,
  20471. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  20472. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  20473. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  20474. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20475. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  20476. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  20477. var currentRenderList = null;
  20478. var currentRenderState = null;
  20479. // public properties
  20480. this.domElement = _canvas;
  20481. // Debug configuration container
  20482. this.debug = {
  20483. /**
  20484. * Enables error checking and reporting when shader programs are being compiled
  20485. * @type {boolean}
  20486. */
  20487. checkShaderErrors: true
  20488. };
  20489. // clearing
  20490. this.autoClear = true;
  20491. this.autoClearColor = true;
  20492. this.autoClearDepth = true;
  20493. this.autoClearStencil = true;
  20494. // scene graph
  20495. this.sortObjects = true;
  20496. // user-defined clipping
  20497. this.clippingPlanes = [];
  20498. this.localClippingEnabled = false;
  20499. // physically based shading
  20500. this.gammaFactor = 2.0; // for backwards compatibility
  20501. this.outputEncoding = LinearEncoding;
  20502. // physical lights
  20503. this.physicallyCorrectLights = false;
  20504. // tone mapping
  20505. this.toneMapping = NoToneMapping;
  20506. this.toneMappingExposure = 1.0;
  20507. // morphs
  20508. this.maxMorphTargets = 8;
  20509. this.maxMorphNormals = 4;
  20510. // internal properties
  20511. var _this = this;
  20512. var _isContextLost = false;
  20513. // internal state cache
  20514. var _framebuffer = null;
  20515. var _currentActiveCubeFace = 0;
  20516. var _currentActiveMipmapLevel = 0;
  20517. var _currentRenderTarget = null;
  20518. var _currentFramebuffer = null;
  20519. var _currentMaterialId = - 1;
  20520. var _currentCamera = null;
  20521. var _currentArrayCamera = null;
  20522. var _currentViewport = new Vector4();
  20523. var _currentScissor = new Vector4();
  20524. var _currentScissorTest = null;
  20525. //
  20526. var _width = _canvas.width;
  20527. var _height = _canvas.height;
  20528. var _pixelRatio = 1;
  20529. var _opaqueSort = null;
  20530. var _transparentSort = null;
  20531. var _viewport = new Vector4( 0, 0, _width, _height );
  20532. var _scissor = new Vector4( 0, 0, _width, _height );
  20533. var _scissorTest = false;
  20534. // frustum
  20535. var _frustum = new Frustum();
  20536. // clipping
  20537. var _clipping = new WebGLClipping();
  20538. var _clippingEnabled = false;
  20539. var _localClippingEnabled = false;
  20540. // camera matrices cache
  20541. var _projScreenMatrix = new Matrix4();
  20542. var _vector3 = new Vector3();
  20543. var _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  20544. function getTargetPixelRatio() {
  20545. return _currentRenderTarget === null ? _pixelRatio : 1;
  20546. }
  20547. // initialize
  20548. var _gl = _context;
  20549. function getContext( contextNames, contextAttributes ) {
  20550. for ( var i = 0; i < contextNames.length; i ++ ) {
  20551. var contextName = contextNames[ i ];
  20552. var context = _canvas.getContext( contextName, contextAttributes );
  20553. if ( context !== null ) { return context; }
  20554. }
  20555. return null;
  20556. }
  20557. try {
  20558. var contextAttributes = {
  20559. alpha: _alpha,
  20560. depth: _depth,
  20561. stencil: _stencil,
  20562. antialias: _antialias,
  20563. premultipliedAlpha: _premultipliedAlpha,
  20564. preserveDrawingBuffer: _preserveDrawingBuffer,
  20565. powerPreference: _powerPreference,
  20566. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  20567. };
  20568. // event listeners must be registered before WebGL context is created, see #12753
  20569. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  20570. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  20571. if ( _gl === null ) {
  20572. var contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  20573. if ( _this.isWebGL1Renderer === true ) {
  20574. contextNames.shift();
  20575. }
  20576. _gl = getContext( contextNames, contextAttributes );
  20577. if ( _gl === null ) {
  20578. if ( getContext( contextNames ) ) {
  20579. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  20580. } else {
  20581. throw new Error( 'Error creating WebGL context.' );
  20582. }
  20583. }
  20584. }
  20585. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  20586. if ( _gl.getShaderPrecisionFormat === undefined ) {
  20587. _gl.getShaderPrecisionFormat = function () {
  20588. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  20589. };
  20590. }
  20591. } catch ( error ) {
  20592. console.error( 'THREE.WebGLRenderer: ' + error.message );
  20593. throw error;
  20594. }
  20595. var extensions, capabilities, state, info;
  20596. var properties, textures, attributes, geometries, objects;
  20597. var programCache, materials, renderLists, renderStates;
  20598. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  20599. var utils, bindingStates;
  20600. function initGLContext() {
  20601. extensions = new WebGLExtensions( _gl );
  20602. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  20603. if ( capabilities.isWebGL2 === false ) {
  20604. extensions.get( 'WEBGL_depth_texture' );
  20605. extensions.get( 'OES_texture_float' );
  20606. extensions.get( 'OES_texture_half_float' );
  20607. extensions.get( 'OES_texture_half_float_linear' );
  20608. extensions.get( 'OES_standard_derivatives' );
  20609. extensions.get( 'OES_element_index_uint' );
  20610. extensions.get( 'OES_vertex_array_object' );
  20611. extensions.get( 'ANGLE_instanced_arrays' );
  20612. }
  20613. extensions.get( 'OES_texture_float_linear' );
  20614. utils = new WebGLUtils( _gl, extensions, capabilities );
  20615. state = new WebGLState( _gl, extensions, capabilities );
  20616. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  20617. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  20618. info = new WebGLInfo( _gl );
  20619. properties = new WebGLProperties();
  20620. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  20621. attributes = new WebGLAttributes( _gl, capabilities );
  20622. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  20623. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  20624. objects = new WebGLObjects( _gl, geometries, attributes, info );
  20625. morphtargets = new WebGLMorphtargets( _gl );
  20626. programCache = new WebGLPrograms( _this, extensions, capabilities, bindingStates );
  20627. materials = new WebGLMaterials( properties );
  20628. renderLists = new WebGLRenderLists( properties );
  20629. renderStates = new WebGLRenderStates();
  20630. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  20631. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  20632. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  20633. info.programs = programCache.programs;
  20634. _this.capabilities = capabilities;
  20635. _this.extensions = extensions;
  20636. _this.properties = properties;
  20637. _this.renderLists = renderLists;
  20638. _this.state = state;
  20639. _this.info = info;
  20640. }
  20641. initGLContext();
  20642. var xr = ( typeof navigator !== 'undefined' && 'xr' in navigator ) ? new WebXRManager( _this, _gl ) : new WebVRManager( _this );
  20643. this.xr = xr;
  20644. // shadow map
  20645. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  20646. this.shadowMap = shadowMap;
  20647. // API
  20648. this.getContext = function () {
  20649. return _gl;
  20650. };
  20651. this.getContextAttributes = function () {
  20652. return _gl.getContextAttributes();
  20653. };
  20654. this.forceContextLoss = function () {
  20655. var extension = extensions.get( 'WEBGL_lose_context' );
  20656. if ( extension ) { extension.loseContext(); }
  20657. };
  20658. this.forceContextRestore = function () {
  20659. var extension = extensions.get( 'WEBGL_lose_context' );
  20660. if ( extension ) { extension.restoreContext(); }
  20661. };
  20662. this.getPixelRatio = function () {
  20663. return _pixelRatio;
  20664. };
  20665. this.setPixelRatio = function ( value ) {
  20666. if ( value === undefined ) { return; }
  20667. _pixelRatio = value;
  20668. this.setSize( _width, _height, false );
  20669. };
  20670. this.getSize = function ( target ) {
  20671. if ( target === undefined ) {
  20672. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  20673. target = new Vector2();
  20674. }
  20675. return target.set( _width, _height );
  20676. };
  20677. this.setSize = function ( width, height, updateStyle ) {
  20678. if ( xr.isPresenting ) {
  20679. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  20680. return;
  20681. }
  20682. _width = width;
  20683. _height = height;
  20684. _canvas.width = Math.floor( width * _pixelRatio );
  20685. _canvas.height = Math.floor( height * _pixelRatio );
  20686. if ( updateStyle !== false ) {
  20687. _canvas.style.width = width + 'px';
  20688. _canvas.style.height = height + 'px';
  20689. }
  20690. this.setViewport( 0, 0, width, height );
  20691. };
  20692. this.getDrawingBufferSize = function ( target ) {
  20693. if ( target === undefined ) {
  20694. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  20695. target = new Vector2();
  20696. }
  20697. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  20698. };
  20699. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  20700. _width = width;
  20701. _height = height;
  20702. _pixelRatio = pixelRatio;
  20703. _canvas.width = Math.floor( width * pixelRatio );
  20704. _canvas.height = Math.floor( height * pixelRatio );
  20705. this.setViewport( 0, 0, width, height );
  20706. };
  20707. this.getCurrentViewport = function ( target ) {
  20708. if ( target === undefined ) {
  20709. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  20710. target = new Vector4();
  20711. }
  20712. return target.copy( _currentViewport );
  20713. };
  20714. this.getViewport = function ( target ) {
  20715. return target.copy( _viewport );
  20716. };
  20717. this.setViewport = function ( x, y, width, height ) {
  20718. if ( x.isVector4 ) {
  20719. _viewport.set( x.x, x.y, x.z, x.w );
  20720. } else {
  20721. _viewport.set( x, y, width, height );
  20722. }
  20723. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  20724. };
  20725. this.getScissor = function ( target ) {
  20726. return target.copy( _scissor );
  20727. };
  20728. this.setScissor = function ( x, y, width, height ) {
  20729. if ( x.isVector4 ) {
  20730. _scissor.set( x.x, x.y, x.z, x.w );
  20731. } else {
  20732. _scissor.set( x, y, width, height );
  20733. }
  20734. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  20735. };
  20736. this.getScissorTest = function () {
  20737. return _scissorTest;
  20738. };
  20739. this.setScissorTest = function ( boolean ) {
  20740. state.setScissorTest( _scissorTest = boolean );
  20741. };
  20742. this.setOpaqueSort = function ( method ) {
  20743. _opaqueSort = method;
  20744. };
  20745. this.setTransparentSort = function ( method ) {
  20746. _transparentSort = method;
  20747. };
  20748. // Clearing
  20749. this.getClearColor = function () {
  20750. return background.getClearColor();
  20751. };
  20752. this.setClearColor = function () {
  20753. background.setClearColor.apply( background, arguments );
  20754. };
  20755. this.getClearAlpha = function () {
  20756. return background.getClearAlpha();
  20757. };
  20758. this.setClearAlpha = function () {
  20759. background.setClearAlpha.apply( background, arguments );
  20760. };
  20761. this.clear = function ( color, depth, stencil ) {
  20762. var bits = 0;
  20763. if ( color === undefined || color ) { bits |= 16384; }
  20764. if ( depth === undefined || depth ) { bits |= 256; }
  20765. if ( stencil === undefined || stencil ) { bits |= 1024; }
  20766. _gl.clear( bits );
  20767. };
  20768. this.clearColor = function () {
  20769. this.clear( true, false, false );
  20770. };
  20771. this.clearDepth = function () {
  20772. this.clear( false, true, false );
  20773. };
  20774. this.clearStencil = function () {
  20775. this.clear( false, false, true );
  20776. };
  20777. //
  20778. this.dispose = function () {
  20779. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  20780. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  20781. renderLists.dispose();
  20782. renderStates.dispose();
  20783. properties.dispose();
  20784. objects.dispose();
  20785. bindingStates.dispose();
  20786. xr.dispose();
  20787. animation.stop();
  20788. };
  20789. // Events
  20790. function onContextLost( event ) {
  20791. event.preventDefault();
  20792. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  20793. _isContextLost = true;
  20794. }
  20795. function onContextRestore( /* event */ ) {
  20796. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  20797. _isContextLost = false;
  20798. initGLContext();
  20799. }
  20800. function onMaterialDispose( event ) {
  20801. var material = event.target;
  20802. material.removeEventListener( 'dispose', onMaterialDispose );
  20803. deallocateMaterial( material );
  20804. }
  20805. // Buffer deallocation
  20806. function deallocateMaterial( material ) {
  20807. releaseMaterialProgramReference( material );
  20808. properties.remove( material );
  20809. }
  20810. function releaseMaterialProgramReference( material ) {
  20811. var programInfo = properties.get( material ).program;
  20812. if ( programInfo !== undefined ) {
  20813. programCache.releaseProgram( programInfo );
  20814. }
  20815. }
  20816. // Buffer rendering
  20817. function renderObjectImmediate( object, program ) {
  20818. object.render( function ( object ) {
  20819. _this.renderBufferImmediate( object, program );
  20820. } );
  20821. }
  20822. this.renderBufferImmediate = function ( object, program ) {
  20823. bindingStates.initAttributes();
  20824. var buffers = properties.get( object );
  20825. if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); }
  20826. if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); }
  20827. if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); }
  20828. if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); }
  20829. var programAttributes = program.getAttributes();
  20830. if ( object.hasPositions ) {
  20831. _gl.bindBuffer( 34962, buffers.position );
  20832. _gl.bufferData( 34962, object.positionArray, 35048 );
  20833. bindingStates.enableAttribute( programAttributes.position );
  20834. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  20835. }
  20836. if ( object.hasNormals ) {
  20837. _gl.bindBuffer( 34962, buffers.normal );
  20838. _gl.bufferData( 34962, object.normalArray, 35048 );
  20839. bindingStates.enableAttribute( programAttributes.normal );
  20840. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  20841. }
  20842. if ( object.hasUvs ) {
  20843. _gl.bindBuffer( 34962, buffers.uv );
  20844. _gl.bufferData( 34962, object.uvArray, 35048 );
  20845. bindingStates.enableAttribute( programAttributes.uv );
  20846. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  20847. }
  20848. if ( object.hasColors ) {
  20849. _gl.bindBuffer( 34962, buffers.color );
  20850. _gl.bufferData( 34962, object.colorArray, 35048 );
  20851. bindingStates.enableAttribute( programAttributes.color );
  20852. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  20853. }
  20854. bindingStates.disableUnusedAttributes();
  20855. _gl.drawArrays( 4, 0, object.count );
  20856. object.count = 0;
  20857. };
  20858. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  20859. if ( scene === null ) { scene = _emptyScene; } // renderBufferDirect second parameter used to be fog (could be null)
  20860. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20861. var program = setProgram( camera, scene, material, object );
  20862. state.setMaterial( material, frontFaceCW );
  20863. //
  20864. var index = geometry.index;
  20865. var position = geometry.attributes.position;
  20866. //
  20867. if ( index === null ) {
  20868. if ( position === undefined || position.count === 0 ) { return; }
  20869. } else if ( index.count === 0 ) {
  20870. return;
  20871. }
  20872. //
  20873. var rangeFactor = 1;
  20874. if ( material.wireframe === true ) {
  20875. index = geometries.getWireframeAttribute( geometry );
  20876. rangeFactor = 2;
  20877. }
  20878. if ( material.morphTargets || material.morphNormals ) {
  20879. morphtargets.update( object, geometry, material, program );
  20880. }
  20881. bindingStates.setup( object, material, program, geometry, index );
  20882. var attribute;
  20883. var renderer = bufferRenderer;
  20884. if ( index !== null ) {
  20885. attribute = attributes.get( index );
  20886. renderer = indexedBufferRenderer;
  20887. renderer.setIndex( attribute );
  20888. }
  20889. //
  20890. var dataCount = ( index !== null ) ? index.count : position.count;
  20891. var rangeStart = geometry.drawRange.start * rangeFactor;
  20892. var rangeCount = geometry.drawRange.count * rangeFactor;
  20893. var groupStart = group !== null ? group.start * rangeFactor : 0;
  20894. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  20895. var drawStart = Math.max( rangeStart, groupStart );
  20896. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  20897. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  20898. if ( drawCount === 0 ) { return; }
  20899. //
  20900. if ( object.isMesh ) {
  20901. if ( material.wireframe === true ) {
  20902. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  20903. renderer.setMode( 1 );
  20904. } else {
  20905. renderer.setMode( 4 );
  20906. }
  20907. } else if ( object.isLine ) {
  20908. var lineWidth = material.linewidth;
  20909. if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material
  20910. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  20911. if ( object.isLineSegments ) {
  20912. renderer.setMode( 1 );
  20913. } else if ( object.isLineLoop ) {
  20914. renderer.setMode( 2 );
  20915. } else {
  20916. renderer.setMode( 3 );
  20917. }
  20918. } else if ( object.isPoints ) {
  20919. renderer.setMode( 0 );
  20920. } else if ( object.isSprite ) {
  20921. renderer.setMode( 4 );
  20922. }
  20923. if ( object.isInstancedMesh ) {
  20924. renderer.renderInstances( drawStart, drawCount, object.count );
  20925. } else if ( geometry.isInstancedBufferGeometry ) {
  20926. var instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  20927. renderer.renderInstances( drawStart, drawCount, instanceCount );
  20928. } else {
  20929. renderer.render( drawStart, drawCount );
  20930. }
  20931. };
  20932. // Compile
  20933. this.compile = function ( scene, camera ) {
  20934. currentRenderState = renderStates.get( scene, camera );
  20935. currentRenderState.init();
  20936. scene.traverse( function ( object ) {
  20937. if ( object.isLight ) {
  20938. currentRenderState.pushLight( object );
  20939. if ( object.castShadow ) {
  20940. currentRenderState.pushShadow( object );
  20941. }
  20942. }
  20943. } );
  20944. currentRenderState.setupLights( camera );
  20945. var compiled = new WeakMap();
  20946. scene.traverse( function ( object ) {
  20947. var material = object.material;
  20948. if ( material ) {
  20949. if ( Array.isArray( material ) ) {
  20950. for ( var i = 0; i < material.length; i ++ ) {
  20951. var material2 = material[ i ];
  20952. if ( compiled.has( material2 ) === false ) {
  20953. initMaterial( material2, scene, object );
  20954. compiled.set( material2 );
  20955. }
  20956. }
  20957. } else if ( compiled.has( material ) === false ) {
  20958. initMaterial( material, scene, object );
  20959. compiled.set( material );
  20960. }
  20961. }
  20962. } );
  20963. };
  20964. // Animation Loop
  20965. var onAnimationFrameCallback = null;
  20966. function onAnimationFrame( time ) {
  20967. if ( xr.isPresenting ) { return; }
  20968. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); }
  20969. }
  20970. var animation = new WebGLAnimation();
  20971. animation.setAnimationLoop( onAnimationFrame );
  20972. if ( typeof window !== 'undefined' ) { animation.setContext( window ); }
  20973. this.setAnimationLoop = function ( callback ) {
  20974. onAnimationFrameCallback = callback;
  20975. xr.setAnimationLoop( callback );
  20976. ( callback === null ) ? animation.stop() : animation.start();
  20977. };
  20978. // Rendering
  20979. this.render = function ( scene, camera ) {
  20980. var renderTarget, forceClear;
  20981. if ( arguments[ 2 ] !== undefined ) {
  20982. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  20983. renderTarget = arguments[ 2 ];
  20984. }
  20985. if ( arguments[ 3 ] !== undefined ) {
  20986. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  20987. forceClear = arguments[ 3 ];
  20988. }
  20989. if ( camera !== undefined && camera.isCamera !== true ) {
  20990. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  20991. return;
  20992. }
  20993. if ( _isContextLost === true ) { return; }
  20994. // reset caching for this frame
  20995. bindingStates.resetDefaultState();
  20996. _currentMaterialId = - 1;
  20997. _currentCamera = null;
  20998. // update scene graph
  20999. if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); }
  21000. // update camera matrices and frustum
  21001. if ( camera.parent === null ) { camera.updateMatrixWorld(); }
  21002. if ( xr.enabled === true && xr.isPresenting === true ) {
  21003. camera = xr.getCamera( camera );
  21004. }
  21005. //
  21006. if ( scene.isScene === true ) { scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); }
  21007. currentRenderState = renderStates.get( scene, camera );
  21008. currentRenderState.init();
  21009. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21010. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  21011. _localClippingEnabled = this.localClippingEnabled;
  21012. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  21013. currentRenderList = renderLists.get( scene, camera );
  21014. currentRenderList.init();
  21015. projectObject( scene, camera, 0, _this.sortObjects );
  21016. currentRenderList.finish();
  21017. if ( _this.sortObjects === true ) {
  21018. currentRenderList.sort( _opaqueSort, _transparentSort );
  21019. }
  21020. //
  21021. if ( _clippingEnabled === true ) { _clipping.beginShadows(); }
  21022. var shadowsArray = currentRenderState.state.shadowsArray;
  21023. shadowMap.render( shadowsArray, scene, camera );
  21024. currentRenderState.setupLights( camera );
  21025. if ( _clippingEnabled === true ) { _clipping.endShadows(); }
  21026. //
  21027. if ( this.info.autoReset === true ) { this.info.reset(); }
  21028. if ( renderTarget !== undefined ) {
  21029. this.setRenderTarget( renderTarget );
  21030. }
  21031. //
  21032. background.render( currentRenderList, scene, camera, forceClear );
  21033. // render scene
  21034. var opaqueObjects = currentRenderList.opaque;
  21035. var transparentObjects = currentRenderList.transparent;
  21036. if ( opaqueObjects.length > 0 ) { renderObjects( opaqueObjects, scene, camera ); }
  21037. if ( transparentObjects.length > 0 ) { renderObjects( transparentObjects, scene, camera ); }
  21038. //
  21039. if ( scene.isScene === true ) { scene.onAfterRender( _this, scene, camera ); }
  21040. //
  21041. if ( _currentRenderTarget !== null ) {
  21042. // Generate mipmap if we're using any kind of mipmap filtering
  21043. textures.updateRenderTargetMipmap( _currentRenderTarget );
  21044. // resolve multisample renderbuffers to a single-sample texture if necessary
  21045. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  21046. }
  21047. // Ensure depth buffer writing is enabled so it can be cleared on next render
  21048. state.buffers.depth.setTest( true );
  21049. state.buffers.depth.setMask( true );
  21050. state.buffers.color.setMask( true );
  21051. state.setPolygonOffset( false );
  21052. if ( xr.enabled && xr.submitFrame ) {
  21053. xr.submitFrame();
  21054. }
  21055. // _gl.finish();
  21056. currentRenderList = null;
  21057. currentRenderState = null;
  21058. };
  21059. function projectObject( object, camera, groupOrder, sortObjects ) {
  21060. if ( object.visible === false ) { return; }
  21061. var visible = object.layers.test( camera.layers );
  21062. if ( visible ) {
  21063. if ( object.isGroup ) {
  21064. groupOrder = object.renderOrder;
  21065. } else if ( object.isLOD ) {
  21066. if ( object.autoUpdate === true ) { object.update( camera ); }
  21067. } else if ( object.isLight ) {
  21068. currentRenderState.pushLight( object );
  21069. if ( object.castShadow ) {
  21070. currentRenderState.pushShadow( object );
  21071. }
  21072. } else if ( object.isSprite ) {
  21073. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  21074. if ( sortObjects ) {
  21075. _vector3.setFromMatrixPosition( object.matrixWorld )
  21076. .applyMatrix4( _projScreenMatrix );
  21077. }
  21078. var geometry = objects.update( object );
  21079. var material = object.material;
  21080. if ( material.visible ) {
  21081. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  21082. }
  21083. }
  21084. } else if ( object.isImmediateRenderObject ) {
  21085. if ( sortObjects ) {
  21086. _vector3.setFromMatrixPosition( object.matrixWorld )
  21087. .applyMatrix4( _projScreenMatrix );
  21088. }
  21089. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  21090. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  21091. if ( object.isSkinnedMesh ) {
  21092. // update skeleton only once in a frame
  21093. if ( object.skeleton.frame !== info.render.frame ) {
  21094. object.skeleton.update();
  21095. object.skeleton.frame = info.render.frame;
  21096. }
  21097. }
  21098. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  21099. if ( sortObjects ) {
  21100. _vector3.setFromMatrixPosition( object.matrixWorld )
  21101. .applyMatrix4( _projScreenMatrix );
  21102. }
  21103. var geometry$1 = objects.update( object );
  21104. var material$1 = object.material;
  21105. if ( Array.isArray( material$1 ) ) {
  21106. var groups = geometry$1.groups;
  21107. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  21108. var group = groups[ i ];
  21109. var groupMaterial = material$1[ group.materialIndex ];
  21110. if ( groupMaterial && groupMaterial.visible ) {
  21111. currentRenderList.push( object, geometry$1, groupMaterial, groupOrder, _vector3.z, group );
  21112. }
  21113. }
  21114. } else if ( material$1.visible ) {
  21115. currentRenderList.push( object, geometry$1, material$1, groupOrder, _vector3.z, null );
  21116. }
  21117. }
  21118. }
  21119. }
  21120. var children = object.children;
  21121. for ( var i$1 = 0, l$1 = children.length; i$1 < l$1; i$1 ++ ) {
  21122. projectObject( children[ i$1 ], camera, groupOrder, sortObjects );
  21123. }
  21124. }
  21125. function renderObjects( renderList, scene, camera ) {
  21126. var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  21127. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  21128. var renderItem = renderList[ i ];
  21129. var object = renderItem.object;
  21130. var geometry = renderItem.geometry;
  21131. var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  21132. var group = renderItem.group;
  21133. if ( camera.isArrayCamera ) {
  21134. _currentArrayCamera = camera;
  21135. var cameras = camera.cameras;
  21136. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  21137. var camera2 = cameras[ j ];
  21138. if ( object.layers.test( camera2.layers ) ) {
  21139. state.viewport( _currentViewport.copy( camera2.viewport ) );
  21140. currentRenderState.setupLights( camera2 );
  21141. renderObject( object, scene, camera2, geometry, material, group );
  21142. }
  21143. }
  21144. } else {
  21145. _currentArrayCamera = null;
  21146. renderObject( object, scene, camera, geometry, material, group );
  21147. }
  21148. }
  21149. }
  21150. function renderObject( object, scene, camera, geometry, material, group ) {
  21151. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  21152. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  21153. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21154. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  21155. if ( object.isImmediateRenderObject ) {
  21156. var program = setProgram( camera, scene, material, object );
  21157. state.setMaterial( material );
  21158. bindingStates.reset();
  21159. renderObjectImmediate( object, program );
  21160. } else {
  21161. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  21162. }
  21163. object.onAfterRender( _this, scene, camera, geometry, material, group );
  21164. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  21165. }
  21166. function initMaterial( material, scene, object ) {
  21167. if ( scene.isScene !== true ) { scene = _emptyScene; } // scene could be a Mesh, Line, Points, ...
  21168. var materialProperties = properties.get( material );
  21169. var lights = currentRenderState.state.lights;
  21170. var shadowsArray = currentRenderState.state.shadowsArray;
  21171. var lightsStateVersion = lights.state.version;
  21172. var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
  21173. var programCacheKey = programCache.getProgramCacheKey( parameters );
  21174. var program = materialProperties.program;
  21175. var programChange = true;
  21176. if ( program === undefined ) {
  21177. // new material
  21178. material.addEventListener( 'dispose', onMaterialDispose );
  21179. } else if ( program.cacheKey !== programCacheKey ) {
  21180. // changed glsl or parameters
  21181. releaseMaterialProgramReference( material );
  21182. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  21183. materialProperties.lightsStateVersion = lightsStateVersion;
  21184. programChange = false;
  21185. } else if ( parameters.shaderID !== undefined ) {
  21186. // same glsl and uniform list
  21187. return;
  21188. } else {
  21189. // only rebuild uniform list
  21190. programChange = false;
  21191. }
  21192. if ( programChange ) {
  21193. parameters.uniforms = programCache.getUniforms( material, parameters );
  21194. material.onBeforeCompile( parameters, _this );
  21195. program = programCache.acquireProgram( parameters, programCacheKey );
  21196. materialProperties.program = program;
  21197. materialProperties.uniforms = parameters.uniforms;
  21198. materialProperties.outputEncoding = parameters.outputEncoding;
  21199. }
  21200. var programAttributes = program.getAttributes();
  21201. if ( material.morphTargets ) {
  21202. material.numSupportedMorphTargets = 0;
  21203. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  21204. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  21205. material.numSupportedMorphTargets ++;
  21206. }
  21207. }
  21208. }
  21209. if ( material.morphNormals ) {
  21210. material.numSupportedMorphNormals = 0;
  21211. for ( var i$1 = 0; i$1 < _this.maxMorphNormals; i$1 ++ ) {
  21212. if ( programAttributes[ 'morphNormal' + i$1 ] >= 0 ) {
  21213. material.numSupportedMorphNormals ++;
  21214. }
  21215. }
  21216. }
  21217. var uniforms = materialProperties.uniforms;
  21218. if ( ! material.isShaderMaterial &&
  21219. ! material.isRawShaderMaterial ||
  21220. material.clipping === true ) {
  21221. materialProperties.numClippingPlanes = _clipping.numPlanes;
  21222. materialProperties.numIntersection = _clipping.numIntersection;
  21223. uniforms.clippingPlanes = _clipping.uniform;
  21224. }
  21225. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  21226. materialProperties.fog = scene.fog;
  21227. // store the light setup it was created for
  21228. materialProperties.needsLights = materialNeedsLights( material );
  21229. materialProperties.lightsStateVersion = lightsStateVersion;
  21230. if ( materialProperties.needsLights ) {
  21231. // wire up the material to this renderer's lighting state
  21232. uniforms.ambientLightColor.value = lights.state.ambient;
  21233. uniforms.lightProbe.value = lights.state.probe;
  21234. uniforms.directionalLights.value = lights.state.directional;
  21235. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  21236. uniforms.spotLights.value = lights.state.spot;
  21237. uniforms.spotLightShadows.value = lights.state.spotShadow;
  21238. uniforms.rectAreaLights.value = lights.state.rectArea;
  21239. uniforms.pointLights.value = lights.state.point;
  21240. uniforms.pointLightShadows.value = lights.state.pointShadow;
  21241. uniforms.hemisphereLights.value = lights.state.hemi;
  21242. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  21243. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  21244. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  21245. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  21246. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  21247. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  21248. // TODO (abelnation): add area lights shadow info to uniforms
  21249. }
  21250. var progUniforms = materialProperties.program.getUniforms(),
  21251. uniformsList =
  21252. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  21253. materialProperties.uniformsList = uniformsList;
  21254. }
  21255. function setProgram( camera, scene, material, object ) {
  21256. if ( scene.isScene !== true ) { scene = _emptyScene; } // scene could be a Mesh, Line, Points, ...
  21257. textures.resetTextureUnits();
  21258. var fog = scene.fog;
  21259. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  21260. var encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  21261. var materialProperties = properties.get( material );
  21262. var lights = currentRenderState.state.lights;
  21263. if ( _clippingEnabled === true ) {
  21264. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  21265. var useCache =
  21266. camera === _currentCamera &&
  21267. material.id === _currentMaterialId;
  21268. // we might want to call this function with some ClippingGroup
  21269. // object instead of the material, once it becomes feasible
  21270. // (#8465, #8379)
  21271. _clipping.setState(
  21272. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  21273. camera, materialProperties, useCache );
  21274. }
  21275. }
  21276. if ( material.version === materialProperties.__version ) {
  21277. if ( materialProperties.program === undefined ) {
  21278. initMaterial( material, scene, object );
  21279. } else if ( material.fog && materialProperties.fog !== fog ) {
  21280. initMaterial( material, scene, object );
  21281. } else if ( materialProperties.environment !== environment ) {
  21282. initMaterial( material, scene, object );
  21283. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  21284. initMaterial( material, scene, object );
  21285. } else if ( materialProperties.numClippingPlanes !== undefined &&
  21286. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  21287. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  21288. initMaterial( material, scene, object );
  21289. } else if ( materialProperties.outputEncoding !== encoding ) {
  21290. initMaterial( material, scene, object );
  21291. }
  21292. } else {
  21293. initMaterial( material, scene, object );
  21294. materialProperties.__version = material.version;
  21295. }
  21296. var refreshProgram = false;
  21297. var refreshMaterial = false;
  21298. var refreshLights = false;
  21299. var program = materialProperties.program,
  21300. p_uniforms = program.getUniforms(),
  21301. m_uniforms = materialProperties.uniforms;
  21302. if ( state.useProgram( program.program ) ) {
  21303. refreshProgram = true;
  21304. refreshMaterial = true;
  21305. refreshLights = true;
  21306. }
  21307. if ( material.id !== _currentMaterialId ) {
  21308. _currentMaterialId = material.id;
  21309. refreshMaterial = true;
  21310. }
  21311. if ( refreshProgram || _currentCamera !== camera ) {
  21312. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  21313. if ( capabilities.logarithmicDepthBuffer ) {
  21314. p_uniforms.setValue( _gl, 'logDepthBufFC',
  21315. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  21316. }
  21317. if ( _currentCamera !== camera ) {
  21318. _currentCamera = camera;
  21319. // lighting uniforms depend on the camera so enforce an update
  21320. // now, in case this material supports lights - or later, when
  21321. // the next material that does gets activated:
  21322. refreshMaterial = true; // set to true on material change
  21323. refreshLights = true; // remains set until update done
  21324. }
  21325. // load material specific uniforms
  21326. // (shader material also gets them for the sake of genericity)
  21327. if ( material.isShaderMaterial ||
  21328. material.isMeshPhongMaterial ||
  21329. material.isMeshToonMaterial ||
  21330. material.isMeshStandardMaterial ||
  21331. material.envMap ) {
  21332. var uCamPos = p_uniforms.map.cameraPosition;
  21333. if ( uCamPos !== undefined ) {
  21334. uCamPos.setValue( _gl,
  21335. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  21336. }
  21337. }
  21338. if ( material.isMeshPhongMaterial ||
  21339. material.isMeshToonMaterial ||
  21340. material.isMeshLambertMaterial ||
  21341. material.isMeshBasicMaterial ||
  21342. material.isMeshStandardMaterial ||
  21343. material.isShaderMaterial ) {
  21344. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  21345. }
  21346. if ( material.isMeshPhongMaterial ||
  21347. material.isMeshToonMaterial ||
  21348. material.isMeshLambertMaterial ||
  21349. material.isMeshBasicMaterial ||
  21350. material.isMeshStandardMaterial ||
  21351. material.isShaderMaterial ||
  21352. material.isShadowMaterial ||
  21353. material.skinning ) {
  21354. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  21355. }
  21356. }
  21357. // skinning uniforms must be set even if material didn't change
  21358. // auto-setting of texture unit for bone texture must go before other textures
  21359. // otherwise textures used for skinning can take over texture units reserved for other material textures
  21360. if ( material.skinning ) {
  21361. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  21362. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  21363. var skeleton = object.skeleton;
  21364. if ( skeleton ) {
  21365. var bones = skeleton.bones;
  21366. if ( capabilities.floatVertexTextures ) {
  21367. if ( skeleton.boneTexture === undefined ) {
  21368. // layout (1 matrix = 4 pixels)
  21369. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  21370. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  21371. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  21372. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  21373. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  21374. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  21375. size = MathUtils.ceilPowerOfTwo( size );
  21376. size = Math.max( size, 4 );
  21377. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  21378. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  21379. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  21380. skeleton.boneMatrices = boneMatrices;
  21381. skeleton.boneTexture = boneTexture;
  21382. skeleton.boneTextureSize = size;
  21383. }
  21384. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  21385. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  21386. } else {
  21387. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  21388. }
  21389. }
  21390. }
  21391. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  21392. materialProperties.receiveShadow = object.receiveShadow;
  21393. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  21394. }
  21395. if ( refreshMaterial ) {
  21396. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  21397. if ( materialProperties.needsLights ) {
  21398. // the current material requires lighting info
  21399. // note: all lighting uniforms are always set correctly
  21400. // they simply reference the renderer's state for their
  21401. // values
  21402. //
  21403. // use the current material's .needsUpdate flags to set
  21404. // the GL state when required
  21405. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  21406. }
  21407. // refresh uniforms common to several materials
  21408. if ( fog && material.fog ) {
  21409. materials.refreshFogUniforms( m_uniforms, fog );
  21410. }
  21411. materials.refreshMaterialUniforms( m_uniforms, material, environment, _pixelRatio, _height );
  21412. // RectAreaLight Texture
  21413. // TODO (mrdoob): Find a nicer implementation
  21414. if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; }
  21415. if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; }
  21416. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  21417. }
  21418. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  21419. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  21420. material.uniformsNeedUpdate = false;
  21421. }
  21422. if ( material.isSpriteMaterial ) {
  21423. p_uniforms.setValue( _gl, 'center', object.center );
  21424. }
  21425. // common matrices
  21426. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  21427. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  21428. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  21429. return program;
  21430. }
  21431. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  21432. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  21433. uniforms.ambientLightColor.needsUpdate = value;
  21434. uniforms.lightProbe.needsUpdate = value;
  21435. uniforms.directionalLights.needsUpdate = value;
  21436. uniforms.directionalLightShadows.needsUpdate = value;
  21437. uniforms.pointLights.needsUpdate = value;
  21438. uniforms.pointLightShadows.needsUpdate = value;
  21439. uniforms.spotLights.needsUpdate = value;
  21440. uniforms.spotLightShadows.needsUpdate = value;
  21441. uniforms.rectAreaLights.needsUpdate = value;
  21442. uniforms.hemisphereLights.needsUpdate = value;
  21443. }
  21444. function materialNeedsLights( material ) {
  21445. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  21446. material.isMeshStandardMaterial || material.isShadowMaterial ||
  21447. ( material.isShaderMaterial && material.lights === true );
  21448. }
  21449. // this.setTexture2D = setTexture2D;
  21450. this.setTexture2D = ( function () {
  21451. var warned = false;
  21452. // backwards compatibility: peel texture.texture
  21453. return function setTexture2D( texture, slot ) {
  21454. if ( texture && texture.isWebGLRenderTarget ) {
  21455. if ( ! warned ) {
  21456. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  21457. warned = true;
  21458. }
  21459. texture = texture.texture;
  21460. }
  21461. textures.setTexture2D( texture, slot );
  21462. };
  21463. }() );
  21464. //
  21465. this.setFramebuffer = function ( value ) {
  21466. if ( _framebuffer !== value && _currentRenderTarget === null ) { _gl.bindFramebuffer( 36160, value ); }
  21467. _framebuffer = value;
  21468. };
  21469. this.getActiveCubeFace = function () {
  21470. return _currentActiveCubeFace;
  21471. };
  21472. this.getActiveMipmapLevel = function () {
  21473. return _currentActiveMipmapLevel;
  21474. };
  21475. this.getRenderTarget = function () {
  21476. return _currentRenderTarget;
  21477. };
  21478. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
  21479. _currentRenderTarget = renderTarget;
  21480. _currentActiveCubeFace = activeCubeFace;
  21481. _currentActiveMipmapLevel = activeMipmapLevel;
  21482. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  21483. textures.setupRenderTarget( renderTarget );
  21484. }
  21485. var framebuffer = _framebuffer;
  21486. var isCube = false;
  21487. if ( renderTarget ) {
  21488. var _webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  21489. if ( renderTarget.isWebGLCubeRenderTarget ) {
  21490. framebuffer = _webglFramebuffer[ activeCubeFace || 0 ];
  21491. isCube = true;
  21492. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  21493. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  21494. } else {
  21495. framebuffer = _webglFramebuffer;
  21496. }
  21497. _currentViewport.copy( renderTarget.viewport );
  21498. _currentScissor.copy( renderTarget.scissor );
  21499. _currentScissorTest = renderTarget.scissorTest;
  21500. } else {
  21501. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  21502. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  21503. _currentScissorTest = _scissorTest;
  21504. }
  21505. if ( _currentFramebuffer !== framebuffer ) {
  21506. _gl.bindFramebuffer( 36160, framebuffer );
  21507. _currentFramebuffer = framebuffer;
  21508. }
  21509. state.viewport( _currentViewport );
  21510. state.scissor( _currentScissor );
  21511. state.setScissorTest( _currentScissorTest );
  21512. if ( isCube ) {
  21513. var textureProperties = properties.get( renderTarget.texture );
  21514. _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
  21515. }
  21516. };
  21517. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  21518. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  21519. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  21520. return;
  21521. }
  21522. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  21523. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  21524. framebuffer = framebuffer[ activeCubeFaceIndex ];
  21525. }
  21526. if ( framebuffer ) {
  21527. var restore = false;
  21528. if ( framebuffer !== _currentFramebuffer ) {
  21529. _gl.bindFramebuffer( 36160, framebuffer );
  21530. restore = true;
  21531. }
  21532. try {
  21533. var texture = renderTarget.texture;
  21534. var textureFormat = texture.format;
  21535. var textureType = texture.type;
  21536. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  21537. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  21538. return;
  21539. }
  21540. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  21541. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  21542. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  21543. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  21544. return;
  21545. }
  21546. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  21547. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  21548. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  21549. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  21550. }
  21551. } else {
  21552. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  21553. }
  21554. } finally {
  21555. if ( restore ) {
  21556. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  21557. }
  21558. }
  21559. }
  21560. };
  21561. this.copyFramebufferToTexture = function ( position, texture, level ) {
  21562. if ( level === undefined ) { level = 0; }
  21563. var levelScale = Math.pow( 2, - level );
  21564. var width = Math.floor( texture.image.width * levelScale );
  21565. var height = Math.floor( texture.image.height * levelScale );
  21566. var glFormat = utils.convert( texture.format );
  21567. textures.setTexture2D( texture, 0 );
  21568. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  21569. state.unbindTexture();
  21570. };
  21571. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  21572. if ( level === undefined ) { level = 0; }
  21573. var width = srcTexture.image.width;
  21574. var height = srcTexture.image.height;
  21575. var glFormat = utils.convert( dstTexture.format );
  21576. var glType = utils.convert( dstTexture.type );
  21577. textures.setTexture2D( dstTexture, 0 );
  21578. // As another texture upload may have changed pixelStorei
  21579. // parameters, make sure they are correct for the dstTexture
  21580. _gl.pixelStorei( 37440, dstTexture.flipY );
  21581. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  21582. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  21583. if ( srcTexture.isDataTexture ) {
  21584. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  21585. } else {
  21586. if ( srcTexture.isCompressedTexture ) {
  21587. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  21588. } else {
  21589. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  21590. }
  21591. }
  21592. // Generate mipmaps only when copying level 0
  21593. if ( level === 0 && dstTexture.generateMipmaps ) { _gl.generateMipmap( 3553 ); }
  21594. state.unbindTexture();
  21595. };
  21596. this.initTexture = function ( texture ) {
  21597. textures.setTexture2D( texture, 0 );
  21598. state.unbindTexture();
  21599. };
  21600. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  21601. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  21602. }
  21603. }
  21604. function WebGL1Renderer( parameters ) {
  21605. WebGLRenderer.call( this, parameters );
  21606. }
  21607. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  21608. constructor: WebGL1Renderer,
  21609. isWebGL1Renderer: true
  21610. } );
  21611. function FogExp2( color, density ) {
  21612. this.name = '';
  21613. this.color = new Color( color );
  21614. this.density = ( density !== undefined ) ? density : 0.00025;
  21615. }
  21616. Object.assign( FogExp2.prototype, {
  21617. isFogExp2: true,
  21618. clone: function () {
  21619. return new FogExp2( this.color, this.density );
  21620. },
  21621. toJSON: function ( /* meta */ ) {
  21622. return {
  21623. type: 'FogExp2',
  21624. color: this.color.getHex(),
  21625. density: this.density
  21626. };
  21627. }
  21628. } );
  21629. function Fog( color, near, far ) {
  21630. this.name = '';
  21631. this.color = new Color( color );
  21632. this.near = ( near !== undefined ) ? near : 1;
  21633. this.far = ( far !== undefined ) ? far : 1000;
  21634. }
  21635. Object.assign( Fog.prototype, {
  21636. isFog: true,
  21637. clone: function () {
  21638. return new Fog( this.color, this.near, this.far );
  21639. },
  21640. toJSON: function ( /* meta */ ) {
  21641. return {
  21642. type: 'Fog',
  21643. color: this.color.getHex(),
  21644. near: this.near,
  21645. far: this.far
  21646. };
  21647. }
  21648. } );
  21649. function InterleavedBuffer( array, stride ) {
  21650. this.array = array;
  21651. this.stride = stride;
  21652. this.count = array !== undefined ? array.length / stride : 0;
  21653. this.usage = StaticDrawUsage;
  21654. this.updateRange = { offset: 0, count: - 1 };
  21655. this.version = 0;
  21656. this.uuid = MathUtils.generateUUID();
  21657. }
  21658. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  21659. set: function ( value ) {
  21660. if ( value === true ) { this.version ++; }
  21661. }
  21662. } );
  21663. Object.assign( InterleavedBuffer.prototype, {
  21664. isInterleavedBuffer: true,
  21665. onUploadCallback: function () {},
  21666. setUsage: function ( value ) {
  21667. this.usage = value;
  21668. return this;
  21669. },
  21670. copy: function ( source ) {
  21671. this.array = new source.array.constructor( source.array );
  21672. this.count = source.count;
  21673. this.stride = source.stride;
  21674. this.usage = source.usage;
  21675. return this;
  21676. },
  21677. copyAt: function ( index1, attribute, index2 ) {
  21678. index1 *= this.stride;
  21679. index2 *= attribute.stride;
  21680. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21681. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21682. }
  21683. return this;
  21684. },
  21685. set: function ( value, offset ) {
  21686. if ( offset === undefined ) { offset = 0; }
  21687. this.array.set( value, offset );
  21688. return this;
  21689. },
  21690. clone: function ( data ) {
  21691. if ( data.arrayBuffers === undefined ) {
  21692. data.arrayBuffers = {};
  21693. }
  21694. if ( this.array.buffer._uuid === undefined ) {
  21695. this.array.buffer._uuid = MathUtils.generateUUID();
  21696. }
  21697. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  21698. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  21699. }
  21700. var array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  21701. var ib = new InterleavedBuffer( array, this.stride );
  21702. ib.setUsage( this.usage );
  21703. return ib;
  21704. },
  21705. onUpload: function ( callback ) {
  21706. this.onUploadCallback = callback;
  21707. return this;
  21708. },
  21709. toJSON: function ( data ) {
  21710. if ( data.arrayBuffers === undefined ) {
  21711. data.arrayBuffers = {};
  21712. }
  21713. // generate UUID for array buffer if necessary
  21714. if ( this.array.buffer._uuid === undefined ) {
  21715. this.array.buffer._uuid = MathUtils.generateUUID();
  21716. }
  21717. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  21718. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  21719. }
  21720. //
  21721. return {
  21722. uuid: this.uuid,
  21723. buffer: this.array.buffer._uuid,
  21724. type: this.array.constructor.name,
  21725. stride: this.stride
  21726. };
  21727. }
  21728. } );
  21729. var _vector$6 = new Vector3();
  21730. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21731. this.name = '';
  21732. this.data = interleavedBuffer;
  21733. this.itemSize = itemSize;
  21734. this.offset = offset;
  21735. this.normalized = normalized === true;
  21736. }
  21737. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  21738. count: {
  21739. get: function () {
  21740. return this.data.count;
  21741. }
  21742. },
  21743. array: {
  21744. get: function () {
  21745. return this.data.array;
  21746. }
  21747. },
  21748. needsUpdate: {
  21749. set: function ( value ) {
  21750. this.data.needsUpdate = value;
  21751. }
  21752. }
  21753. } );
  21754. Object.assign( InterleavedBufferAttribute.prototype, {
  21755. isInterleavedBufferAttribute: true,
  21756. applyMatrix4: function ( m ) {
  21757. for ( var i = 0, l = this.data.count; i < l; i ++ ) {
  21758. _vector$6.x = this.getX( i );
  21759. _vector$6.y = this.getY( i );
  21760. _vector$6.z = this.getZ( i );
  21761. _vector$6.applyMatrix4( m );
  21762. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  21763. }
  21764. return this;
  21765. },
  21766. setX: function ( index, x ) {
  21767. this.data.array[ index * this.data.stride + this.offset ] = x;
  21768. return this;
  21769. },
  21770. setY: function ( index, y ) {
  21771. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21772. return this;
  21773. },
  21774. setZ: function ( index, z ) {
  21775. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21776. return this;
  21777. },
  21778. setW: function ( index, w ) {
  21779. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21780. return this;
  21781. },
  21782. getX: function ( index ) {
  21783. return this.data.array[ index * this.data.stride + this.offset ];
  21784. },
  21785. getY: function ( index ) {
  21786. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21787. },
  21788. getZ: function ( index ) {
  21789. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21790. },
  21791. getW: function ( index ) {
  21792. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21793. },
  21794. setXY: function ( index, x, y ) {
  21795. index = index * this.data.stride + this.offset;
  21796. this.data.array[ index + 0 ] = x;
  21797. this.data.array[ index + 1 ] = y;
  21798. return this;
  21799. },
  21800. setXYZ: function ( index, x, y, z ) {
  21801. index = index * this.data.stride + this.offset;
  21802. this.data.array[ index + 0 ] = x;
  21803. this.data.array[ index + 1 ] = y;
  21804. this.data.array[ index + 2 ] = z;
  21805. return this;
  21806. },
  21807. setXYZW: function ( index, x, y, z, w ) {
  21808. index = index * this.data.stride + this.offset;
  21809. this.data.array[ index + 0 ] = x;
  21810. this.data.array[ index + 1 ] = y;
  21811. this.data.array[ index + 2 ] = z;
  21812. this.data.array[ index + 3 ] = w;
  21813. return this;
  21814. },
  21815. clone: function ( data ) {
  21816. if ( data === undefined ) {
  21817. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  21818. var array = [];
  21819. for ( var i = 0; i < this.count; i ++ ) {
  21820. var index = i * this.data.stride + this.offset;
  21821. for ( var j = 0; j < this.itemSize; j ++ ) {
  21822. array.push( this.data.array[ index + j ] );
  21823. }
  21824. }
  21825. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  21826. } else {
  21827. if ( data.interleavedBuffers === undefined ) {
  21828. data.interleavedBuffers = {};
  21829. }
  21830. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  21831. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  21832. }
  21833. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  21834. }
  21835. },
  21836. toJSON: function ( data ) {
  21837. if ( data === undefined ) {
  21838. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  21839. var array = [];
  21840. for ( var i = 0; i < this.count; i ++ ) {
  21841. var index = i * this.data.stride + this.offset;
  21842. for ( var j = 0; j < this.itemSize; j ++ ) {
  21843. array.push( this.data.array[ index + j ] );
  21844. }
  21845. }
  21846. // deinterleave data and save it as an ordinary buffer attribute for now
  21847. return {
  21848. itemSize: this.itemSize,
  21849. type: this.array.constructor.name,
  21850. array: array,
  21851. normalized: this.normalized
  21852. };
  21853. } else {
  21854. // save as true interlaved attribtue
  21855. if ( data.interleavedBuffers === undefined ) {
  21856. data.interleavedBuffers = {};
  21857. }
  21858. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  21859. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  21860. }
  21861. return {
  21862. isInterleavedBufferAttribute: true,
  21863. itemSize: this.itemSize,
  21864. data: this.data.uuid,
  21865. offset: this.offset,
  21866. normalized: this.normalized
  21867. };
  21868. }
  21869. }
  21870. } );
  21871. /**
  21872. * parameters = {
  21873. * color: <hex>,
  21874. * map: new THREE.Texture( <Image> ),
  21875. * alphaMap: new THREE.Texture( <Image> ),
  21876. * rotation: <float>,
  21877. * sizeAttenuation: <bool>
  21878. * }
  21879. */
  21880. function SpriteMaterial( parameters ) {
  21881. Material.call( this );
  21882. this.type = 'SpriteMaterial';
  21883. this.color = new Color( 0xffffff );
  21884. this.map = null;
  21885. this.alphaMap = null;
  21886. this.rotation = 0;
  21887. this.sizeAttenuation = true;
  21888. this.transparent = true;
  21889. this.setValues( parameters );
  21890. }
  21891. SpriteMaterial.prototype = Object.create( Material.prototype );
  21892. SpriteMaterial.prototype.constructor = SpriteMaterial;
  21893. SpriteMaterial.prototype.isSpriteMaterial = true;
  21894. SpriteMaterial.prototype.copy = function ( source ) {
  21895. Material.prototype.copy.call( this, source );
  21896. this.color.copy( source.color );
  21897. this.map = source.map;
  21898. this.alphaMap = source.alphaMap;
  21899. this.rotation = source.rotation;
  21900. this.sizeAttenuation = source.sizeAttenuation;
  21901. return this;
  21902. };
  21903. var _geometry;
  21904. var _intersectPoint = new Vector3();
  21905. var _worldScale = new Vector3();
  21906. var _mvPosition = new Vector3();
  21907. var _alignedPosition = new Vector2();
  21908. var _rotatedPosition = new Vector2();
  21909. var _viewWorldMatrix = new Matrix4();
  21910. var _vA$1 = new Vector3();
  21911. var _vB$1 = new Vector3();
  21912. var _vC$1 = new Vector3();
  21913. var _uvA$1 = new Vector2();
  21914. var _uvB$1 = new Vector2();
  21915. var _uvC$1 = new Vector2();
  21916. function Sprite( material ) {
  21917. Object3D.call( this );
  21918. this.type = 'Sprite';
  21919. if ( _geometry === undefined ) {
  21920. _geometry = new BufferGeometry();
  21921. var float32Array = new Float32Array( [
  21922. - 0.5, - 0.5, 0, 0, 0,
  21923. 0.5, - 0.5, 0, 1, 0,
  21924. 0.5, 0.5, 0, 1, 1,
  21925. - 0.5, 0.5, 0, 0, 1
  21926. ] );
  21927. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  21928. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  21929. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  21930. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  21931. }
  21932. this.geometry = _geometry;
  21933. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  21934. this.center = new Vector2( 0.5, 0.5 );
  21935. }
  21936. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21937. constructor: Sprite,
  21938. isSprite: true,
  21939. raycast: function ( raycaster, intersects ) {
  21940. if ( raycaster.camera === null ) {
  21941. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  21942. }
  21943. _worldScale.setFromMatrixScale( this.matrixWorld );
  21944. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  21945. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  21946. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  21947. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  21948. _worldScale.multiplyScalar( - _mvPosition.z );
  21949. }
  21950. var rotation = this.material.rotation;
  21951. var sin, cos;
  21952. if ( rotation !== 0 ) {
  21953. cos = Math.cos( rotation );
  21954. sin = Math.sin( rotation );
  21955. }
  21956. var center = this.center;
  21957. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21958. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21959. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21960. _uvA$1.set( 0, 0 );
  21961. _uvB$1.set( 1, 0 );
  21962. _uvC$1.set( 1, 1 );
  21963. // check first triangle
  21964. var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  21965. if ( intersect === null ) {
  21966. // check second triangle
  21967. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21968. _uvB$1.set( 0, 1 );
  21969. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  21970. if ( intersect === null ) {
  21971. return;
  21972. }
  21973. }
  21974. var distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  21975. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  21976. intersects.push( {
  21977. distance: distance,
  21978. point: _intersectPoint.clone(),
  21979. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  21980. face: null,
  21981. object: this
  21982. } );
  21983. },
  21984. copy: function ( source ) {
  21985. Object3D.prototype.copy.call( this, source );
  21986. if ( source.center !== undefined ) { this.center.copy( source.center ); }
  21987. this.material = source.material;
  21988. return this;
  21989. }
  21990. } );
  21991. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  21992. // compute position in camera space
  21993. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  21994. // to check if rotation is not zero
  21995. if ( sin !== undefined ) {
  21996. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  21997. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  21998. } else {
  21999. _rotatedPosition.copy( _alignedPosition );
  22000. }
  22001. vertexPosition.copy( mvPosition );
  22002. vertexPosition.x += _rotatedPosition.x;
  22003. vertexPosition.y += _rotatedPosition.y;
  22004. // transform to world space
  22005. vertexPosition.applyMatrix4( _viewWorldMatrix );
  22006. }
  22007. var _v1$4 = new Vector3();
  22008. var _v2$2 = new Vector3();
  22009. function LOD() {
  22010. Object3D.call( this );
  22011. this._currentLevel = 0;
  22012. this.type = 'LOD';
  22013. Object.defineProperties( this, {
  22014. levels: {
  22015. enumerable: true,
  22016. value: []
  22017. }
  22018. } );
  22019. this.autoUpdate = true;
  22020. }
  22021. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22022. constructor: LOD,
  22023. isLOD: true,
  22024. copy: function ( source ) {
  22025. Object3D.prototype.copy.call( this, source, false );
  22026. var levels = source.levels;
  22027. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  22028. var level = levels[ i ];
  22029. this.addLevel( level.object.clone(), level.distance );
  22030. }
  22031. this.autoUpdate = source.autoUpdate;
  22032. return this;
  22033. },
  22034. addLevel: function ( object, distance ) {
  22035. if ( distance === undefined ) { distance = 0; }
  22036. distance = Math.abs( distance );
  22037. var levels = this.levels;
  22038. var l;
  22039. for ( l = 0; l < levels.length; l ++ ) {
  22040. if ( distance < levels[ l ].distance ) {
  22041. break;
  22042. }
  22043. }
  22044. levels.splice( l, 0, { distance: distance, object: object } );
  22045. this.add( object );
  22046. return this;
  22047. },
  22048. getCurrentLevel: function () {
  22049. return this._currentLevel;
  22050. },
  22051. getObjectForDistance: function ( distance ) {
  22052. var levels = this.levels;
  22053. if ( levels.length > 0 ) {
  22054. var i, l;
  22055. for ( i = 1, l = levels.length; i < l; i ++ ) {
  22056. if ( distance < levels[ i ].distance ) {
  22057. break;
  22058. }
  22059. }
  22060. return levels[ i - 1 ].object;
  22061. }
  22062. return null;
  22063. },
  22064. raycast: function ( raycaster, intersects ) {
  22065. var levels = this.levels;
  22066. if ( levels.length > 0 ) {
  22067. _v1$4.setFromMatrixPosition( this.matrixWorld );
  22068. var distance = raycaster.ray.origin.distanceTo( _v1$4 );
  22069. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  22070. }
  22071. },
  22072. update: function ( camera ) {
  22073. var levels = this.levels;
  22074. if ( levels.length > 1 ) {
  22075. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  22076. _v2$2.setFromMatrixPosition( this.matrixWorld );
  22077. var distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  22078. levels[ 0 ].object.visible = true;
  22079. var i, l;
  22080. for ( i = 1, l = levels.length; i < l; i ++ ) {
  22081. if ( distance >= levels[ i ].distance ) {
  22082. levels[ i - 1 ].object.visible = false;
  22083. levels[ i ].object.visible = true;
  22084. } else {
  22085. break;
  22086. }
  22087. }
  22088. this._currentLevel = i - 1;
  22089. for ( ; i < l; i ++ ) {
  22090. levels[ i ].object.visible = false;
  22091. }
  22092. }
  22093. },
  22094. toJSON: function ( meta ) {
  22095. var data = Object3D.prototype.toJSON.call( this, meta );
  22096. if ( this.autoUpdate === false ) { data.object.autoUpdate = false; }
  22097. data.object.levels = [];
  22098. var levels = this.levels;
  22099. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  22100. var level = levels[ i ];
  22101. data.object.levels.push( {
  22102. object: level.object.uuid,
  22103. distance: level.distance
  22104. } );
  22105. }
  22106. return data;
  22107. }
  22108. } );
  22109. function SkinnedMesh( geometry, material ) {
  22110. if ( geometry && geometry.isGeometry ) {
  22111. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  22112. }
  22113. Mesh.call( this, geometry, material );
  22114. this.type = 'SkinnedMesh';
  22115. this.bindMode = 'attached';
  22116. this.bindMatrix = new Matrix4();
  22117. this.bindMatrixInverse = new Matrix4();
  22118. }
  22119. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  22120. constructor: SkinnedMesh,
  22121. isSkinnedMesh: true,
  22122. copy: function ( source ) {
  22123. Mesh.prototype.copy.call( this, source );
  22124. this.bindMode = source.bindMode;
  22125. this.bindMatrix.copy( source.bindMatrix );
  22126. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  22127. this.skeleton = source.skeleton;
  22128. return this;
  22129. },
  22130. bind: function ( skeleton, bindMatrix ) {
  22131. this.skeleton = skeleton;
  22132. if ( bindMatrix === undefined ) {
  22133. this.updateMatrixWorld( true );
  22134. this.skeleton.calculateInverses();
  22135. bindMatrix = this.matrixWorld;
  22136. }
  22137. this.bindMatrix.copy( bindMatrix );
  22138. this.bindMatrixInverse.getInverse( bindMatrix );
  22139. },
  22140. pose: function () {
  22141. this.skeleton.pose();
  22142. },
  22143. normalizeSkinWeights: function () {
  22144. var vector = new Vector4();
  22145. var skinWeight = this.geometry.attributes.skinWeight;
  22146. for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
  22147. vector.x = skinWeight.getX( i );
  22148. vector.y = skinWeight.getY( i );
  22149. vector.z = skinWeight.getZ( i );
  22150. vector.w = skinWeight.getW( i );
  22151. var scale = 1.0 / vector.manhattanLength();
  22152. if ( scale !== Infinity ) {
  22153. vector.multiplyScalar( scale );
  22154. } else {
  22155. vector.set( 1, 0, 0, 0 ); // do something reasonable
  22156. }
  22157. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  22158. }
  22159. },
  22160. updateMatrixWorld: function ( force ) {
  22161. Mesh.prototype.updateMatrixWorld.call( this, force );
  22162. if ( this.bindMode === 'attached' ) {
  22163. this.bindMatrixInverse.getInverse( this.matrixWorld );
  22164. } else if ( this.bindMode === 'detached' ) {
  22165. this.bindMatrixInverse.getInverse( this.bindMatrix );
  22166. } else {
  22167. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  22168. }
  22169. },
  22170. boneTransform: ( function () {
  22171. var basePosition = new Vector3();
  22172. var skinIndex = new Vector4();
  22173. var skinWeight = new Vector4();
  22174. var vector = new Vector3();
  22175. var matrix = new Matrix4();
  22176. return function ( index, target ) {
  22177. var skeleton = this.skeleton;
  22178. var geometry = this.geometry;
  22179. skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  22180. skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  22181. basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  22182. target.set( 0, 0, 0 );
  22183. for ( var i = 0; i < 4; i ++ ) {
  22184. var weight = skinWeight.getComponent( i );
  22185. if ( weight !== 0 ) {
  22186. var boneIndex = skinIndex.getComponent( i );
  22187. matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  22188. target.addScaledVector( vector.copy( basePosition ).applyMatrix4( matrix ), weight );
  22189. }
  22190. }
  22191. return target.applyMatrix4( this.bindMatrixInverse );
  22192. };
  22193. }() )
  22194. } );
  22195. var _offsetMatrix = new Matrix4();
  22196. var _identityMatrix = new Matrix4();
  22197. function Skeleton( bones, boneInverses ) {
  22198. // copy the bone array
  22199. bones = bones || [];
  22200. this.bones = bones.slice( 0 );
  22201. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  22202. this.frame = - 1;
  22203. // use the supplied bone inverses or calculate the inverses
  22204. if ( boneInverses === undefined ) {
  22205. this.calculateInverses();
  22206. } else {
  22207. if ( this.bones.length === boneInverses.length ) {
  22208. this.boneInverses = boneInverses.slice( 0 );
  22209. } else {
  22210. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  22211. this.boneInverses = [];
  22212. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  22213. this.boneInverses.push( new Matrix4() );
  22214. }
  22215. }
  22216. }
  22217. }
  22218. Object.assign( Skeleton.prototype, {
  22219. calculateInverses: function () {
  22220. this.boneInverses = [];
  22221. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  22222. var inverse = new Matrix4();
  22223. if ( this.bones[ i ] ) {
  22224. inverse.getInverse( this.bones[ i ].matrixWorld );
  22225. }
  22226. this.boneInverses.push( inverse );
  22227. }
  22228. },
  22229. pose: function () {
  22230. // recover the bind-time world matrices
  22231. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  22232. var bone = this.bones[ i ];
  22233. if ( bone ) {
  22234. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  22235. }
  22236. }
  22237. // compute the local matrices, positions, rotations and scales
  22238. for ( var i$1 = 0, il$1 = this.bones.length; i$1 < il$1; i$1 ++ ) {
  22239. var bone$1 = this.bones[ i$1 ];
  22240. if ( bone$1 ) {
  22241. if ( bone$1.parent && bone$1.parent.isBone ) {
  22242. bone$1.matrix.getInverse( bone$1.parent.matrixWorld );
  22243. bone$1.matrix.multiply( bone$1.matrixWorld );
  22244. } else {
  22245. bone$1.matrix.copy( bone$1.matrixWorld );
  22246. }
  22247. bone$1.matrix.decompose( bone$1.position, bone$1.quaternion, bone$1.scale );
  22248. }
  22249. }
  22250. },
  22251. update: function () {
  22252. var bones = this.bones;
  22253. var boneInverses = this.boneInverses;
  22254. var boneMatrices = this.boneMatrices;
  22255. var boneTexture = this.boneTexture;
  22256. // flatten bone matrices to array
  22257. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  22258. // compute the offset between the current and the original transform
  22259. var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  22260. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  22261. _offsetMatrix.toArray( boneMatrices, i * 16 );
  22262. }
  22263. if ( boneTexture !== undefined ) {
  22264. boneTexture.needsUpdate = true;
  22265. }
  22266. },
  22267. clone: function () {
  22268. return new Skeleton( this.bones, this.boneInverses );
  22269. },
  22270. getBoneByName: function ( name ) {
  22271. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  22272. var bone = this.bones[ i ];
  22273. if ( bone.name === name ) {
  22274. return bone;
  22275. }
  22276. }
  22277. return undefined;
  22278. },
  22279. dispose: function ( ) {
  22280. if ( this.boneTexture ) {
  22281. this.boneTexture.dispose();
  22282. this.boneTexture = undefined;
  22283. }
  22284. }
  22285. } );
  22286. function Bone() {
  22287. Object3D.call( this );
  22288. this.type = 'Bone';
  22289. }
  22290. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22291. constructor: Bone,
  22292. isBone: true
  22293. } );
  22294. var _instanceLocalMatrix = new Matrix4();
  22295. var _instanceWorldMatrix = new Matrix4();
  22296. var _instanceIntersects = [];
  22297. var _mesh = new Mesh();
  22298. function InstancedMesh( geometry, material, count ) {
  22299. Mesh.call( this, geometry, material );
  22300. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  22301. this.count = count;
  22302. this.frustumCulled = false;
  22303. }
  22304. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  22305. constructor: InstancedMesh,
  22306. isInstancedMesh: true,
  22307. copy: function ( source ) {
  22308. Mesh.prototype.copy.call( this, source );
  22309. this.instanceMatrix.copy( source.instanceMatrix );
  22310. this.count = source.count;
  22311. return this;
  22312. },
  22313. getMatrixAt: function ( index, matrix ) {
  22314. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  22315. },
  22316. raycast: function ( raycaster, intersects ) {
  22317. var matrixWorld = this.matrixWorld;
  22318. var raycastTimes = this.count;
  22319. _mesh.geometry = this.geometry;
  22320. _mesh.material = this.material;
  22321. if ( _mesh.material === undefined ) { return; }
  22322. for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  22323. // calculate the world matrix for each instance
  22324. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  22325. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  22326. // the mesh represents this single instance
  22327. _mesh.matrixWorld = _instanceWorldMatrix;
  22328. _mesh.raycast( raycaster, _instanceIntersects );
  22329. // process the result of raycast
  22330. for ( var i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  22331. var intersect = _instanceIntersects[ i ];
  22332. intersect.instanceId = instanceId;
  22333. intersect.object = this;
  22334. intersects.push( intersect );
  22335. }
  22336. _instanceIntersects.length = 0;
  22337. }
  22338. },
  22339. setMatrixAt: function ( index, matrix ) {
  22340. matrix.toArray( this.instanceMatrix.array, index * 16 );
  22341. },
  22342. updateMorphTargets: function () {
  22343. }
  22344. } );
  22345. /**
  22346. * parameters = {
  22347. * color: <hex>,
  22348. * opacity: <float>,
  22349. *
  22350. * linewidth: <float>,
  22351. * linecap: "round",
  22352. * linejoin: "round"
  22353. * }
  22354. */
  22355. function LineBasicMaterial( parameters ) {
  22356. Material.call( this );
  22357. this.type = 'LineBasicMaterial';
  22358. this.color = new Color( 0xffffff );
  22359. this.linewidth = 1;
  22360. this.linecap = 'round';
  22361. this.linejoin = 'round';
  22362. this.morphTargets = false;
  22363. this.setValues( parameters );
  22364. }
  22365. LineBasicMaterial.prototype = Object.create( Material.prototype );
  22366. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  22367. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  22368. LineBasicMaterial.prototype.copy = function ( source ) {
  22369. Material.prototype.copy.call( this, source );
  22370. this.color.copy( source.color );
  22371. this.linewidth = source.linewidth;
  22372. this.linecap = source.linecap;
  22373. this.linejoin = source.linejoin;
  22374. this.morphTargets = source.morphTargets;
  22375. return this;
  22376. };
  22377. var _start = new Vector3();
  22378. var _end = new Vector3();
  22379. var _inverseMatrix$1 = new Matrix4();
  22380. var _ray$1 = new Ray();
  22381. var _sphere$2 = new Sphere();
  22382. function Line( geometry, material, mode ) {
  22383. if ( mode === 1 ) {
  22384. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  22385. }
  22386. Object3D.call( this );
  22387. this.type = 'Line';
  22388. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22389. this.material = material !== undefined ? material : new LineBasicMaterial();
  22390. this.updateMorphTargets();
  22391. }
  22392. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22393. constructor: Line,
  22394. isLine: true,
  22395. copy: function ( source ) {
  22396. Object3D.prototype.copy.call( this, source );
  22397. this.material = source.material;
  22398. this.geometry = source.geometry;
  22399. return this;
  22400. },
  22401. computeLineDistances: function () {
  22402. var geometry = this.geometry;
  22403. if ( geometry.isBufferGeometry ) {
  22404. // we assume non-indexed geometry
  22405. if ( geometry.index === null ) {
  22406. var positionAttribute = geometry.attributes.position;
  22407. var lineDistances = [ 0 ];
  22408. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  22409. _start.fromBufferAttribute( positionAttribute, i - 1 );
  22410. _end.fromBufferAttribute( positionAttribute, i );
  22411. lineDistances[ i ] = lineDistances[ i - 1 ];
  22412. lineDistances[ i ] += _start.distanceTo( _end );
  22413. }
  22414. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  22415. } else {
  22416. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  22417. }
  22418. } else if ( geometry.isGeometry ) {
  22419. var vertices = geometry.vertices;
  22420. var lineDistances$1 = geometry.lineDistances;
  22421. lineDistances$1[ 0 ] = 0;
  22422. for ( var i$1 = 1, l$1 = vertices.length; i$1 < l$1; i$1 ++ ) {
  22423. lineDistances$1[ i$1 ] = lineDistances$1[ i$1 - 1 ];
  22424. lineDistances$1[ i$1 ] += vertices[ i$1 - 1 ].distanceTo( vertices[ i$1 ] );
  22425. }
  22426. }
  22427. return this;
  22428. },
  22429. raycast: function ( raycaster, intersects ) {
  22430. var geometry = this.geometry;
  22431. var matrixWorld = this.matrixWorld;
  22432. var threshold = raycaster.params.Line.threshold;
  22433. // Checking boundingSphere distance to ray
  22434. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  22435. _sphere$2.copy( geometry.boundingSphere );
  22436. _sphere$2.applyMatrix4( matrixWorld );
  22437. _sphere$2.radius += threshold;
  22438. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; }
  22439. //
  22440. _inverseMatrix$1.getInverse( matrixWorld );
  22441. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  22442. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  22443. var localThresholdSq = localThreshold * localThreshold;
  22444. var vStart = new Vector3();
  22445. var vEnd = new Vector3();
  22446. var interSegment = new Vector3();
  22447. var interRay = new Vector3();
  22448. var step = ( this && this.isLineSegments ) ? 2 : 1;
  22449. if ( geometry.isBufferGeometry ) {
  22450. var index = geometry.index;
  22451. var attributes = geometry.attributes;
  22452. var positions = attributes.position.array;
  22453. if ( index !== null ) {
  22454. var indices = index.array;
  22455. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  22456. var a = indices[ i ];
  22457. var b = indices[ i + 1 ];
  22458. vStart.fromArray( positions, a * 3 );
  22459. vEnd.fromArray( positions, b * 3 );
  22460. var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  22461. if ( distSq > localThresholdSq ) { continue; }
  22462. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22463. var distance = raycaster.ray.origin.distanceTo( interRay );
  22464. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  22465. intersects.push( {
  22466. distance: distance,
  22467. // What do we want? intersection point on the ray or on the segment??
  22468. // point: raycaster.ray.at( distance ),
  22469. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22470. index: i,
  22471. face: null,
  22472. faceIndex: null,
  22473. object: this
  22474. } );
  22475. }
  22476. } else {
  22477. for ( var i$1 = 0, l$1 = positions.length / 3 - 1; i$1 < l$1; i$1 += step ) {
  22478. vStart.fromArray( positions, 3 * i$1 );
  22479. vEnd.fromArray( positions, 3 * i$1 + 3 );
  22480. var distSq$1 = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  22481. if ( distSq$1 > localThresholdSq ) { continue; }
  22482. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22483. var distance$1 = raycaster.ray.origin.distanceTo( interRay );
  22484. if ( distance$1 < raycaster.near || distance$1 > raycaster.far ) { continue; }
  22485. intersects.push( {
  22486. distance: distance$1,
  22487. // What do we want? intersection point on the ray or on the segment??
  22488. // point: raycaster.ray.at( distance ),
  22489. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22490. index: i$1,
  22491. face: null,
  22492. faceIndex: null,
  22493. object: this
  22494. } );
  22495. }
  22496. }
  22497. } else if ( geometry.isGeometry ) {
  22498. var vertices = geometry.vertices;
  22499. var nbVertices = vertices.length;
  22500. for ( var i$2 = 0; i$2 < nbVertices - 1; i$2 += step ) {
  22501. var distSq$2 = _ray$1.distanceSqToSegment( vertices[ i$2 ], vertices[ i$2 + 1 ], interRay, interSegment );
  22502. if ( distSq$2 > localThresholdSq ) { continue; }
  22503. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22504. var distance$2 = raycaster.ray.origin.distanceTo( interRay );
  22505. if ( distance$2 < raycaster.near || distance$2 > raycaster.far ) { continue; }
  22506. intersects.push( {
  22507. distance: distance$2,
  22508. // What do we want? intersection point on the ray or on the segment??
  22509. // point: raycaster.ray.at( distance ),
  22510. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22511. index: i$2,
  22512. face: null,
  22513. faceIndex: null,
  22514. object: this
  22515. } );
  22516. }
  22517. }
  22518. },
  22519. updateMorphTargets: function () {
  22520. var geometry = this.geometry;
  22521. if ( geometry.isBufferGeometry ) {
  22522. var morphAttributes = geometry.morphAttributes;
  22523. var keys = Object.keys( morphAttributes );
  22524. if ( keys.length > 0 ) {
  22525. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  22526. if ( morphAttribute !== undefined ) {
  22527. this.morphTargetInfluences = [];
  22528. this.morphTargetDictionary = {};
  22529. for ( var m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  22530. var name = morphAttribute[ m ].name || String( m );
  22531. this.morphTargetInfluences.push( 0 );
  22532. this.morphTargetDictionary[ name ] = m;
  22533. }
  22534. }
  22535. }
  22536. } else {
  22537. var morphTargets = geometry.morphTargets;
  22538. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  22539. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  22540. }
  22541. }
  22542. }
  22543. } );
  22544. var _start$1 = new Vector3();
  22545. var _end$1 = new Vector3();
  22546. function LineSegments( geometry, material ) {
  22547. Line.call( this, geometry, material );
  22548. this.type = 'LineSegments';
  22549. }
  22550. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  22551. constructor: LineSegments,
  22552. isLineSegments: true,
  22553. computeLineDistances: function () {
  22554. var geometry = this.geometry;
  22555. if ( geometry.isBufferGeometry ) {
  22556. // we assume non-indexed geometry
  22557. if ( geometry.index === null ) {
  22558. var positionAttribute = geometry.attributes.position;
  22559. var lineDistances = [];
  22560. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  22561. _start$1.fromBufferAttribute( positionAttribute, i );
  22562. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  22563. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  22564. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  22565. }
  22566. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  22567. } else {
  22568. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  22569. }
  22570. } else if ( geometry.isGeometry ) {
  22571. var vertices = geometry.vertices;
  22572. var lineDistances$1 = geometry.lineDistances;
  22573. for ( var i$1 = 0, l$1 = vertices.length; i$1 < l$1; i$1 += 2 ) {
  22574. _start$1.copy( vertices[ i$1 ] );
  22575. _end$1.copy( vertices[ i$1 + 1 ] );
  22576. lineDistances$1[ i$1 ] = ( i$1 === 0 ) ? 0 : lineDistances$1[ i$1 - 1 ];
  22577. lineDistances$1[ i$1 + 1 ] = lineDistances$1[ i$1 ] + _start$1.distanceTo( _end$1 );
  22578. }
  22579. }
  22580. return this;
  22581. }
  22582. } );
  22583. function LineLoop( geometry, material ) {
  22584. Line.call( this, geometry, material );
  22585. this.type = 'LineLoop';
  22586. }
  22587. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  22588. constructor: LineLoop,
  22589. isLineLoop: true,
  22590. } );
  22591. /**
  22592. * parameters = {
  22593. * color: <hex>,
  22594. * opacity: <float>,
  22595. * map: new THREE.Texture( <Image> ),
  22596. * alphaMap: new THREE.Texture( <Image> ),
  22597. *
  22598. * size: <float>,
  22599. * sizeAttenuation: <bool>
  22600. *
  22601. * morphTargets: <bool>
  22602. * }
  22603. */
  22604. function PointsMaterial( parameters ) {
  22605. Material.call( this );
  22606. this.type = 'PointsMaterial';
  22607. this.color = new Color( 0xffffff );
  22608. this.map = null;
  22609. this.alphaMap = null;
  22610. this.size = 1;
  22611. this.sizeAttenuation = true;
  22612. this.morphTargets = false;
  22613. this.setValues( parameters );
  22614. }
  22615. PointsMaterial.prototype = Object.create( Material.prototype );
  22616. PointsMaterial.prototype.constructor = PointsMaterial;
  22617. PointsMaterial.prototype.isPointsMaterial = true;
  22618. PointsMaterial.prototype.copy = function ( source ) {
  22619. Material.prototype.copy.call( this, source );
  22620. this.color.copy( source.color );
  22621. this.map = source.map;
  22622. this.alphaMap = source.alphaMap;
  22623. this.size = source.size;
  22624. this.sizeAttenuation = source.sizeAttenuation;
  22625. this.morphTargets = source.morphTargets;
  22626. return this;
  22627. };
  22628. var _inverseMatrix$2 = new Matrix4();
  22629. var _ray$2 = new Ray();
  22630. var _sphere$3 = new Sphere();
  22631. var _position$1 = new Vector3();
  22632. function Points( geometry, material ) {
  22633. Object3D.call( this );
  22634. this.type = 'Points';
  22635. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22636. this.material = material !== undefined ? material : new PointsMaterial();
  22637. this.updateMorphTargets();
  22638. }
  22639. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22640. constructor: Points,
  22641. isPoints: true,
  22642. copy: function ( source ) {
  22643. Object3D.prototype.copy.call( this, source );
  22644. this.material = source.material;
  22645. this.geometry = source.geometry;
  22646. return this;
  22647. },
  22648. raycast: function ( raycaster, intersects ) {
  22649. var geometry = this.geometry;
  22650. var matrixWorld = this.matrixWorld;
  22651. var threshold = raycaster.params.Points.threshold;
  22652. // Checking boundingSphere distance to ray
  22653. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  22654. _sphere$3.copy( geometry.boundingSphere );
  22655. _sphere$3.applyMatrix4( matrixWorld );
  22656. _sphere$3.radius += threshold;
  22657. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; }
  22658. //
  22659. _inverseMatrix$2.getInverse( matrixWorld );
  22660. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  22661. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  22662. var localThresholdSq = localThreshold * localThreshold;
  22663. if ( geometry.isBufferGeometry ) {
  22664. var index = geometry.index;
  22665. var attributes = geometry.attributes;
  22666. var positions = attributes.position.array;
  22667. if ( index !== null ) {
  22668. var indices = index.array;
  22669. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  22670. var a = indices[ i ];
  22671. _position$1.fromArray( positions, a * 3 );
  22672. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22673. }
  22674. } else {
  22675. for ( var i$1 = 0, l = positions.length / 3; i$1 < l; i$1 ++ ) {
  22676. _position$1.fromArray( positions, i$1 * 3 );
  22677. testPoint( _position$1, i$1, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22678. }
  22679. }
  22680. } else {
  22681. var vertices = geometry.vertices;
  22682. for ( var i$2 = 0, l$1 = vertices.length; i$2 < l$1; i$2 ++ ) {
  22683. testPoint( vertices[ i$2 ], i$2, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22684. }
  22685. }
  22686. },
  22687. updateMorphTargets: function () {
  22688. var geometry = this.geometry;
  22689. if ( geometry.isBufferGeometry ) {
  22690. var morphAttributes = geometry.morphAttributes;
  22691. var keys = Object.keys( morphAttributes );
  22692. if ( keys.length > 0 ) {
  22693. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  22694. if ( morphAttribute !== undefined ) {
  22695. this.morphTargetInfluences = [];
  22696. this.morphTargetDictionary = {};
  22697. for ( var m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  22698. var name = morphAttribute[ m ].name || String( m );
  22699. this.morphTargetInfluences.push( 0 );
  22700. this.morphTargetDictionary[ name ] = m;
  22701. }
  22702. }
  22703. }
  22704. } else {
  22705. var morphTargets = geometry.morphTargets;
  22706. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  22707. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  22708. }
  22709. }
  22710. }
  22711. } );
  22712. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  22713. var rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  22714. if ( rayPointDistanceSq < localThresholdSq ) {
  22715. var intersectPoint = new Vector3();
  22716. _ray$2.closestPointToPoint( point, intersectPoint );
  22717. intersectPoint.applyMatrix4( matrixWorld );
  22718. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  22719. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  22720. intersects.push( {
  22721. distance: distance,
  22722. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  22723. point: intersectPoint,
  22724. index: index,
  22725. face: null,
  22726. object: object
  22727. } );
  22728. }
  22729. }
  22730. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22731. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22732. this.format = format !== undefined ? format : RGBFormat;
  22733. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  22734. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  22735. this.generateMipmaps = false;
  22736. var scope = this;
  22737. function updateVideo() {
  22738. scope.needsUpdate = true;
  22739. video.requestVideoFrameCallback( updateVideo );
  22740. }
  22741. if ( 'requestVideoFrameCallback' in video ) {
  22742. video.requestVideoFrameCallback( updateVideo );
  22743. }
  22744. }
  22745. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  22746. constructor: VideoTexture,
  22747. isVideoTexture: true,
  22748. update: function () {
  22749. var video = this.image;
  22750. var hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  22751. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  22752. this.needsUpdate = true;
  22753. }
  22754. }
  22755. } );
  22756. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  22757. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  22758. this.image = { width: width, height: height };
  22759. this.mipmaps = mipmaps;
  22760. // no flipping for cube textures
  22761. // (also flipping doesn't work for compressed textures )
  22762. this.flipY = false;
  22763. // can't generate mipmaps for compressed textures
  22764. // mips must be embedded in DDS files
  22765. this.generateMipmaps = false;
  22766. }
  22767. CompressedTexture.prototype = Object.create( Texture.prototype );
  22768. CompressedTexture.prototype.constructor = CompressedTexture;
  22769. CompressedTexture.prototype.isCompressedTexture = true;
  22770. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22771. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22772. this.needsUpdate = true;
  22773. }
  22774. CanvasTexture.prototype = Object.create( Texture.prototype );
  22775. CanvasTexture.prototype.constructor = CanvasTexture;
  22776. CanvasTexture.prototype.isCanvasTexture = true;
  22777. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  22778. format = format !== undefined ? format : DepthFormat;
  22779. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22780. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22781. }
  22782. if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; }
  22783. if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; }
  22784. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22785. this.image = { width: width, height: height };
  22786. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  22787. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  22788. this.flipY = false;
  22789. this.generateMipmaps = false;
  22790. }
  22791. DepthTexture.prototype = Object.create( Texture.prototype );
  22792. DepthTexture.prototype.constructor = DepthTexture;
  22793. DepthTexture.prototype.isDepthTexture = true;
  22794. function WireframeGeometry( geometry ) {
  22795. BufferGeometry.call( this );
  22796. this.type = 'WireframeGeometry';
  22797. // buffer
  22798. var vertices = [];
  22799. // helper variables
  22800. var edge = [ 0, 0 ], edges = {};
  22801. var keys = [ 'a', 'b', 'c' ];
  22802. // different logic for Geometry and BufferGeometry
  22803. if ( geometry && geometry.isGeometry ) {
  22804. // create a data structure that contains all edges without duplicates
  22805. var faces = geometry.faces;
  22806. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22807. var face = faces[ i ];
  22808. for ( var j = 0; j < 3; j ++ ) {
  22809. var edge1 = face[ keys[ j ] ];
  22810. var edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  22811. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  22812. edge[ 1 ] = Math.max( edge1, edge2 );
  22813. var key = edge[ 0 ] + ',' + edge[ 1 ];
  22814. if ( edges[ key ] === undefined ) {
  22815. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22816. }
  22817. }
  22818. }
  22819. // generate vertices
  22820. for ( var key$1 in edges ) {
  22821. var e = edges[ key$1 ];
  22822. var vertex = geometry.vertices[ e.index1 ];
  22823. vertices.push( vertex.x, vertex.y, vertex.z );
  22824. vertex = geometry.vertices[ e.index2 ];
  22825. vertices.push( vertex.x, vertex.y, vertex.z );
  22826. }
  22827. } else if ( geometry && geometry.isBufferGeometry ) {
  22828. var vertex$1 = new Vector3();
  22829. if ( geometry.index !== null ) {
  22830. // indexed BufferGeometry
  22831. var position = geometry.attributes.position;
  22832. var indices = geometry.index;
  22833. var groups = geometry.groups;
  22834. if ( groups.length === 0 ) {
  22835. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22836. }
  22837. // create a data structure that contains all eges without duplicates
  22838. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  22839. var group = groups[ o ];
  22840. var start = group.start;
  22841. var count = group.count;
  22842. for ( var i$1 = start, l$1 = ( start + count ); i$1 < l$1; i$1 += 3 ) {
  22843. for ( var j$1 = 0; j$1 < 3; j$1 ++ ) {
  22844. var edge1$1 = indices.getX( i$1 + j$1 );
  22845. var edge2$1 = indices.getX( i$1 + ( j$1 + 1 ) % 3 );
  22846. edge[ 0 ] = Math.min( edge1$1, edge2$1 ); // sorting prevents duplicates
  22847. edge[ 1 ] = Math.max( edge1$1, edge2$1 );
  22848. var key$2 = edge[ 0 ] + ',' + edge[ 1 ];
  22849. if ( edges[ key$2 ] === undefined ) {
  22850. edges[ key$2 ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22851. }
  22852. }
  22853. }
  22854. }
  22855. // generate vertices
  22856. for ( var key$3 in edges ) {
  22857. var e$1 = edges[ key$3 ];
  22858. vertex$1.fromBufferAttribute( position, e$1.index1 );
  22859. vertices.push( vertex$1.x, vertex$1.y, vertex$1.z );
  22860. vertex$1.fromBufferAttribute( position, e$1.index2 );
  22861. vertices.push( vertex$1.x, vertex$1.y, vertex$1.z );
  22862. }
  22863. } else {
  22864. // non-indexed BufferGeometry
  22865. var position$1 = geometry.attributes.position;
  22866. for ( var i$2 = 0, l$2 = ( position$1.count / 3 ); i$2 < l$2; i$2 ++ ) {
  22867. for ( var j$2 = 0; j$2 < 3; j$2 ++ ) {
  22868. // three edges per triangle, an edge is represented as (index1, index2)
  22869. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22870. var index1 = 3 * i$2 + j$2;
  22871. vertex$1.fromBufferAttribute( position$1, index1 );
  22872. vertices.push( vertex$1.x, vertex$1.y, vertex$1.z );
  22873. var index2 = 3 * i$2 + ( ( j$2 + 1 ) % 3 );
  22874. vertex$1.fromBufferAttribute( position$1, index2 );
  22875. vertices.push( vertex$1.x, vertex$1.y, vertex$1.z );
  22876. }
  22877. }
  22878. }
  22879. }
  22880. // build geometry
  22881. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22882. }
  22883. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  22884. WireframeGeometry.prototype.constructor = WireframeGeometry;
  22885. /**
  22886. * Parametric Surfaces Geometry
  22887. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  22888. */
  22889. // ParametricGeometry
  22890. function ParametricGeometry( func, slices, stacks ) {
  22891. Geometry.call( this );
  22892. this.type = 'ParametricGeometry';
  22893. this.parameters = {
  22894. func: func,
  22895. slices: slices,
  22896. stacks: stacks
  22897. };
  22898. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  22899. this.mergeVertices();
  22900. }
  22901. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  22902. ParametricGeometry.prototype.constructor = ParametricGeometry;
  22903. // ParametricBufferGeometry
  22904. function ParametricBufferGeometry( func, slices, stacks ) {
  22905. BufferGeometry.call( this );
  22906. this.type = 'ParametricBufferGeometry';
  22907. this.parameters = {
  22908. func: func,
  22909. slices: slices,
  22910. stacks: stacks
  22911. };
  22912. // buffers
  22913. var indices = [];
  22914. var vertices = [];
  22915. var normals = [];
  22916. var uvs = [];
  22917. var EPS = 0.00001;
  22918. var normal = new Vector3();
  22919. var p0 = new Vector3(), p1 = new Vector3();
  22920. var pu = new Vector3(), pv = new Vector3();
  22921. if ( func.length < 3 ) {
  22922. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  22923. }
  22924. // generate vertices, normals and uvs
  22925. var sliceCount = slices + 1;
  22926. for ( var i = 0; i <= stacks; i ++ ) {
  22927. var v = i / stacks;
  22928. for ( var j = 0; j <= slices; j ++ ) {
  22929. var u = j / slices;
  22930. // vertex
  22931. func( u, v, p0 );
  22932. vertices.push( p0.x, p0.y, p0.z );
  22933. // normal
  22934. // approximate tangent vectors via finite differences
  22935. if ( u - EPS >= 0 ) {
  22936. func( u - EPS, v, p1 );
  22937. pu.subVectors( p0, p1 );
  22938. } else {
  22939. func( u + EPS, v, p1 );
  22940. pu.subVectors( p1, p0 );
  22941. }
  22942. if ( v - EPS >= 0 ) {
  22943. func( u, v - EPS, p1 );
  22944. pv.subVectors( p0, p1 );
  22945. } else {
  22946. func( u, v + EPS, p1 );
  22947. pv.subVectors( p1, p0 );
  22948. }
  22949. // cross product of tangent vectors returns surface normal
  22950. normal.crossVectors( pu, pv ).normalize();
  22951. normals.push( normal.x, normal.y, normal.z );
  22952. // uv
  22953. uvs.push( u, v );
  22954. }
  22955. }
  22956. // generate indices
  22957. for ( var i$1 = 0; i$1 < stacks; i$1 ++ ) {
  22958. for ( var j$1 = 0; j$1 < slices; j$1 ++ ) {
  22959. var a = i$1 * sliceCount + j$1;
  22960. var b = i$1 * sliceCount + j$1 + 1;
  22961. var c = ( i$1 + 1 ) * sliceCount + j$1 + 1;
  22962. var d = ( i$1 + 1 ) * sliceCount + j$1;
  22963. // faces one and two
  22964. indices.push( a, b, d );
  22965. indices.push( b, c, d );
  22966. }
  22967. }
  22968. // build geometry
  22969. this.setIndex( indices );
  22970. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22971. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22972. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22973. }
  22974. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22975. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  22976. // PolyhedronGeometry
  22977. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  22978. Geometry.call( this );
  22979. this.type = 'PolyhedronGeometry';
  22980. this.parameters = {
  22981. vertices: vertices,
  22982. indices: indices,
  22983. radius: radius,
  22984. detail: detail
  22985. };
  22986. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  22987. this.mergeVertices();
  22988. }
  22989. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  22990. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  22991. // PolyhedronBufferGeometry
  22992. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  22993. BufferGeometry.call( this );
  22994. this.type = 'PolyhedronBufferGeometry';
  22995. this.parameters = {
  22996. vertices: vertices,
  22997. indices: indices,
  22998. radius: radius,
  22999. detail: detail
  23000. };
  23001. radius = radius || 1;
  23002. detail = detail || 0;
  23003. // default buffer data
  23004. var vertexBuffer = [];
  23005. var uvBuffer = [];
  23006. // the subdivision creates the vertex buffer data
  23007. subdivide( detail );
  23008. // all vertices should lie on a conceptual sphere with a given radius
  23009. applyRadius( radius );
  23010. // finally, create the uv data
  23011. generateUVs();
  23012. // build non-indexed geometry
  23013. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  23014. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  23015. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  23016. if ( detail === 0 ) {
  23017. this.computeVertexNormals(); // flat normals
  23018. } else {
  23019. this.normalizeNormals(); // smooth normals
  23020. }
  23021. // helper functions
  23022. function subdivide( detail ) {
  23023. var a = new Vector3();
  23024. var b = new Vector3();
  23025. var c = new Vector3();
  23026. // iterate over all faces and apply a subdivison with the given detail value
  23027. for ( var i = 0; i < indices.length; i += 3 ) {
  23028. // get the vertices of the face
  23029. getVertexByIndex( indices[ i + 0 ], a );
  23030. getVertexByIndex( indices[ i + 1 ], b );
  23031. getVertexByIndex( indices[ i + 2 ], c );
  23032. // perform subdivision
  23033. subdivideFace( a, b, c, detail );
  23034. }
  23035. }
  23036. function subdivideFace( a, b, c, detail ) {
  23037. var cols = Math.pow( 2, detail );
  23038. // we use this multidimensional array as a data structure for creating the subdivision
  23039. var v = [];
  23040. // construct all of the vertices for this subdivision
  23041. for ( var i = 0; i <= cols; i ++ ) {
  23042. v[ i ] = [];
  23043. var aj = a.clone().lerp( c, i / cols );
  23044. var bj = b.clone().lerp( c, i / cols );
  23045. var rows = cols - i;
  23046. for ( var j = 0; j <= rows; j ++ ) {
  23047. if ( j === 0 && i === cols ) {
  23048. v[ i ][ j ] = aj;
  23049. } else {
  23050. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23051. }
  23052. }
  23053. }
  23054. // construct all of the faces
  23055. for ( var i$1 = 0; i$1 < cols; i$1 ++ ) {
  23056. for ( var j$1 = 0; j$1 < 2 * ( cols - i$1 ) - 1; j$1 ++ ) {
  23057. var k = Math.floor( j$1 / 2 );
  23058. if ( j$1 % 2 === 0 ) {
  23059. pushVertex( v[ i$1 ][ k + 1 ] );
  23060. pushVertex( v[ i$1 + 1 ][ k ] );
  23061. pushVertex( v[ i$1 ][ k ] );
  23062. } else {
  23063. pushVertex( v[ i$1 ][ k + 1 ] );
  23064. pushVertex( v[ i$1 + 1 ][ k + 1 ] );
  23065. pushVertex( v[ i$1 + 1 ][ k ] );
  23066. }
  23067. }
  23068. }
  23069. }
  23070. function applyRadius( radius ) {
  23071. var vertex = new Vector3();
  23072. // iterate over the entire buffer and apply the radius to each vertex
  23073. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  23074. vertex.x = vertexBuffer[ i + 0 ];
  23075. vertex.y = vertexBuffer[ i + 1 ];
  23076. vertex.z = vertexBuffer[ i + 2 ];
  23077. vertex.normalize().multiplyScalar( radius );
  23078. vertexBuffer[ i + 0 ] = vertex.x;
  23079. vertexBuffer[ i + 1 ] = vertex.y;
  23080. vertexBuffer[ i + 2 ] = vertex.z;
  23081. }
  23082. }
  23083. function generateUVs() {
  23084. var vertex = new Vector3();
  23085. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  23086. vertex.x = vertexBuffer[ i + 0 ];
  23087. vertex.y = vertexBuffer[ i + 1 ];
  23088. vertex.z = vertexBuffer[ i + 2 ];
  23089. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23090. var v = inclination( vertex ) / Math.PI + 0.5;
  23091. uvBuffer.push( u, 1 - v );
  23092. }
  23093. correctUVs();
  23094. correctSeam();
  23095. }
  23096. function correctSeam() {
  23097. // handle case when face straddles the seam, see #3269
  23098. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  23099. // uv data of a single face
  23100. var x0 = uvBuffer[ i + 0 ];
  23101. var x1 = uvBuffer[ i + 2 ];
  23102. var x2 = uvBuffer[ i + 4 ];
  23103. var max = Math.max( x0, x1, x2 );
  23104. var min = Math.min( x0, x1, x2 );
  23105. // 0.9 is somewhat arbitrary
  23106. if ( max > 0.9 && min < 0.1 ) {
  23107. if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; }
  23108. if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; }
  23109. if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; }
  23110. }
  23111. }
  23112. }
  23113. function pushVertex( vertex ) {
  23114. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23115. }
  23116. function getVertexByIndex( index, vertex ) {
  23117. var stride = index * 3;
  23118. vertex.x = vertices[ stride + 0 ];
  23119. vertex.y = vertices[ stride + 1 ];
  23120. vertex.z = vertices[ stride + 2 ];
  23121. }
  23122. function correctUVs() {
  23123. var a = new Vector3();
  23124. var b = new Vector3();
  23125. var c = new Vector3();
  23126. var centroid = new Vector3();
  23127. var uvA = new Vector2();
  23128. var uvB = new Vector2();
  23129. var uvC = new Vector2();
  23130. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23131. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23132. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23133. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23134. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23135. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23136. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23137. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23138. var azi = azimuth( centroid );
  23139. correctUV( uvA, j + 0, a, azi );
  23140. correctUV( uvB, j + 2, b, azi );
  23141. correctUV( uvC, j + 4, c, azi );
  23142. }
  23143. }
  23144. function correctUV( uv, stride, vector, azimuth ) {
  23145. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23146. uvBuffer[ stride ] = uv.x - 1;
  23147. }
  23148. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23149. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23150. }
  23151. }
  23152. // Angle around the Y axis, counter-clockwise when looking from above.
  23153. function azimuth( vector ) {
  23154. return Math.atan2( vector.z, - vector.x );
  23155. }
  23156. // Angle above the XZ plane.
  23157. function inclination( vector ) {
  23158. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23159. }
  23160. }
  23161. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23162. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  23163. // TetrahedronGeometry
  23164. function TetrahedronGeometry( radius, detail ) {
  23165. Geometry.call( this );
  23166. this.type = 'TetrahedronGeometry';
  23167. this.parameters = {
  23168. radius: radius,
  23169. detail: detail
  23170. };
  23171. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  23172. this.mergeVertices();
  23173. }
  23174. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  23175. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  23176. // TetrahedronBufferGeometry
  23177. function TetrahedronBufferGeometry( radius, detail ) {
  23178. var vertices = [
  23179. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23180. ];
  23181. var indices = [
  23182. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23183. ];
  23184. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23185. this.type = 'TetrahedronBufferGeometry';
  23186. this.parameters = {
  23187. radius: radius,
  23188. detail: detail
  23189. };
  23190. }
  23191. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23192. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  23193. // OctahedronGeometry
  23194. function OctahedronGeometry( radius, detail ) {
  23195. Geometry.call( this );
  23196. this.type = 'OctahedronGeometry';
  23197. this.parameters = {
  23198. radius: radius,
  23199. detail: detail
  23200. };
  23201. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  23202. this.mergeVertices();
  23203. }
  23204. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  23205. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  23206. // OctahedronBufferGeometry
  23207. function OctahedronBufferGeometry( radius, detail ) {
  23208. var vertices = [
  23209. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23210. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23211. ];
  23212. var indices = [
  23213. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23214. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23215. 1, 3, 4, 1, 4, 2
  23216. ];
  23217. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23218. this.type = 'OctahedronBufferGeometry';
  23219. this.parameters = {
  23220. radius: radius,
  23221. detail: detail
  23222. };
  23223. }
  23224. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23225. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  23226. // IcosahedronGeometry
  23227. function IcosahedronGeometry( radius, detail ) {
  23228. Geometry.call( this );
  23229. this.type = 'IcosahedronGeometry';
  23230. this.parameters = {
  23231. radius: radius,
  23232. detail: detail
  23233. };
  23234. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  23235. this.mergeVertices();
  23236. }
  23237. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  23238. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  23239. // IcosahedronBufferGeometry
  23240. function IcosahedronBufferGeometry( radius, detail ) {
  23241. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23242. var vertices = [
  23243. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23244. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23245. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23246. ];
  23247. var indices = [
  23248. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23249. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23250. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23251. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23252. ];
  23253. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23254. this.type = 'IcosahedronBufferGeometry';
  23255. this.parameters = {
  23256. radius: radius,
  23257. detail: detail
  23258. };
  23259. }
  23260. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23261. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  23262. // DodecahedronGeometry
  23263. function DodecahedronGeometry( radius, detail ) {
  23264. Geometry.call( this );
  23265. this.type = 'DodecahedronGeometry';
  23266. this.parameters = {
  23267. radius: radius,
  23268. detail: detail
  23269. };
  23270. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  23271. this.mergeVertices();
  23272. }
  23273. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  23274. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  23275. // DodecahedronBufferGeometry
  23276. function DodecahedronBufferGeometry( radius, detail ) {
  23277. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23278. var r = 1 / t;
  23279. var vertices = [
  23280. // (±1, ±1, ±1)
  23281. - 1, - 1, - 1, - 1, - 1, 1,
  23282. - 1, 1, - 1, - 1, 1, 1,
  23283. 1, - 1, - 1, 1, - 1, 1,
  23284. 1, 1, - 1, 1, 1, 1,
  23285. // (0, ±1/φ, ±φ)
  23286. 0, - r, - t, 0, - r, t,
  23287. 0, r, - t, 0, r, t,
  23288. // (±1/φ, ±φ, 0)
  23289. - r, - t, 0, - r, t, 0,
  23290. r, - t, 0, r, t, 0,
  23291. // (±φ, 0, ±1/φ)
  23292. - t, 0, - r, t, 0, - r,
  23293. - t, 0, r, t, 0, r
  23294. ];
  23295. var indices = [
  23296. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23297. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23298. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23299. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23300. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23301. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23302. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23303. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23304. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23305. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23306. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23307. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23308. ];
  23309. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23310. this.type = 'DodecahedronBufferGeometry';
  23311. this.parameters = {
  23312. radius: radius,
  23313. detail: detail
  23314. };
  23315. }
  23316. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23317. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  23318. // TubeGeometry
  23319. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  23320. Geometry.call( this );
  23321. this.type = 'TubeGeometry';
  23322. this.parameters = {
  23323. path: path,
  23324. tubularSegments: tubularSegments,
  23325. radius: radius,
  23326. radialSegments: radialSegments,
  23327. closed: closed
  23328. };
  23329. if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); }
  23330. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  23331. // expose internals
  23332. this.tangents = bufferGeometry.tangents;
  23333. this.normals = bufferGeometry.normals;
  23334. this.binormals = bufferGeometry.binormals;
  23335. // create geometry
  23336. this.fromBufferGeometry( bufferGeometry );
  23337. this.mergeVertices();
  23338. }
  23339. TubeGeometry.prototype = Object.create( Geometry.prototype );
  23340. TubeGeometry.prototype.constructor = TubeGeometry;
  23341. // TubeBufferGeometry
  23342. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  23343. BufferGeometry.call( this );
  23344. this.type = 'TubeBufferGeometry';
  23345. this.parameters = {
  23346. path: path,
  23347. tubularSegments: tubularSegments,
  23348. radius: radius,
  23349. radialSegments: radialSegments,
  23350. closed: closed
  23351. };
  23352. tubularSegments = tubularSegments || 64;
  23353. radius = radius || 1;
  23354. radialSegments = radialSegments || 8;
  23355. closed = closed || false;
  23356. var frames = path.computeFrenetFrames( tubularSegments, closed );
  23357. // expose internals
  23358. this.tangents = frames.tangents;
  23359. this.normals = frames.normals;
  23360. this.binormals = frames.binormals;
  23361. // helper variables
  23362. var vertex = new Vector3();
  23363. var normal = new Vector3();
  23364. var uv = new Vector2();
  23365. var P = new Vector3();
  23366. // buffer
  23367. var vertices = [];
  23368. var normals = [];
  23369. var uvs = [];
  23370. var indices = [];
  23371. // create buffer data
  23372. generateBufferData();
  23373. // build geometry
  23374. this.setIndex( indices );
  23375. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23376. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23377. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23378. // functions
  23379. function generateBufferData() {
  23380. for ( var i = 0; i < tubularSegments; i ++ ) {
  23381. generateSegment( i );
  23382. }
  23383. // if the geometry is not closed, generate the last row of vertices and normals
  23384. // at the regular position on the given path
  23385. //
  23386. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23387. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23388. // uvs are generated in a separate function.
  23389. // this makes it easy compute correct values for closed geometries
  23390. generateUVs();
  23391. // finally create faces
  23392. generateIndices();
  23393. }
  23394. function generateSegment( i ) {
  23395. // we use getPointAt to sample evenly distributed points from the given path
  23396. P = path.getPointAt( i / tubularSegments, P );
  23397. // retrieve corresponding normal and binormal
  23398. var N = frames.normals[ i ];
  23399. var B = frames.binormals[ i ];
  23400. // generate normals and vertices for the current segment
  23401. for ( var j = 0; j <= radialSegments; j ++ ) {
  23402. var v = j / radialSegments * Math.PI * 2;
  23403. var sin = Math.sin( v );
  23404. var cos = - Math.cos( v );
  23405. // normal
  23406. normal.x = ( cos * N.x + sin * B.x );
  23407. normal.y = ( cos * N.y + sin * B.y );
  23408. normal.z = ( cos * N.z + sin * B.z );
  23409. normal.normalize();
  23410. normals.push( normal.x, normal.y, normal.z );
  23411. // vertex
  23412. vertex.x = P.x + radius * normal.x;
  23413. vertex.y = P.y + radius * normal.y;
  23414. vertex.z = P.z + radius * normal.z;
  23415. vertices.push( vertex.x, vertex.y, vertex.z );
  23416. }
  23417. }
  23418. function generateIndices() {
  23419. for ( var j = 1; j <= tubularSegments; j ++ ) {
  23420. for ( var i = 1; i <= radialSegments; i ++ ) {
  23421. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23422. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23423. var c = ( radialSegments + 1 ) * j + i;
  23424. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23425. // faces
  23426. indices.push( a, b, d );
  23427. indices.push( b, c, d );
  23428. }
  23429. }
  23430. }
  23431. function generateUVs() {
  23432. for ( var i = 0; i <= tubularSegments; i ++ ) {
  23433. for ( var j = 0; j <= radialSegments; j ++ ) {
  23434. uv.x = i / tubularSegments;
  23435. uv.y = j / radialSegments;
  23436. uvs.push( uv.x, uv.y );
  23437. }
  23438. }
  23439. }
  23440. }
  23441. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23442. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  23443. TubeBufferGeometry.prototype.toJSON = function () {
  23444. var data = BufferGeometry.prototype.toJSON.call( this );
  23445. data.path = this.parameters.path.toJSON();
  23446. return data;
  23447. };
  23448. // TorusKnotGeometry
  23449. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23450. Geometry.call( this );
  23451. this.type = 'TorusKnotGeometry';
  23452. this.parameters = {
  23453. radius: radius,
  23454. tube: tube,
  23455. tubularSegments: tubularSegments,
  23456. radialSegments: radialSegments,
  23457. p: p,
  23458. q: q
  23459. };
  23460. if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); }
  23461. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23462. this.mergeVertices();
  23463. }
  23464. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  23465. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  23466. // TorusKnotBufferGeometry
  23467. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  23468. BufferGeometry.call( this );
  23469. this.type = 'TorusKnotBufferGeometry';
  23470. this.parameters = {
  23471. radius: radius,
  23472. tube: tube,
  23473. tubularSegments: tubularSegments,
  23474. radialSegments: radialSegments,
  23475. p: p,
  23476. q: q
  23477. };
  23478. radius = radius || 1;
  23479. tube = tube || 0.4;
  23480. tubularSegments = Math.floor( tubularSegments ) || 64;
  23481. radialSegments = Math.floor( radialSegments ) || 8;
  23482. p = p || 2;
  23483. q = q || 3;
  23484. // buffers
  23485. var indices = [];
  23486. var vertices = [];
  23487. var normals = [];
  23488. var uvs = [];
  23489. // helper variables
  23490. var vertex = new Vector3();
  23491. var normal = new Vector3();
  23492. var P1 = new Vector3();
  23493. var P2 = new Vector3();
  23494. var B = new Vector3();
  23495. var T = new Vector3();
  23496. var N = new Vector3();
  23497. // generate vertices, normals and uvs
  23498. for ( var i = 0; i <= tubularSegments; ++ i ) {
  23499. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23500. var u = i / tubularSegments * p * Math.PI * 2;
  23501. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23502. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23503. calculatePositionOnCurve( u, p, q, radius, P1 );
  23504. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23505. // calculate orthonormal basis
  23506. T.subVectors( P2, P1 );
  23507. N.addVectors( P2, P1 );
  23508. B.crossVectors( T, N );
  23509. N.crossVectors( B, T );
  23510. // normalize B, N. T can be ignored, we don't use it
  23511. B.normalize();
  23512. N.normalize();
  23513. for ( var j = 0; j <= radialSegments; ++ j ) {
  23514. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23515. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23516. var v = j / radialSegments * Math.PI * 2;
  23517. var cx = - tube * Math.cos( v );
  23518. var cy = tube * Math.sin( v );
  23519. // now calculate the final vertex position.
  23520. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23521. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23522. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23523. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23524. vertices.push( vertex.x, vertex.y, vertex.z );
  23525. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23526. normal.subVectors( vertex, P1 ).normalize();
  23527. normals.push( normal.x, normal.y, normal.z );
  23528. // uv
  23529. uvs.push( i / tubularSegments );
  23530. uvs.push( j / radialSegments );
  23531. }
  23532. }
  23533. // generate indices
  23534. for ( var j$1 = 1; j$1 <= tubularSegments; j$1 ++ ) {
  23535. for ( var i$1 = 1; i$1 <= radialSegments; i$1 ++ ) {
  23536. // indices
  23537. var a = ( radialSegments + 1 ) * ( j$1 - 1 ) + ( i$1 - 1 );
  23538. var b = ( radialSegments + 1 ) * j$1 + ( i$1 - 1 );
  23539. var c = ( radialSegments + 1 ) * j$1 + i$1;
  23540. var d = ( radialSegments + 1 ) * ( j$1 - 1 ) + i$1;
  23541. // faces
  23542. indices.push( a, b, d );
  23543. indices.push( b, c, d );
  23544. }
  23545. }
  23546. // build geometry
  23547. this.setIndex( indices );
  23548. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23549. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23550. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23551. // this function calculates the current position on the torus curve
  23552. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23553. var cu = Math.cos( u );
  23554. var su = Math.sin( u );
  23555. var quOverP = q / p * u;
  23556. var cs = Math.cos( quOverP );
  23557. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23558. position.y = radius * ( 2 + cs ) * su * 0.5;
  23559. position.z = radius * Math.sin( quOverP ) * 0.5;
  23560. }
  23561. }
  23562. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23563. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  23564. // TorusGeometry
  23565. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23566. Geometry.call( this );
  23567. this.type = 'TorusGeometry';
  23568. this.parameters = {
  23569. radius: radius,
  23570. tube: tube,
  23571. radialSegments: radialSegments,
  23572. tubularSegments: tubularSegments,
  23573. arc: arc
  23574. };
  23575. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23576. this.mergeVertices();
  23577. }
  23578. TorusGeometry.prototype = Object.create( Geometry.prototype );
  23579. TorusGeometry.prototype.constructor = TorusGeometry;
  23580. // TorusBufferGeometry
  23581. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23582. BufferGeometry.call( this );
  23583. this.type = 'TorusBufferGeometry';
  23584. this.parameters = {
  23585. radius: radius,
  23586. tube: tube,
  23587. radialSegments: radialSegments,
  23588. tubularSegments: tubularSegments,
  23589. arc: arc
  23590. };
  23591. radius = radius || 1;
  23592. tube = tube || 0.4;
  23593. radialSegments = Math.floor( radialSegments ) || 8;
  23594. tubularSegments = Math.floor( tubularSegments ) || 6;
  23595. arc = arc || Math.PI * 2;
  23596. // buffers
  23597. var indices = [];
  23598. var vertices = [];
  23599. var normals = [];
  23600. var uvs = [];
  23601. // helper variables
  23602. var center = new Vector3();
  23603. var vertex = new Vector3();
  23604. var normal = new Vector3();
  23605. // generate vertices, normals and uvs
  23606. for ( var j = 0; j <= radialSegments; j ++ ) {
  23607. for ( var i = 0; i <= tubularSegments; i ++ ) {
  23608. var u = i / tubularSegments * arc;
  23609. var v = j / radialSegments * Math.PI * 2;
  23610. // vertex
  23611. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23612. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23613. vertex.z = tube * Math.sin( v );
  23614. vertices.push( vertex.x, vertex.y, vertex.z );
  23615. // normal
  23616. center.x = radius * Math.cos( u );
  23617. center.y = radius * Math.sin( u );
  23618. normal.subVectors( vertex, center ).normalize();
  23619. normals.push( normal.x, normal.y, normal.z );
  23620. // uv
  23621. uvs.push( i / tubularSegments );
  23622. uvs.push( j / radialSegments );
  23623. }
  23624. }
  23625. // generate indices
  23626. for ( var j$1 = 1; j$1 <= radialSegments; j$1 ++ ) {
  23627. for ( var i$1 = 1; i$1 <= tubularSegments; i$1 ++ ) {
  23628. // indices
  23629. var a = ( tubularSegments + 1 ) * j$1 + i$1 - 1;
  23630. var b = ( tubularSegments + 1 ) * ( j$1 - 1 ) + i$1 - 1;
  23631. var c = ( tubularSegments + 1 ) * ( j$1 - 1 ) + i$1;
  23632. var d = ( tubularSegments + 1 ) * j$1 + i$1;
  23633. // faces
  23634. indices.push( a, b, d );
  23635. indices.push( b, c, d );
  23636. }
  23637. }
  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. }
  23644. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23645. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  23646. /**
  23647. * Port from https://github.com/mapbox/earcut (v2.2.2)
  23648. */
  23649. var Earcut = {
  23650. triangulate: function ( data, holeIndices, dim ) {
  23651. dim = dim || 2;
  23652. var hasHoles = holeIndices && holeIndices.length,
  23653. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  23654. outerNode = linkedList( data, 0, outerLen, dim, true ),
  23655. triangles = [];
  23656. if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; }
  23657. var minX, minY, maxX, maxY, x, y, invSize;
  23658. if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); }
  23659. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  23660. if ( data.length > 80 * dim ) {
  23661. minX = maxX = data[ 0 ];
  23662. minY = maxY = data[ 1 ];
  23663. for ( var i = dim; i < outerLen; i += dim ) {
  23664. x = data[ i ];
  23665. y = data[ i + 1 ];
  23666. if ( x < minX ) { minX = x; }
  23667. if ( y < minY ) { minY = y; }
  23668. if ( x > maxX ) { maxX = x; }
  23669. if ( y > maxY ) { maxY = y; }
  23670. }
  23671. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  23672. invSize = Math.max( maxX - minX, maxY - minY );
  23673. invSize = invSize !== 0 ? 1 / invSize : 0;
  23674. }
  23675. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  23676. return triangles;
  23677. }
  23678. };
  23679. // create a circular doubly linked list from polygon points in the specified winding order
  23680. function linkedList( data, start, end, dim, clockwise ) {
  23681. var i, last;
  23682. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  23683. for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  23684. } else {
  23685. for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  23686. }
  23687. if ( last && equals( last, last.next ) ) {
  23688. removeNode( last );
  23689. last = last.next;
  23690. }
  23691. return last;
  23692. }
  23693. // eliminate colinear or duplicate points
  23694. function filterPoints( start, end ) {
  23695. if ( ! start ) { return start; }
  23696. if ( ! end ) { end = start; }
  23697. var p = start,
  23698. again;
  23699. do {
  23700. again = false;
  23701. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  23702. removeNode( p );
  23703. p = end = p.prev;
  23704. if ( p === p.next ) { break; }
  23705. again = true;
  23706. } else {
  23707. p = p.next;
  23708. }
  23709. } while ( again || p !== end );
  23710. return end;
  23711. }
  23712. // main ear slicing loop which triangulates a polygon (given as a linked list)
  23713. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  23714. if ( ! ear ) { return; }
  23715. // interlink polygon nodes in z-order
  23716. if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); }
  23717. var stop = ear,
  23718. prev, next;
  23719. // iterate through ears, slicing them one by one
  23720. while ( ear.prev !== ear.next ) {
  23721. prev = ear.prev;
  23722. next = ear.next;
  23723. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  23724. // cut off the triangle
  23725. triangles.push( prev.i / dim );
  23726. triangles.push( ear.i / dim );
  23727. triangles.push( next.i / dim );
  23728. removeNode( ear );
  23729. // skipping the next vertex leads to less sliver triangles
  23730. ear = next.next;
  23731. stop = next.next;
  23732. continue;
  23733. }
  23734. ear = next;
  23735. // if we looped through the whole remaining polygon and can't find any more ears
  23736. if ( ear === stop ) {
  23737. // try filtering points and slicing again
  23738. if ( ! pass ) {
  23739. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  23740. // if this didn't work, try curing all small self-intersections locally
  23741. } else if ( pass === 1 ) {
  23742. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  23743. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  23744. // as a last resort, try splitting the remaining polygon into two
  23745. } else if ( pass === 2 ) {
  23746. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  23747. }
  23748. break;
  23749. }
  23750. }
  23751. }
  23752. // check whether a polygon node forms a valid ear with adjacent nodes
  23753. function isEar( ear ) {
  23754. var a = ear.prev,
  23755. b = ear,
  23756. c = ear.next;
  23757. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23758. // now make sure we don't have other points inside the potential ear
  23759. var p = ear.next.next;
  23760. while ( p !== ear.prev ) {
  23761. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23762. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23763. p = p.next;
  23764. }
  23765. return true;
  23766. }
  23767. function isEarHashed( ear, minX, minY, invSize ) {
  23768. var a = ear.prev,
  23769. b = ear,
  23770. c = ear.next;
  23771. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23772. // triangle bbox; min & max are calculated like this for speed
  23773. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  23774. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  23775. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  23776. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  23777. // z-order range for the current triangle bbox;
  23778. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  23779. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  23780. var p = ear.prevZ,
  23781. n = ear.nextZ;
  23782. // look for points inside the triangle in both directions
  23783. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  23784. if ( p !== ear.prev && p !== ear.next &&
  23785. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23786. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23787. p = p.prevZ;
  23788. if ( n !== ear.prev && n !== ear.next &&
  23789. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23790. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23791. n = n.nextZ;
  23792. }
  23793. // look for remaining points in decreasing z-order
  23794. while ( p && p.z >= minZ ) {
  23795. if ( p !== ear.prev && p !== ear.next &&
  23796. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23797. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23798. p = p.prevZ;
  23799. }
  23800. // look for remaining points in increasing z-order
  23801. while ( n && n.z <= maxZ ) {
  23802. if ( n !== ear.prev && n !== ear.next &&
  23803. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23804. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23805. n = n.nextZ;
  23806. }
  23807. return true;
  23808. }
  23809. // go through all polygon nodes and cure small local self-intersections
  23810. function cureLocalIntersections( start, triangles, dim ) {
  23811. var p = start;
  23812. do {
  23813. var a = p.prev,
  23814. b = p.next.next;
  23815. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  23816. triangles.push( a.i / dim );
  23817. triangles.push( p.i / dim );
  23818. triangles.push( b.i / dim );
  23819. // remove two nodes involved
  23820. removeNode( p );
  23821. removeNode( p.next );
  23822. p = start = b;
  23823. }
  23824. p = p.next;
  23825. } while ( p !== start );
  23826. return filterPoints( p );
  23827. }
  23828. // try splitting polygon into two and triangulate them independently
  23829. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  23830. // look for a valid diagonal that divides the polygon into two
  23831. var a = start;
  23832. do {
  23833. var b = a.next.next;
  23834. while ( b !== a.prev ) {
  23835. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  23836. // split the polygon in two by the diagonal
  23837. var c = splitPolygon( a, b );
  23838. // filter colinear points around the cuts
  23839. a = filterPoints( a, a.next );
  23840. c = filterPoints( c, c.next );
  23841. // run earcut on each half
  23842. earcutLinked( a, triangles, dim, minX, minY, invSize );
  23843. earcutLinked( c, triangles, dim, minX, minY, invSize );
  23844. return;
  23845. }
  23846. b = b.next;
  23847. }
  23848. a = a.next;
  23849. } while ( a !== start );
  23850. }
  23851. // link every hole into the outer loop, producing a single-ring polygon without holes
  23852. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  23853. var queue = [],
  23854. i, len, start, end, list;
  23855. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  23856. start = holeIndices[ i ] * dim;
  23857. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  23858. list = linkedList( data, start, end, dim, false );
  23859. if ( list === list.next ) { list.steiner = true; }
  23860. queue.push( getLeftmost( list ) );
  23861. }
  23862. queue.sort( compareX );
  23863. // process holes from left to right
  23864. for ( i = 0; i < queue.length; i ++ ) {
  23865. eliminateHole( queue[ i ], outerNode );
  23866. outerNode = filterPoints( outerNode, outerNode.next );
  23867. }
  23868. return outerNode;
  23869. }
  23870. function compareX( a, b ) {
  23871. return a.x - b.x;
  23872. }
  23873. // find a bridge between vertices that connects hole with an outer ring and and link it
  23874. function eliminateHole( hole, outerNode ) {
  23875. outerNode = findHoleBridge( hole, outerNode );
  23876. if ( outerNode ) {
  23877. var b = splitPolygon( outerNode, hole );
  23878. // filter collinear points around the cuts
  23879. filterPoints( outerNode, outerNode.next );
  23880. filterPoints( b, b.next );
  23881. }
  23882. }
  23883. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23884. function findHoleBridge( hole, outerNode ) {
  23885. var p = outerNode,
  23886. hx = hole.x,
  23887. hy = hole.y,
  23888. qx = - Infinity,
  23889. m;
  23890. // find a segment intersected by a ray from the hole's leftmost point to the left;
  23891. // segment's endpoint with lesser x will be potential connection point
  23892. do {
  23893. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  23894. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  23895. if ( x <= hx && x > qx ) {
  23896. qx = x;
  23897. if ( x === hx ) {
  23898. if ( hy === p.y ) { return p; }
  23899. if ( hy === p.next.y ) { return p.next; }
  23900. }
  23901. m = p.x < p.next.x ? p : p.next;
  23902. }
  23903. }
  23904. p = p.next;
  23905. } while ( p !== outerNode );
  23906. if ( ! m ) { return null; }
  23907. if ( hx === qx ) { return m; } // hole touches outer segment; pick leftmost endpoint
  23908. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23909. // if there are no points found, we have a valid connection;
  23910. // otherwise choose the point of the minimum angle with the ray as connection point
  23911. var stop = m,
  23912. mx = m.x,
  23913. my = m.y,
  23914. tanMin = Infinity,
  23915. tan;
  23916. p = m;
  23917. do {
  23918. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  23919. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  23920. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  23921. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  23922. m = p;
  23923. tanMin = tan;
  23924. }
  23925. }
  23926. p = p.next;
  23927. } while ( p !== stop );
  23928. return m;
  23929. }
  23930. // whether sector in vertex m contains sector in vertex p in the same coordinates
  23931. function sectorContainsSector( m, p ) {
  23932. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  23933. }
  23934. // interlink polygon nodes in z-order
  23935. function indexCurve( start, minX, minY, invSize ) {
  23936. var p = start;
  23937. do {
  23938. if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); }
  23939. p.prevZ = p.prev;
  23940. p.nextZ = p.next;
  23941. p = p.next;
  23942. } while ( p !== start );
  23943. p.prevZ.nextZ = null;
  23944. p.prevZ = null;
  23945. sortLinked( p );
  23946. }
  23947. // Simon Tatham's linked list merge sort algorithm
  23948. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23949. function sortLinked( list ) {
  23950. var i, p, q, e, tail, numMerges, pSize, qSize,
  23951. inSize = 1;
  23952. do {
  23953. p = list;
  23954. list = null;
  23955. tail = null;
  23956. numMerges = 0;
  23957. while ( p ) {
  23958. numMerges ++;
  23959. q = p;
  23960. pSize = 0;
  23961. for ( i = 0; i < inSize; i ++ ) {
  23962. pSize ++;
  23963. q = q.nextZ;
  23964. if ( ! q ) { break; }
  23965. }
  23966. qSize = inSize;
  23967. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  23968. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  23969. e = p;
  23970. p = p.nextZ;
  23971. pSize --;
  23972. } else {
  23973. e = q;
  23974. q = q.nextZ;
  23975. qSize --;
  23976. }
  23977. if ( tail ) { tail.nextZ = e; }
  23978. else { list = e; }
  23979. e.prevZ = tail;
  23980. tail = e;
  23981. }
  23982. p = q;
  23983. }
  23984. tail.nextZ = null;
  23985. inSize *= 2;
  23986. } while ( numMerges > 1 );
  23987. return list;
  23988. }
  23989. // z-order of a point given coords and inverse of the longer side of data bbox
  23990. function zOrder( x, y, minX, minY, invSize ) {
  23991. // coords are transformed into non-negative 15-bit integer range
  23992. x = 32767 * ( x - minX ) * invSize;
  23993. y = 32767 * ( y - minY ) * invSize;
  23994. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  23995. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  23996. x = ( x | ( x << 2 ) ) & 0x33333333;
  23997. x = ( x | ( x << 1 ) ) & 0x55555555;
  23998. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  23999. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  24000. y = ( y | ( y << 2 ) ) & 0x33333333;
  24001. y = ( y | ( y << 1 ) ) & 0x55555555;
  24002. return x | ( y << 1 );
  24003. }
  24004. // find the leftmost node of a polygon ring
  24005. function getLeftmost( start ) {
  24006. var p = start,
  24007. leftmost = start;
  24008. do {
  24009. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; }
  24010. p = p.next;
  24011. } while ( p !== start );
  24012. return leftmost;
  24013. }
  24014. // check if a point lies within a convex triangle
  24015. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  24016. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  24017. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  24018. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  24019. }
  24020. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24021. function isValidDiagonal( a, b ) {
  24022. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  24023. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  24024. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  24025. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  24026. }
  24027. // signed area of a triangle
  24028. function area( p, q, r ) {
  24029. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  24030. }
  24031. // check if two points are equal
  24032. function equals( p1, p2 ) {
  24033. return p1.x === p2.x && p1.y === p2.y;
  24034. }
  24035. // check if two segments intersect
  24036. function intersects( p1, q1, p2, q2 ) {
  24037. var o1 = sign( area( p1, q1, p2 ) );
  24038. var o2 = sign( area( p1, q1, q2 ) );
  24039. var o3 = sign( area( p2, q2, p1 ) );
  24040. var o4 = sign( area( p2, q2, q1 ) );
  24041. if ( o1 !== o2 && o3 !== o4 ) { return true; } // general case
  24042. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1
  24043. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1
  24044. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2
  24045. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2
  24046. return false;
  24047. }
  24048. // for collinear points p, q, r, check if point q lies on segment pr
  24049. function onSegment( p, q, r ) {
  24050. 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 );
  24051. }
  24052. function sign( num ) {
  24053. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  24054. }
  24055. // check if a polygon diagonal intersects any polygon segments
  24056. function intersectsPolygon( a, b ) {
  24057. var p = a;
  24058. do {
  24059. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24060. intersects( p, p.next, a, b ) ) { return true; }
  24061. p = p.next;
  24062. } while ( p !== a );
  24063. return false;
  24064. }
  24065. // check if a polygon diagonal is locally inside the polygon
  24066. function locallyInside( a, b ) {
  24067. return area( a.prev, a, a.next ) < 0 ?
  24068. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  24069. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  24070. }
  24071. // check if the middle point of a polygon diagonal is inside the polygon
  24072. function middleInside( a, b ) {
  24073. var p = a,
  24074. inside = false,
  24075. px = ( a.x + b.x ) / 2,
  24076. py = ( a.y + b.y ) / 2;
  24077. do {
  24078. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  24079. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  24080. { inside = ! inside; }
  24081. p = p.next;
  24082. } while ( p !== a );
  24083. return inside;
  24084. }
  24085. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24086. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24087. function splitPolygon( a, b ) {
  24088. var a2 = new Node( a.i, a.x, a.y ),
  24089. b2 = new Node( b.i, b.x, b.y ),
  24090. an = a.next,
  24091. bp = b.prev;
  24092. a.next = b;
  24093. b.prev = a;
  24094. a2.next = an;
  24095. an.prev = a2;
  24096. b2.next = a2;
  24097. a2.prev = b2;
  24098. bp.next = b2;
  24099. b2.prev = bp;
  24100. return b2;
  24101. }
  24102. // create a node and optionally link it with previous one (in a circular doubly linked list)
  24103. function insertNode( i, x, y, last ) {
  24104. var p = new Node( i, x, y );
  24105. if ( ! last ) {
  24106. p.prev = p;
  24107. p.next = p;
  24108. } else {
  24109. p.next = last.next;
  24110. p.prev = last;
  24111. last.next.prev = p;
  24112. last.next = p;
  24113. }
  24114. return p;
  24115. }
  24116. function removeNode( p ) {
  24117. p.next.prev = p.prev;
  24118. p.prev.next = p.next;
  24119. if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; }
  24120. if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; }
  24121. }
  24122. function Node( i, x, y ) {
  24123. // vertex index in coordinates array
  24124. this.i = i;
  24125. // vertex coordinates
  24126. this.x = x;
  24127. this.y = y;
  24128. // previous and next vertex nodes in a polygon ring
  24129. this.prev = null;
  24130. this.next = null;
  24131. // z-order curve value
  24132. this.z = null;
  24133. // previous and next nodes in z-order
  24134. this.prevZ = null;
  24135. this.nextZ = null;
  24136. // indicates whether this is a steiner point
  24137. this.steiner = false;
  24138. }
  24139. function signedArea( data, start, end, dim ) {
  24140. var sum = 0;
  24141. for ( var i = start, j = end - dim; i < end; i += dim ) {
  24142. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  24143. j = i;
  24144. }
  24145. return sum;
  24146. }
  24147. var ShapeUtils = {
  24148. // calculate area of the contour polygon
  24149. area: function ( contour ) {
  24150. var n = contour.length;
  24151. var a = 0.0;
  24152. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  24153. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  24154. }
  24155. return a * 0.5;
  24156. },
  24157. isClockWise: function ( pts ) {
  24158. return ShapeUtils.area( pts ) < 0;
  24159. },
  24160. triangulateShape: function ( contour, holes ) {
  24161. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  24162. var holeIndices = []; // array of hole indices
  24163. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  24164. removeDupEndPts( contour );
  24165. addContour( vertices, contour );
  24166. //
  24167. var holeIndex = contour.length;
  24168. holes.forEach( removeDupEndPts );
  24169. for ( var i = 0; i < holes.length; i ++ ) {
  24170. holeIndices.push( holeIndex );
  24171. holeIndex += holes[ i ].length;
  24172. addContour( vertices, holes[ i ] );
  24173. }
  24174. //
  24175. var triangles = Earcut.triangulate( vertices, holeIndices );
  24176. //
  24177. for ( var i$1 = 0; i$1 < triangles.length; i$1 += 3 ) {
  24178. faces.push( triangles.slice( i$1, i$1 + 3 ) );
  24179. }
  24180. return faces;
  24181. }
  24182. };
  24183. function removeDupEndPts( points ) {
  24184. var l = points.length;
  24185. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  24186. points.pop();
  24187. }
  24188. }
  24189. function addContour( vertices, contour ) {
  24190. for ( var i = 0; i < contour.length; i ++ ) {
  24191. vertices.push( contour[ i ].x );
  24192. vertices.push( contour[ i ].y );
  24193. }
  24194. }
  24195. /**
  24196. * Creates extruded geometry from a path shape.
  24197. *
  24198. * parameters = {
  24199. *
  24200. * curveSegments: <int>, // number of points on the curves
  24201. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  24202. * depth: <float>, // Depth to extrude the shape
  24203. *
  24204. * bevelEnabled: <bool>, // turn on bevel
  24205. * bevelThickness: <float>, // how deep into the original shape bevel goes
  24206. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  24207. * bevelOffset: <float>, // how far from shape outline does bevel start
  24208. * bevelSegments: <int>, // number of bevel layers
  24209. *
  24210. * extrudePath: <THREE.Curve> // curve to extrude shape along
  24211. *
  24212. * UVGenerator: <Object> // object that provides UV generator functions
  24213. *
  24214. * }
  24215. */
  24216. // ExtrudeGeometry
  24217. function ExtrudeGeometry( shapes, options ) {
  24218. Geometry.call( this );
  24219. this.type = 'ExtrudeGeometry';
  24220. this.parameters = {
  24221. shapes: shapes,
  24222. options: options
  24223. };
  24224. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  24225. this.mergeVertices();
  24226. }
  24227. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  24228. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  24229. ExtrudeGeometry.prototype.toJSON = function () {
  24230. var data = Geometry.prototype.toJSON.call( this );
  24231. var shapes = this.parameters.shapes;
  24232. var options = this.parameters.options;
  24233. return toJSON( shapes, options, data );
  24234. };
  24235. // ExtrudeBufferGeometry
  24236. function ExtrudeBufferGeometry( shapes, options ) {
  24237. BufferGeometry.call( this );
  24238. this.type = 'ExtrudeBufferGeometry';
  24239. this.parameters = {
  24240. shapes: shapes,
  24241. options: options
  24242. };
  24243. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  24244. var scope = this;
  24245. var verticesArray = [];
  24246. var uvArray = [];
  24247. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24248. var shape = shapes[ i ];
  24249. addShape( shape );
  24250. }
  24251. // build geometry
  24252. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  24253. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  24254. this.computeVertexNormals();
  24255. // functions
  24256. function addShape( shape ) {
  24257. var placeholder = [];
  24258. // options
  24259. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  24260. var steps = options.steps !== undefined ? options.steps : 1;
  24261. var depth = options.depth !== undefined ? options.depth : 100;
  24262. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  24263. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  24264. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  24265. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  24266. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  24267. var extrudePath = options.extrudePath;
  24268. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  24269. // deprecated options
  24270. if ( options.amount !== undefined ) {
  24271. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  24272. depth = options.amount;
  24273. }
  24274. //
  24275. var extrudePts, extrudeByPath = false;
  24276. var splineTube, binormal, normal, position2;
  24277. if ( extrudePath ) {
  24278. extrudePts = extrudePath.getSpacedPoints( steps );
  24279. extrudeByPath = true;
  24280. bevelEnabled = false; // bevels not supported for path extrusion
  24281. // SETUP TNB variables
  24282. // TODO1 - have a .isClosed in spline?
  24283. splineTube = extrudePath.computeFrenetFrames( steps, false );
  24284. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  24285. binormal = new Vector3();
  24286. normal = new Vector3();
  24287. position2 = new Vector3();
  24288. }
  24289. // Safeguards if bevels are not enabled
  24290. if ( ! bevelEnabled ) {
  24291. bevelSegments = 0;
  24292. bevelThickness = 0;
  24293. bevelSize = 0;
  24294. bevelOffset = 0;
  24295. }
  24296. // Variables initialization
  24297. var shapePoints = shape.extractPoints( curveSegments );
  24298. var vertices = shapePoints.shape;
  24299. var holes = shapePoints.holes;
  24300. var reverse = ! ShapeUtils.isClockWise( vertices );
  24301. if ( reverse ) {
  24302. vertices = vertices.reverse();
  24303. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  24304. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  24305. var ahole = holes[ h ];
  24306. if ( ShapeUtils.isClockWise( ahole ) ) {
  24307. holes[ h ] = ahole.reverse();
  24308. }
  24309. }
  24310. }
  24311. var faces = ShapeUtils.triangulateShape( vertices, holes );
  24312. /* Vertices */
  24313. var contour = vertices; // vertices has all points but contour has only points of circumference
  24314. for ( var h$1 = 0, hl$1 = holes.length; h$1 < hl$1; h$1 ++ ) {
  24315. var ahole$1 = holes[ h$1 ];
  24316. vertices = vertices.concat( ahole$1 );
  24317. }
  24318. function scalePt2( pt, vec, size ) {
  24319. if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); }
  24320. return vec.clone().multiplyScalar( size ).add( pt );
  24321. }
  24322. var vlen = vertices.length, flen = faces.length;
  24323. // Find directions for point movement
  24324. function getBevelVec( inPt, inPrev, inNext ) {
  24325. // computes for inPt the corresponding point inPt' on a new contour
  24326. // shifted by 1 unit (length of normalized vector) to the left
  24327. // if we walk along contour clockwise, this new contour is outside the old one
  24328. //
  24329. // inPt' is the intersection of the two lines parallel to the two
  24330. // adjacent edges of inPt at a distance of 1 unit on the left side.
  24331. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  24332. // good reading for geometry algorithms (here: line-line intersection)
  24333. // http://geomalgorithms.com/a05-_intersect-1.html
  24334. var v_prev_x = inPt.x - inPrev.x,
  24335. v_prev_y = inPt.y - inPrev.y;
  24336. var v_next_x = inNext.x - inPt.x,
  24337. v_next_y = inNext.y - inPt.y;
  24338. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  24339. // check for collinear edges
  24340. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  24341. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  24342. // not collinear
  24343. // length of vectors for normalizing
  24344. var v_prev_len = Math.sqrt( v_prev_lensq );
  24345. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  24346. // shift adjacent points by unit vectors to the left
  24347. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  24348. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  24349. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  24350. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  24351. // scaling factor for v_prev to intersection point
  24352. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  24353. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  24354. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  24355. // vector from inPt to intersection point
  24356. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  24357. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  24358. // Don't normalize!, otherwise sharp corners become ugly
  24359. // but prevent crazy spikes
  24360. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  24361. if ( v_trans_lensq <= 2 ) {
  24362. return new Vector2( v_trans_x, v_trans_y );
  24363. } else {
  24364. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  24365. }
  24366. } else {
  24367. // handle special case of collinear edges
  24368. var direction_eq = false; // assumes: opposite
  24369. if ( v_prev_x > Number.EPSILON ) {
  24370. if ( v_next_x > Number.EPSILON ) {
  24371. direction_eq = true;
  24372. }
  24373. } else {
  24374. if ( v_prev_x < - Number.EPSILON ) {
  24375. if ( v_next_x < - Number.EPSILON ) {
  24376. direction_eq = true;
  24377. }
  24378. } else {
  24379. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  24380. direction_eq = true;
  24381. }
  24382. }
  24383. }
  24384. if ( direction_eq ) {
  24385. // console.log("Warning: lines are a straight sequence");
  24386. v_trans_x = - v_prev_y;
  24387. v_trans_y = v_prev_x;
  24388. shrink_by = Math.sqrt( v_prev_lensq );
  24389. } else {
  24390. // console.log("Warning: lines are a straight spike");
  24391. v_trans_x = v_prev_x;
  24392. v_trans_y = v_prev_y;
  24393. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  24394. }
  24395. }
  24396. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  24397. }
  24398. var contourMovements = [];
  24399. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  24400. if ( j === il ) { j = 0; }
  24401. if ( k === il ) { k = 0; }
  24402. // (j)---(i)---(k)
  24403. // console.log('i,j,k', i, j , k)
  24404. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  24405. }
  24406. var holesMovements = [];
  24407. var oneHoleMovements, verticesMovements = contourMovements.concat();
  24408. for ( var h$2 = 0, hl$2 = holes.length; h$2 < hl$2; h$2 ++ ) {
  24409. var ahole$2 = holes[ h$2 ];
  24410. oneHoleMovements = [];
  24411. for ( var i$1 = 0, il$1 = ahole$2.length, j$1 = il$1 - 1, k$1 = i$1 + 1; i$1 < il$1; i$1 ++, j$1 ++, k$1 ++ ) {
  24412. if ( j$1 === il$1 ) { j$1 = 0; }
  24413. if ( k$1 === il$1 ) { k$1 = 0; }
  24414. // (j)---(i)---(k)
  24415. oneHoleMovements[ i$1 ] = getBevelVec( ahole$2[ i$1 ], ahole$2[ j$1 ], ahole$2[ k$1 ] );
  24416. }
  24417. holesMovements.push( oneHoleMovements );
  24418. verticesMovements = verticesMovements.concat( oneHoleMovements );
  24419. }
  24420. // Loop bevelSegments, 1 for the front, 1 for the back
  24421. for ( var b = 0; b < bevelSegments; b ++ ) {
  24422. //for ( b = bevelSegments; b > 0; b -- ) {
  24423. var t = b / bevelSegments;
  24424. var z = bevelThickness * Math.cos( t * Math.PI / 2 );
  24425. var bs$1 = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  24426. // contract shape
  24427. for ( var i$2 = 0, il$2 = contour.length; i$2 < il$2; i$2 ++ ) {
  24428. var vert = scalePt2( contour[ i$2 ], contourMovements[ i$2 ], bs$1 );
  24429. v( vert.x, vert.y, - z );
  24430. }
  24431. // expand holes
  24432. for ( var h$3 = 0, hl$3 = holes.length; h$3 < hl$3; h$3 ++ ) {
  24433. var ahole$3 = holes[ h$3 ];
  24434. oneHoleMovements = holesMovements[ h$3 ];
  24435. for ( var i$3 = 0, il$3 = ahole$3.length; i$3 < il$3; i$3 ++ ) {
  24436. var vert$1 = scalePt2( ahole$3[ i$3 ], oneHoleMovements[ i$3 ], bs$1 );
  24437. v( vert$1.x, vert$1.y, - z );
  24438. }
  24439. }
  24440. }
  24441. var bs = bevelSize + bevelOffset;
  24442. // Back facing vertices
  24443. for ( var i$4 = 0; i$4 < vlen; i$4 ++ ) {
  24444. var vert$2 = bevelEnabled ? scalePt2( vertices[ i$4 ], verticesMovements[ i$4 ], bs ) : vertices[ i$4 ];
  24445. if ( ! extrudeByPath ) {
  24446. v( vert$2.x, vert$2.y, 0 );
  24447. } else {
  24448. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  24449. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert$2.x );
  24450. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert$2.y );
  24451. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  24452. v( position2.x, position2.y, position2.z );
  24453. }
  24454. }
  24455. // Add stepped vertices...
  24456. // Including front facing vertices
  24457. for ( var s = 1; s <= steps; s ++ ) {
  24458. for ( var i$5 = 0; i$5 < vlen; i$5 ++ ) {
  24459. var vert$3 = bevelEnabled ? scalePt2( vertices[ i$5 ], verticesMovements[ i$5 ], bs ) : vertices[ i$5 ];
  24460. if ( ! extrudeByPath ) {
  24461. v( vert$3.x, vert$3.y, depth / steps * s );
  24462. } else {
  24463. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  24464. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert$3.x );
  24465. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert$3.y );
  24466. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  24467. v( position2.x, position2.y, position2.z );
  24468. }
  24469. }
  24470. }
  24471. // Add bevel segments planes
  24472. //for ( b = 1; b <= bevelSegments; b ++ ) {
  24473. for ( var b$1 = bevelSegments - 1; b$1 >= 0; b$1 -- ) {
  24474. var t$1 = b$1 / bevelSegments;
  24475. var z$1 = bevelThickness * Math.cos( t$1 * Math.PI / 2 );
  24476. var bs$2 = bevelSize * Math.sin( t$1 * Math.PI / 2 ) + bevelOffset;
  24477. // contract shape
  24478. for ( var i$6 = 0, il$4 = contour.length; i$6 < il$4; i$6 ++ ) {
  24479. var vert$4 = scalePt2( contour[ i$6 ], contourMovements[ i$6 ], bs$2 );
  24480. v( vert$4.x, vert$4.y, depth + z$1 );
  24481. }
  24482. // expand holes
  24483. for ( var h$4 = 0, hl$4 = holes.length; h$4 < hl$4; h$4 ++ ) {
  24484. var ahole$4 = holes[ h$4 ];
  24485. oneHoleMovements = holesMovements[ h$4 ];
  24486. for ( var i$7 = 0, il$5 = ahole$4.length; i$7 < il$5; i$7 ++ ) {
  24487. var vert$5 = scalePt2( ahole$4[ i$7 ], oneHoleMovements[ i$7 ], bs$2 );
  24488. if ( ! extrudeByPath ) {
  24489. v( vert$5.x, vert$5.y, depth + z$1 );
  24490. } else {
  24491. v( vert$5.x, vert$5.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z$1 );
  24492. }
  24493. }
  24494. }
  24495. }
  24496. /* Faces */
  24497. // Top and bottom faces
  24498. buildLidFaces();
  24499. // Sides faces
  24500. buildSideFaces();
  24501. ///// Internal functions
  24502. function buildLidFaces() {
  24503. var start = verticesArray.length / 3;
  24504. if ( bevelEnabled ) {
  24505. var layer = 0; // steps + 1
  24506. var offset = vlen * layer;
  24507. // Bottom faces
  24508. for ( var i = 0; i < flen; i ++ ) {
  24509. var face = faces[ i ];
  24510. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  24511. }
  24512. layer = steps + bevelSegments * 2;
  24513. offset = vlen * layer;
  24514. // Top faces
  24515. for ( var i$1 = 0; i$1 < flen; i$1 ++ ) {
  24516. var face$1 = faces[ i$1 ];
  24517. f3( face$1[ 0 ] + offset, face$1[ 1 ] + offset, face$1[ 2 ] + offset );
  24518. }
  24519. } else {
  24520. // Bottom faces
  24521. for ( var i$2 = 0; i$2 < flen; i$2 ++ ) {
  24522. var face$2 = faces[ i$2 ];
  24523. f3( face$2[ 2 ], face$2[ 1 ], face$2[ 0 ] );
  24524. }
  24525. // Top faces
  24526. for ( var i$3 = 0; i$3 < flen; i$3 ++ ) {
  24527. var face$3 = faces[ i$3 ];
  24528. f3( face$3[ 0 ] + vlen * steps, face$3[ 1 ] + vlen * steps, face$3[ 2 ] + vlen * steps );
  24529. }
  24530. }
  24531. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  24532. }
  24533. // Create faces for the z-sides of the shape
  24534. function buildSideFaces() {
  24535. var start = verticesArray.length / 3;
  24536. var layeroffset = 0;
  24537. sidewalls( contour, layeroffset );
  24538. layeroffset += contour.length;
  24539. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  24540. var ahole = holes[ h ];
  24541. sidewalls( ahole, layeroffset );
  24542. //, true
  24543. layeroffset += ahole.length;
  24544. }
  24545. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  24546. }
  24547. function sidewalls( contour, layeroffset ) {
  24548. var i = contour.length;
  24549. while ( -- i >= 0 ) {
  24550. var j = i;
  24551. var k = i - 1;
  24552. if ( k < 0 ) { k = contour.length - 1; }
  24553. //console.log('b', i,j, i-1, k,vertices.length);
  24554. for ( var s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  24555. var slen1 = vlen * s;
  24556. var slen2 = vlen * ( s + 1 );
  24557. var a = layeroffset + j + slen1,
  24558. b = layeroffset + k + slen1,
  24559. c = layeroffset + k + slen2,
  24560. d = layeroffset + j + slen2;
  24561. f4( a, b, c, d );
  24562. }
  24563. }
  24564. }
  24565. function v( x, y, z ) {
  24566. placeholder.push( x );
  24567. placeholder.push( y );
  24568. placeholder.push( z );
  24569. }
  24570. function f3( a, b, c ) {
  24571. addVertex( a );
  24572. addVertex( b );
  24573. addVertex( c );
  24574. var nextIndex = verticesArray.length / 3;
  24575. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  24576. addUV( uvs[ 0 ] );
  24577. addUV( uvs[ 1 ] );
  24578. addUV( uvs[ 2 ] );
  24579. }
  24580. function f4( a, b, c, d ) {
  24581. addVertex( a );
  24582. addVertex( b );
  24583. addVertex( d );
  24584. addVertex( b );
  24585. addVertex( c );
  24586. addVertex( d );
  24587. var nextIndex = verticesArray.length / 3;
  24588. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  24589. addUV( uvs[ 0 ] );
  24590. addUV( uvs[ 1 ] );
  24591. addUV( uvs[ 3 ] );
  24592. addUV( uvs[ 1 ] );
  24593. addUV( uvs[ 2 ] );
  24594. addUV( uvs[ 3 ] );
  24595. }
  24596. function addVertex( index ) {
  24597. verticesArray.push( placeholder[ index * 3 + 0 ] );
  24598. verticesArray.push( placeholder[ index * 3 + 1 ] );
  24599. verticesArray.push( placeholder[ index * 3 + 2 ] );
  24600. }
  24601. function addUV( vector2 ) {
  24602. uvArray.push( vector2.x );
  24603. uvArray.push( vector2.y );
  24604. }
  24605. }
  24606. }
  24607. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24608. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  24609. ExtrudeBufferGeometry.prototype.toJSON = function () {
  24610. var data = BufferGeometry.prototype.toJSON.call( this );
  24611. var shapes = this.parameters.shapes;
  24612. var options = this.parameters.options;
  24613. return toJSON( shapes, options, data );
  24614. };
  24615. //
  24616. var WorldUVGenerator = {
  24617. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  24618. var a_x = vertices[ indexA * 3 ];
  24619. var a_y = vertices[ indexA * 3 + 1 ];
  24620. var b_x = vertices[ indexB * 3 ];
  24621. var b_y = vertices[ indexB * 3 + 1 ];
  24622. var c_x = vertices[ indexC * 3 ];
  24623. var c_y = vertices[ indexC * 3 + 1 ];
  24624. return [
  24625. new Vector2( a_x, a_y ),
  24626. new Vector2( b_x, b_y ),
  24627. new Vector2( c_x, c_y )
  24628. ];
  24629. },
  24630. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  24631. var a_x = vertices[ indexA * 3 ];
  24632. var a_y = vertices[ indexA * 3 + 1 ];
  24633. var a_z = vertices[ indexA * 3 + 2 ];
  24634. var b_x = vertices[ indexB * 3 ];
  24635. var b_y = vertices[ indexB * 3 + 1 ];
  24636. var b_z = vertices[ indexB * 3 + 2 ];
  24637. var c_x = vertices[ indexC * 3 ];
  24638. var c_y = vertices[ indexC * 3 + 1 ];
  24639. var c_z = vertices[ indexC * 3 + 2 ];
  24640. var d_x = vertices[ indexD * 3 ];
  24641. var d_y = vertices[ indexD * 3 + 1 ];
  24642. var d_z = vertices[ indexD * 3 + 2 ];
  24643. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  24644. return [
  24645. new Vector2( a_x, 1 - a_z ),
  24646. new Vector2( b_x, 1 - b_z ),
  24647. new Vector2( c_x, 1 - c_z ),
  24648. new Vector2( d_x, 1 - d_z )
  24649. ];
  24650. } else {
  24651. return [
  24652. new Vector2( a_y, 1 - a_z ),
  24653. new Vector2( b_y, 1 - b_z ),
  24654. new Vector2( c_y, 1 - c_z ),
  24655. new Vector2( d_y, 1 - d_z )
  24656. ];
  24657. }
  24658. }
  24659. };
  24660. function toJSON( shapes, options, data ) {
  24661. //
  24662. data.shapes = [];
  24663. if ( Array.isArray( shapes ) ) {
  24664. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24665. var shape = shapes[ i ];
  24666. data.shapes.push( shape.uuid );
  24667. }
  24668. } else {
  24669. data.shapes.push( shapes.uuid );
  24670. }
  24671. //
  24672. if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); }
  24673. return data;
  24674. }
  24675. /**
  24676. * Text = 3D Text
  24677. *
  24678. * parameters = {
  24679. * font: <THREE.Font>, // font
  24680. *
  24681. * size: <float>, // size of the text
  24682. * height: <float>, // thickness to extrude text
  24683. * curveSegments: <int>, // number of points on the curves
  24684. *
  24685. * bevelEnabled: <bool>, // turn on bevel
  24686. * bevelThickness: <float>, // how deep into text bevel goes
  24687. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  24688. * bevelOffset: <float> // how far from text outline does bevel start
  24689. * }
  24690. */
  24691. // TextGeometry
  24692. function TextGeometry( text, parameters ) {
  24693. Geometry.call( this );
  24694. this.type = 'TextGeometry';
  24695. this.parameters = {
  24696. text: text,
  24697. parameters: parameters
  24698. };
  24699. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  24700. this.mergeVertices();
  24701. }
  24702. TextGeometry.prototype = Object.create( Geometry.prototype );
  24703. TextGeometry.prototype.constructor = TextGeometry;
  24704. // TextBufferGeometry
  24705. function TextBufferGeometry( text, parameters ) {
  24706. parameters = parameters || {};
  24707. var font = parameters.font;
  24708. if ( ! ( font && font.isFont ) ) {
  24709. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  24710. return new Geometry();
  24711. }
  24712. var shapes = font.generateShapes( text, parameters.size );
  24713. // translate parameters to ExtrudeGeometry API
  24714. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  24715. // defaults
  24716. if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; }
  24717. if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; }
  24718. if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; }
  24719. ExtrudeBufferGeometry.call( this, shapes, parameters );
  24720. this.type = 'TextBufferGeometry';
  24721. }
  24722. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  24723. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  24724. // SphereGeometry
  24725. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24726. Geometry.call( this );
  24727. this.type = 'SphereGeometry';
  24728. this.parameters = {
  24729. radius: radius,
  24730. widthSegments: widthSegments,
  24731. heightSegments: heightSegments,
  24732. phiStart: phiStart,
  24733. phiLength: phiLength,
  24734. thetaStart: thetaStart,
  24735. thetaLength: thetaLength
  24736. };
  24737. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  24738. this.mergeVertices();
  24739. }
  24740. SphereGeometry.prototype = Object.create( Geometry.prototype );
  24741. SphereGeometry.prototype.constructor = SphereGeometry;
  24742. // SphereBufferGeometry
  24743. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24744. BufferGeometry.call( this );
  24745. this.type = 'SphereBufferGeometry';
  24746. this.parameters = {
  24747. radius: radius,
  24748. widthSegments: widthSegments,
  24749. heightSegments: heightSegments,
  24750. phiStart: phiStart,
  24751. phiLength: phiLength,
  24752. thetaStart: thetaStart,
  24753. thetaLength: thetaLength
  24754. };
  24755. radius = radius || 1;
  24756. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  24757. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  24758. phiStart = phiStart !== undefined ? phiStart : 0;
  24759. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  24760. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24761. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  24762. var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  24763. var index = 0;
  24764. var grid = [];
  24765. var vertex = new Vector3();
  24766. var normal = new Vector3();
  24767. // buffers
  24768. var indices = [];
  24769. var vertices = [];
  24770. var normals = [];
  24771. var uvs = [];
  24772. // generate vertices, normals and uvs
  24773. for ( var iy = 0; iy <= heightSegments; iy ++ ) {
  24774. var verticesRow = [];
  24775. var v = iy / heightSegments;
  24776. // special case for the poles
  24777. var uOffset = 0;
  24778. if ( iy == 0 && thetaStart == 0 ) {
  24779. uOffset = 0.5 / widthSegments;
  24780. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  24781. uOffset = - 0.5 / widthSegments;
  24782. }
  24783. for ( var ix = 0; ix <= widthSegments; ix ++ ) {
  24784. var u = ix / widthSegments;
  24785. // vertex
  24786. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24787. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  24788. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24789. vertices.push( vertex.x, vertex.y, vertex.z );
  24790. // normal
  24791. normal.copy( vertex ).normalize();
  24792. normals.push( normal.x, normal.y, normal.z );
  24793. // uv
  24794. uvs.push( u + uOffset, 1 - v );
  24795. verticesRow.push( index ++ );
  24796. }
  24797. grid.push( verticesRow );
  24798. }
  24799. // indices
  24800. for ( var iy$1 = 0; iy$1 < heightSegments; iy$1 ++ ) {
  24801. for ( var ix$1 = 0; ix$1 < widthSegments; ix$1 ++ ) {
  24802. var a = grid[ iy$1 ][ ix$1 + 1 ];
  24803. var b = grid[ iy$1 ][ ix$1 ];
  24804. var c = grid[ iy$1 + 1 ][ ix$1 ];
  24805. var d = grid[ iy$1 + 1 ][ ix$1 + 1 ];
  24806. if ( iy$1 !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); }
  24807. if ( iy$1 !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); }
  24808. }
  24809. }
  24810. // build geometry
  24811. this.setIndex( indices );
  24812. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24813. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24814. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24815. }
  24816. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24817. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  24818. // RingGeometry
  24819. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24820. Geometry.call( this );
  24821. this.type = 'RingGeometry';
  24822. this.parameters = {
  24823. innerRadius: innerRadius,
  24824. outerRadius: outerRadius,
  24825. thetaSegments: thetaSegments,
  24826. phiSegments: phiSegments,
  24827. thetaStart: thetaStart,
  24828. thetaLength: thetaLength
  24829. };
  24830. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  24831. this.mergeVertices();
  24832. }
  24833. RingGeometry.prototype = Object.create( Geometry.prototype );
  24834. RingGeometry.prototype.constructor = RingGeometry;
  24835. // RingBufferGeometry
  24836. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24837. BufferGeometry.call( this );
  24838. this.type = 'RingBufferGeometry';
  24839. this.parameters = {
  24840. innerRadius: innerRadius,
  24841. outerRadius: outerRadius,
  24842. thetaSegments: thetaSegments,
  24843. phiSegments: phiSegments,
  24844. thetaStart: thetaStart,
  24845. thetaLength: thetaLength
  24846. };
  24847. innerRadius = innerRadius || 0.5;
  24848. outerRadius = outerRadius || 1;
  24849. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24850. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24851. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  24852. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  24853. // buffers
  24854. var indices = [];
  24855. var vertices = [];
  24856. var normals = [];
  24857. var uvs = [];
  24858. // some helper variables
  24859. var radius = innerRadius;
  24860. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  24861. var vertex = new Vector3();
  24862. var uv = new Vector2();
  24863. // generate vertices, normals and uvs
  24864. for ( var j = 0; j <= phiSegments; j ++ ) {
  24865. for ( var i = 0; i <= thetaSegments; i ++ ) {
  24866. // values are generate from the inside of the ring to the outside
  24867. var segment = thetaStart + i / thetaSegments * thetaLength;
  24868. // vertex
  24869. vertex.x = radius * Math.cos( segment );
  24870. vertex.y = radius * Math.sin( segment );
  24871. vertices.push( vertex.x, vertex.y, vertex.z );
  24872. // normal
  24873. normals.push( 0, 0, 1 );
  24874. // uv
  24875. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  24876. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  24877. uvs.push( uv.x, uv.y );
  24878. }
  24879. // increase the radius for next row of vertices
  24880. radius += radiusStep;
  24881. }
  24882. // indices
  24883. for ( var j$1 = 0; j$1 < phiSegments; j$1 ++ ) {
  24884. var thetaSegmentLevel = j$1 * ( thetaSegments + 1 );
  24885. for ( var i$1 = 0; i$1 < thetaSegments; i$1 ++ ) {
  24886. var segment$1 = i$1 + thetaSegmentLevel;
  24887. var a = segment$1;
  24888. var b = segment$1 + thetaSegments + 1;
  24889. var c = segment$1 + thetaSegments + 2;
  24890. var d = segment$1 + 1;
  24891. // faces
  24892. indices.push( a, b, d );
  24893. indices.push( b, c, d );
  24894. }
  24895. }
  24896. // build geometry
  24897. this.setIndex( indices );
  24898. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24899. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24900. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24901. }
  24902. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24903. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  24904. // LatheGeometry
  24905. function LatheGeometry( points, segments, phiStart, phiLength ) {
  24906. Geometry.call( this );
  24907. this.type = 'LatheGeometry';
  24908. this.parameters = {
  24909. points: points,
  24910. segments: segments,
  24911. phiStart: phiStart,
  24912. phiLength: phiLength
  24913. };
  24914. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  24915. this.mergeVertices();
  24916. }
  24917. LatheGeometry.prototype = Object.create( Geometry.prototype );
  24918. LatheGeometry.prototype.constructor = LatheGeometry;
  24919. // LatheBufferGeometry
  24920. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  24921. BufferGeometry.call( this );
  24922. this.type = 'LatheBufferGeometry';
  24923. this.parameters = {
  24924. points: points,
  24925. segments: segments,
  24926. phiStart: phiStart,
  24927. phiLength: phiLength
  24928. };
  24929. segments = Math.floor( segments ) || 12;
  24930. phiStart = phiStart || 0;
  24931. phiLength = phiLength || Math.PI * 2;
  24932. // clamp phiLength so it's in range of [ 0, 2PI ]
  24933. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  24934. // buffers
  24935. var indices = [];
  24936. var vertices = [];
  24937. var uvs = [];
  24938. // helper variables
  24939. var inverseSegments = 1.0 / segments;
  24940. var vertex = new Vector3();
  24941. var uv = new Vector2();
  24942. // generate vertices and uvs
  24943. for ( var i = 0; i <= segments; i ++ ) {
  24944. var phi = phiStart + i * inverseSegments * phiLength;
  24945. var sin = Math.sin( phi );
  24946. var cos = Math.cos( phi );
  24947. for ( var j = 0; j <= ( points.length - 1 ); j ++ ) {
  24948. // vertex
  24949. vertex.x = points[ j ].x * sin;
  24950. vertex.y = points[ j ].y;
  24951. vertex.z = points[ j ].x * cos;
  24952. vertices.push( vertex.x, vertex.y, vertex.z );
  24953. // uv
  24954. uv.x = i / segments;
  24955. uv.y = j / ( points.length - 1 );
  24956. uvs.push( uv.x, uv.y );
  24957. }
  24958. }
  24959. // indices
  24960. for ( var i$1 = 0; i$1 < segments; i$1 ++ ) {
  24961. for ( var j$1 = 0; j$1 < ( points.length - 1 ); j$1 ++ ) {
  24962. var base = j$1 + i$1 * points.length;
  24963. var a = base;
  24964. var b = base + points.length;
  24965. var c = base + points.length + 1;
  24966. var d = base + 1;
  24967. // faces
  24968. indices.push( a, b, d );
  24969. indices.push( b, c, d );
  24970. }
  24971. }
  24972. // build geometry
  24973. this.setIndex( indices );
  24974. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24975. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24976. // generate normals
  24977. this.computeVertexNormals();
  24978. // if the geometry is closed, we need to average the normals along the seam.
  24979. // because the corresponding vertices are identical (but still have different UVs).
  24980. if ( phiLength === Math.PI * 2 ) {
  24981. var normals = this.attributes.normal.array;
  24982. var n1 = new Vector3();
  24983. var n2 = new Vector3();
  24984. var n = new Vector3();
  24985. // this is the buffer offset for the last line of vertices
  24986. var base$1 = segments * points.length * 3;
  24987. for ( var i$2 = 0, j$2 = 0; i$2 < points.length; i$2 ++, j$2 += 3 ) {
  24988. // select the normal of the vertex in the first line
  24989. n1.x = normals[ j$2 + 0 ];
  24990. n1.y = normals[ j$2 + 1 ];
  24991. n1.z = normals[ j$2 + 2 ];
  24992. // select the normal of the vertex in the last line
  24993. n2.x = normals[ base$1 + j$2 + 0 ];
  24994. n2.y = normals[ base$1 + j$2 + 1 ];
  24995. n2.z = normals[ base$1 + j$2 + 2 ];
  24996. // average normals
  24997. n.addVectors( n1, n2 ).normalize();
  24998. // assign the new values to both normals
  24999. normals[ j$2 + 0 ] = normals[ base$1 + j$2 + 0 ] = n.x;
  25000. normals[ j$2 + 1 ] = normals[ base$1 + j$2 + 1 ] = n.y;
  25001. normals[ j$2 + 2 ] = normals[ base$1 + j$2 + 2 ] = n.z;
  25002. }
  25003. }
  25004. }
  25005. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25006. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  25007. // ShapeGeometry
  25008. function ShapeGeometry( shapes, curveSegments ) {
  25009. Geometry.call( this );
  25010. this.type = 'ShapeGeometry';
  25011. if ( typeof curveSegments === 'object' ) {
  25012. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  25013. curveSegments = curveSegments.curveSegments;
  25014. }
  25015. this.parameters = {
  25016. shapes: shapes,
  25017. curveSegments: curveSegments
  25018. };
  25019. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  25020. this.mergeVertices();
  25021. }
  25022. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  25023. ShapeGeometry.prototype.constructor = ShapeGeometry;
  25024. ShapeGeometry.prototype.toJSON = function () {
  25025. var data = Geometry.prototype.toJSON.call( this );
  25026. var shapes = this.parameters.shapes;
  25027. return toJSON$1( shapes, data );
  25028. };
  25029. // ShapeBufferGeometry
  25030. function ShapeBufferGeometry( shapes, curveSegments ) {
  25031. BufferGeometry.call( this );
  25032. this.type = 'ShapeBufferGeometry';
  25033. this.parameters = {
  25034. shapes: shapes,
  25035. curveSegments: curveSegments
  25036. };
  25037. curveSegments = curveSegments || 12;
  25038. // buffers
  25039. var indices = [];
  25040. var vertices = [];
  25041. var normals = [];
  25042. var uvs = [];
  25043. // helper variables
  25044. var groupStart = 0;
  25045. var groupCount = 0;
  25046. // allow single and array values for "shapes" parameter
  25047. if ( Array.isArray( shapes ) === false ) {
  25048. addShape( shapes );
  25049. } else {
  25050. for ( var i = 0; i < shapes.length; i ++ ) {
  25051. addShape( shapes[ i ] );
  25052. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  25053. groupStart += groupCount;
  25054. groupCount = 0;
  25055. }
  25056. }
  25057. // build geometry
  25058. this.setIndex( indices );
  25059. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25060. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25061. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25062. // helper functions
  25063. function addShape( shape ) {
  25064. var indexOffset = vertices.length / 3;
  25065. var points = shape.extractPoints( curveSegments );
  25066. var shapeVertices = points.shape;
  25067. var shapeHoles = points.holes;
  25068. // check direction of vertices
  25069. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  25070. shapeVertices = shapeVertices.reverse();
  25071. }
  25072. for ( var i = 0, l = shapeHoles.length; i < l; i ++ ) {
  25073. var shapeHole = shapeHoles[ i ];
  25074. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  25075. shapeHoles[ i ] = shapeHole.reverse();
  25076. }
  25077. }
  25078. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  25079. // join vertices of inner and outer paths to a single array
  25080. for ( var i$1 = 0, l$1 = shapeHoles.length; i$1 < l$1; i$1 ++ ) {
  25081. var shapeHole$1 = shapeHoles[ i$1 ];
  25082. shapeVertices = shapeVertices.concat( shapeHole$1 );
  25083. }
  25084. // vertices, normals, uvs
  25085. for ( var i$2 = 0, l$2 = shapeVertices.length; i$2 < l$2; i$2 ++ ) {
  25086. var vertex = shapeVertices[ i$2 ];
  25087. vertices.push( vertex.x, vertex.y, 0 );
  25088. normals.push( 0, 0, 1 );
  25089. uvs.push( vertex.x, vertex.y ); // world uvs
  25090. }
  25091. // incides
  25092. for ( var i$3 = 0, l$3 = faces.length; i$3 < l$3; i$3 ++ ) {
  25093. var face = faces[ i$3 ];
  25094. var a = face[ 0 ] + indexOffset;
  25095. var b = face[ 1 ] + indexOffset;
  25096. var c = face[ 2 ] + indexOffset;
  25097. indices.push( a, b, c );
  25098. groupCount += 3;
  25099. }
  25100. }
  25101. }
  25102. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25103. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  25104. ShapeBufferGeometry.prototype.toJSON = function () {
  25105. var data = BufferGeometry.prototype.toJSON.call( this );
  25106. var shapes = this.parameters.shapes;
  25107. return toJSON$1( shapes, data );
  25108. };
  25109. //
  25110. function toJSON$1( shapes, data ) {
  25111. data.shapes = [];
  25112. if ( Array.isArray( shapes ) ) {
  25113. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  25114. var shape = shapes[ i ];
  25115. data.shapes.push( shape.uuid );
  25116. }
  25117. } else {
  25118. data.shapes.push( shapes.uuid );
  25119. }
  25120. return data;
  25121. }
  25122. function EdgesGeometry( geometry, thresholdAngle ) {
  25123. BufferGeometry.call( this );
  25124. this.type = 'EdgesGeometry';
  25125. this.parameters = {
  25126. thresholdAngle: thresholdAngle
  25127. };
  25128. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  25129. // buffer
  25130. var vertices = [];
  25131. // helper variables
  25132. var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  25133. var edge = [ 0, 0 ], edges = {};
  25134. var edge1, edge2, key;
  25135. var keys = [ 'a', 'b', 'c' ];
  25136. // prepare source geometry
  25137. var geometry2;
  25138. if ( geometry.isBufferGeometry ) {
  25139. geometry2 = new Geometry();
  25140. geometry2.fromBufferGeometry( geometry );
  25141. } else {
  25142. geometry2 = geometry.clone();
  25143. }
  25144. geometry2.mergeVertices();
  25145. geometry2.computeFaceNormals();
  25146. var sourceVertices = geometry2.vertices;
  25147. var faces = geometry2.faces;
  25148. // now create a data structure where each entry represents an edge with its adjoining faces
  25149. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  25150. var face = faces[ i ];
  25151. for ( var j = 0; j < 3; j ++ ) {
  25152. edge1 = face[ keys[ j ] ];
  25153. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  25154. edge[ 0 ] = Math.min( edge1, edge2 );
  25155. edge[ 1 ] = Math.max( edge1, edge2 );
  25156. key = edge[ 0 ] + ',' + edge[ 1 ];
  25157. if ( edges[ key ] === undefined ) {
  25158. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  25159. } else {
  25160. edges[ key ].face2 = i;
  25161. }
  25162. }
  25163. }
  25164. // generate vertices
  25165. for ( key in edges ) {
  25166. var e = edges[ key ];
  25167. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  25168. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  25169. var vertex = sourceVertices[ e.index1 ];
  25170. vertices.push( vertex.x, vertex.y, vertex.z );
  25171. vertex = sourceVertices[ e.index2 ];
  25172. vertices.push( vertex.x, vertex.y, vertex.z );
  25173. }
  25174. }
  25175. // build geometry
  25176. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25177. }
  25178. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  25179. EdgesGeometry.prototype.constructor = EdgesGeometry;
  25180. // CylinderGeometry
  25181. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25182. Geometry.call( this );
  25183. this.type = 'CylinderGeometry';
  25184. this.parameters = {
  25185. radiusTop: radiusTop,
  25186. radiusBottom: radiusBottom,
  25187. height: height,
  25188. radialSegments: radialSegments,
  25189. heightSegments: heightSegments,
  25190. openEnded: openEnded,
  25191. thetaStart: thetaStart,
  25192. thetaLength: thetaLength
  25193. };
  25194. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  25195. this.mergeVertices();
  25196. }
  25197. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  25198. CylinderGeometry.prototype.constructor = CylinderGeometry;
  25199. // CylinderBufferGeometry
  25200. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25201. BufferGeometry.call( this );
  25202. this.type = 'CylinderBufferGeometry';
  25203. this.parameters = {
  25204. radiusTop: radiusTop,
  25205. radiusBottom: radiusBottom,
  25206. height: height,
  25207. radialSegments: radialSegments,
  25208. heightSegments: heightSegments,
  25209. openEnded: openEnded,
  25210. thetaStart: thetaStart,
  25211. thetaLength: thetaLength
  25212. };
  25213. var scope = this;
  25214. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  25215. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  25216. height = height || 1;
  25217. radialSegments = Math.floor( radialSegments ) || 8;
  25218. heightSegments = Math.floor( heightSegments ) || 1;
  25219. openEnded = openEnded !== undefined ? openEnded : false;
  25220. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  25221. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  25222. // buffers
  25223. var indices = [];
  25224. var vertices = [];
  25225. var normals = [];
  25226. var uvs = [];
  25227. // helper variables
  25228. var index = 0;
  25229. var indexArray = [];
  25230. var halfHeight = height / 2;
  25231. var groupStart = 0;
  25232. // generate geometry
  25233. generateTorso();
  25234. if ( openEnded === false ) {
  25235. if ( radiusTop > 0 ) { generateCap( true ); }
  25236. if ( radiusBottom > 0 ) { generateCap( false ); }
  25237. }
  25238. // build geometry
  25239. this.setIndex( indices );
  25240. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25241. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25242. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25243. function generateTorso() {
  25244. var normal = new Vector3();
  25245. var vertex = new Vector3();
  25246. var groupCount = 0;
  25247. // this will be used to calculate the normal
  25248. var slope = ( radiusBottom - radiusTop ) / height;
  25249. // generate vertices, normals and uvs
  25250. for ( var y = 0; y <= heightSegments; y ++ ) {
  25251. var indexRow = [];
  25252. var v = y / heightSegments;
  25253. // calculate the radius of the current row
  25254. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  25255. for ( var x = 0; x <= radialSegments; x ++ ) {
  25256. var u = x / radialSegments;
  25257. var theta = u * thetaLength + thetaStart;
  25258. var sinTheta = Math.sin( theta );
  25259. var cosTheta = Math.cos( theta );
  25260. // vertex
  25261. vertex.x = radius * sinTheta;
  25262. vertex.y = - v * height + halfHeight;
  25263. vertex.z = radius * cosTheta;
  25264. vertices.push( vertex.x, vertex.y, vertex.z );
  25265. // normal
  25266. normal.set( sinTheta, slope, cosTheta ).normalize();
  25267. normals.push( normal.x, normal.y, normal.z );
  25268. // uv
  25269. uvs.push( u, 1 - v );
  25270. // save index of vertex in respective row
  25271. indexRow.push( index ++ );
  25272. }
  25273. // now save vertices of the row in our index array
  25274. indexArray.push( indexRow );
  25275. }
  25276. // generate indices
  25277. for ( var x$1 = 0; x$1 < radialSegments; x$1 ++ ) {
  25278. for ( var y$1 = 0; y$1 < heightSegments; y$1 ++ ) {
  25279. // we use the index array to access the correct indices
  25280. var a = indexArray[ y$1 ][ x$1 ];
  25281. var b = indexArray[ y$1 + 1 ][ x$1 ];
  25282. var c = indexArray[ y$1 + 1 ][ x$1 + 1 ];
  25283. var d = indexArray[ y$1 ][ x$1 + 1 ];
  25284. // faces
  25285. indices.push( a, b, d );
  25286. indices.push( b, c, d );
  25287. // update group counter
  25288. groupCount += 6;
  25289. }
  25290. }
  25291. // add a group to the geometry. this will ensure multi material support
  25292. scope.addGroup( groupStart, groupCount, 0 );
  25293. // calculate new start value for groups
  25294. groupStart += groupCount;
  25295. }
  25296. function generateCap( top ) {
  25297. var centerIndexStart, centerIndexEnd;
  25298. var uv = new Vector2();
  25299. var vertex = new Vector3();
  25300. var groupCount = 0;
  25301. var radius = ( top === true ) ? radiusTop : radiusBottom;
  25302. var sign = ( top === true ) ? 1 : - 1;
  25303. // save the index of the first center vertex
  25304. centerIndexStart = index;
  25305. // first we generate the center vertex data of the cap.
  25306. // because the geometry needs one set of uvs per face,
  25307. // we must generate a center vertex per face/segment
  25308. for ( var x = 1; x <= radialSegments; x ++ ) {
  25309. // vertex
  25310. vertices.push( 0, halfHeight * sign, 0 );
  25311. // normal
  25312. normals.push( 0, sign, 0 );
  25313. // uv
  25314. uvs.push( 0.5, 0.5 );
  25315. // increase index
  25316. index ++;
  25317. }
  25318. // save the index of the last center vertex
  25319. centerIndexEnd = index;
  25320. // now we generate the surrounding vertices, normals and uvs
  25321. for ( var x$1 = 0; x$1 <= radialSegments; x$1 ++ ) {
  25322. var u = x$1 / radialSegments;
  25323. var theta = u * thetaLength + thetaStart;
  25324. var cosTheta = Math.cos( theta );
  25325. var sinTheta = Math.sin( theta );
  25326. // vertex
  25327. vertex.x = radius * sinTheta;
  25328. vertex.y = halfHeight * sign;
  25329. vertex.z = radius * cosTheta;
  25330. vertices.push( vertex.x, vertex.y, vertex.z );
  25331. // normal
  25332. normals.push( 0, sign, 0 );
  25333. // uv
  25334. uv.x = ( cosTheta * 0.5 ) + 0.5;
  25335. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  25336. uvs.push( uv.x, uv.y );
  25337. // increase index
  25338. index ++;
  25339. }
  25340. // generate indices
  25341. for ( var x$2 = 0; x$2 < radialSegments; x$2 ++ ) {
  25342. var c = centerIndexStart + x$2;
  25343. var i = centerIndexEnd + x$2;
  25344. if ( top === true ) {
  25345. // face top
  25346. indices.push( i, i + 1, c );
  25347. } else {
  25348. // face bottom
  25349. indices.push( i + 1, i, c );
  25350. }
  25351. groupCount += 3;
  25352. }
  25353. // add a group to the geometry. this will ensure multi material support
  25354. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  25355. // calculate new start value for groups
  25356. groupStart += groupCount;
  25357. }
  25358. }
  25359. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25360. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  25361. // ConeGeometry
  25362. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25363. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  25364. this.type = 'ConeGeometry';
  25365. this.parameters = {
  25366. radius: radius,
  25367. height: height,
  25368. radialSegments: radialSegments,
  25369. heightSegments: heightSegments,
  25370. openEnded: openEnded,
  25371. thetaStart: thetaStart,
  25372. thetaLength: thetaLength
  25373. };
  25374. }
  25375. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  25376. ConeGeometry.prototype.constructor = ConeGeometry;
  25377. // ConeBufferGeometry
  25378. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25379. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  25380. this.type = 'ConeBufferGeometry';
  25381. this.parameters = {
  25382. radius: radius,
  25383. height: height,
  25384. radialSegments: radialSegments,
  25385. heightSegments: heightSegments,
  25386. openEnded: openEnded,
  25387. thetaStart: thetaStart,
  25388. thetaLength: thetaLength
  25389. };
  25390. }
  25391. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  25392. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  25393. // CircleGeometry
  25394. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  25395. Geometry.call( this );
  25396. this.type = 'CircleGeometry';
  25397. this.parameters = {
  25398. radius: radius,
  25399. segments: segments,
  25400. thetaStart: thetaStart,
  25401. thetaLength: thetaLength
  25402. };
  25403. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  25404. this.mergeVertices();
  25405. }
  25406. CircleGeometry.prototype = Object.create( Geometry.prototype );
  25407. CircleGeometry.prototype.constructor = CircleGeometry;
  25408. // CircleBufferGeometry
  25409. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  25410. BufferGeometry.call( this );
  25411. this.type = 'CircleBufferGeometry';
  25412. this.parameters = {
  25413. radius: radius,
  25414. segments: segments,
  25415. thetaStart: thetaStart,
  25416. thetaLength: thetaLength
  25417. };
  25418. radius = radius || 1;
  25419. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  25420. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  25421. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  25422. // buffers
  25423. var indices = [];
  25424. var vertices = [];
  25425. var normals = [];
  25426. var uvs = [];
  25427. // helper variables
  25428. var vertex = new Vector3();
  25429. var uv = new Vector2();
  25430. // center point
  25431. vertices.push( 0, 0, 0 );
  25432. normals.push( 0, 0, 1 );
  25433. uvs.push( 0.5, 0.5 );
  25434. for ( var s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  25435. var segment = thetaStart + s / segments * thetaLength;
  25436. // vertex
  25437. vertex.x = radius * Math.cos( segment );
  25438. vertex.y = radius * Math.sin( segment );
  25439. vertices.push( vertex.x, vertex.y, vertex.z );
  25440. // normal
  25441. normals.push( 0, 0, 1 );
  25442. // uvs
  25443. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  25444. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  25445. uvs.push( uv.x, uv.y );
  25446. }
  25447. // indices
  25448. for ( var i$1 = 1; i$1 <= segments; i$1 ++ ) {
  25449. indices.push( i$1, i$1 + 1, 0 );
  25450. }
  25451. // build geometry
  25452. this.setIndex( indices );
  25453. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25454. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25455. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25456. }
  25457. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25458. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  25459. var Geometries = /*#__PURE__*/Object.freeze({
  25460. __proto__: null,
  25461. WireframeGeometry: WireframeGeometry,
  25462. ParametricGeometry: ParametricGeometry,
  25463. ParametricBufferGeometry: ParametricBufferGeometry,
  25464. TetrahedronGeometry: TetrahedronGeometry,
  25465. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  25466. OctahedronGeometry: OctahedronGeometry,
  25467. OctahedronBufferGeometry: OctahedronBufferGeometry,
  25468. IcosahedronGeometry: IcosahedronGeometry,
  25469. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  25470. DodecahedronGeometry: DodecahedronGeometry,
  25471. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  25472. PolyhedronGeometry: PolyhedronGeometry,
  25473. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  25474. TubeGeometry: TubeGeometry,
  25475. TubeBufferGeometry: TubeBufferGeometry,
  25476. TorusKnotGeometry: TorusKnotGeometry,
  25477. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  25478. TorusGeometry: TorusGeometry,
  25479. TorusBufferGeometry: TorusBufferGeometry,
  25480. TextGeometry: TextGeometry,
  25481. TextBufferGeometry: TextBufferGeometry,
  25482. SphereGeometry: SphereGeometry,
  25483. SphereBufferGeometry: SphereBufferGeometry,
  25484. RingGeometry: RingGeometry,
  25485. RingBufferGeometry: RingBufferGeometry,
  25486. PlaneGeometry: PlaneGeometry,
  25487. PlaneBufferGeometry: PlaneBufferGeometry,
  25488. LatheGeometry: LatheGeometry,
  25489. LatheBufferGeometry: LatheBufferGeometry,
  25490. ShapeGeometry: ShapeGeometry,
  25491. ShapeBufferGeometry: ShapeBufferGeometry,
  25492. ExtrudeGeometry: ExtrudeGeometry,
  25493. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  25494. EdgesGeometry: EdgesGeometry,
  25495. ConeGeometry: ConeGeometry,
  25496. ConeBufferGeometry: ConeBufferGeometry,
  25497. CylinderGeometry: CylinderGeometry,
  25498. CylinderBufferGeometry: CylinderBufferGeometry,
  25499. CircleGeometry: CircleGeometry,
  25500. CircleBufferGeometry: CircleBufferGeometry,
  25501. BoxGeometry: BoxGeometry,
  25502. BoxBufferGeometry: BoxBufferGeometry
  25503. });
  25504. /**
  25505. * parameters = {
  25506. * color: <THREE.Color>
  25507. * }
  25508. */
  25509. function ShadowMaterial( parameters ) {
  25510. Material.call( this );
  25511. this.type = 'ShadowMaterial';
  25512. this.color = new Color( 0x000000 );
  25513. this.transparent = true;
  25514. this.setValues( parameters );
  25515. }
  25516. ShadowMaterial.prototype = Object.create( Material.prototype );
  25517. ShadowMaterial.prototype.constructor = ShadowMaterial;
  25518. ShadowMaterial.prototype.isShadowMaterial = true;
  25519. ShadowMaterial.prototype.copy = function ( source ) {
  25520. Material.prototype.copy.call( this, source );
  25521. this.color.copy( source.color );
  25522. return this;
  25523. };
  25524. function RawShaderMaterial( parameters ) {
  25525. ShaderMaterial.call( this, parameters );
  25526. this.type = 'RawShaderMaterial';
  25527. }
  25528. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  25529. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  25530. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  25531. /**
  25532. * parameters = {
  25533. * color: <hex>,
  25534. * roughness: <float>,
  25535. * metalness: <float>,
  25536. * opacity: <float>,
  25537. *
  25538. * map: new THREE.Texture( <Image> ),
  25539. *
  25540. * lightMap: new THREE.Texture( <Image> ),
  25541. * lightMapIntensity: <float>
  25542. *
  25543. * aoMap: new THREE.Texture( <Image> ),
  25544. * aoMapIntensity: <float>
  25545. *
  25546. * emissive: <hex>,
  25547. * emissiveIntensity: <float>
  25548. * emissiveMap: new THREE.Texture( <Image> ),
  25549. *
  25550. * bumpMap: new THREE.Texture( <Image> ),
  25551. * bumpScale: <float>,
  25552. *
  25553. * normalMap: new THREE.Texture( <Image> ),
  25554. * normalMapType: THREE.TangentSpaceNormalMap,
  25555. * normalScale: <Vector2>,
  25556. *
  25557. * displacementMap: new THREE.Texture( <Image> ),
  25558. * displacementScale: <float>,
  25559. * displacementBias: <float>,
  25560. *
  25561. * roughnessMap: new THREE.Texture( <Image> ),
  25562. *
  25563. * metalnessMap: new THREE.Texture( <Image> ),
  25564. *
  25565. * alphaMap: new THREE.Texture( <Image> ),
  25566. *
  25567. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25568. * envMapIntensity: <float>
  25569. *
  25570. * refractionRatio: <float>,
  25571. *
  25572. * wireframe: <boolean>,
  25573. * wireframeLinewidth: <float>,
  25574. *
  25575. * skinning: <bool>,
  25576. * morphTargets: <bool>,
  25577. * morphNormals: <bool>
  25578. * }
  25579. */
  25580. function MeshStandardMaterial( parameters ) {
  25581. Material.call( this );
  25582. this.defines = { 'STANDARD': '' };
  25583. this.type = 'MeshStandardMaterial';
  25584. this.color = new Color( 0xffffff ); // diffuse
  25585. this.roughness = 1.0;
  25586. this.metalness = 0.0;
  25587. this.map = null;
  25588. this.lightMap = null;
  25589. this.lightMapIntensity = 1.0;
  25590. this.aoMap = null;
  25591. this.aoMapIntensity = 1.0;
  25592. this.emissive = new Color( 0x000000 );
  25593. this.emissiveIntensity = 1.0;
  25594. this.emissiveMap = null;
  25595. this.bumpMap = null;
  25596. this.bumpScale = 1;
  25597. this.normalMap = null;
  25598. this.normalMapType = TangentSpaceNormalMap;
  25599. this.normalScale = new Vector2( 1, 1 );
  25600. this.displacementMap = null;
  25601. this.displacementScale = 1;
  25602. this.displacementBias = 0;
  25603. this.roughnessMap = null;
  25604. this.metalnessMap = null;
  25605. this.alphaMap = null;
  25606. this.envMap = null;
  25607. this.envMapIntensity = 1.0;
  25608. this.refractionRatio = 0.98;
  25609. this.wireframe = false;
  25610. this.wireframeLinewidth = 1;
  25611. this.wireframeLinecap = 'round';
  25612. this.wireframeLinejoin = 'round';
  25613. this.skinning = false;
  25614. this.morphTargets = false;
  25615. this.morphNormals = false;
  25616. this.vertexTangents = false;
  25617. this.setValues( parameters );
  25618. }
  25619. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  25620. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  25621. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  25622. MeshStandardMaterial.prototype.copy = function ( source ) {
  25623. Material.prototype.copy.call( this, source );
  25624. this.defines = { 'STANDARD': '' };
  25625. this.color.copy( source.color );
  25626. this.roughness = source.roughness;
  25627. this.metalness = source.metalness;
  25628. this.map = source.map;
  25629. this.lightMap = source.lightMap;
  25630. this.lightMapIntensity = source.lightMapIntensity;
  25631. this.aoMap = source.aoMap;
  25632. this.aoMapIntensity = source.aoMapIntensity;
  25633. this.emissive.copy( source.emissive );
  25634. this.emissiveMap = source.emissiveMap;
  25635. this.emissiveIntensity = source.emissiveIntensity;
  25636. this.bumpMap = source.bumpMap;
  25637. this.bumpScale = source.bumpScale;
  25638. this.normalMap = source.normalMap;
  25639. this.normalMapType = source.normalMapType;
  25640. this.normalScale.copy( source.normalScale );
  25641. this.displacementMap = source.displacementMap;
  25642. this.displacementScale = source.displacementScale;
  25643. this.displacementBias = source.displacementBias;
  25644. this.roughnessMap = source.roughnessMap;
  25645. this.metalnessMap = source.metalnessMap;
  25646. this.alphaMap = source.alphaMap;
  25647. this.envMap = source.envMap;
  25648. this.envMapIntensity = source.envMapIntensity;
  25649. this.refractionRatio = source.refractionRatio;
  25650. this.wireframe = source.wireframe;
  25651. this.wireframeLinewidth = source.wireframeLinewidth;
  25652. this.wireframeLinecap = source.wireframeLinecap;
  25653. this.wireframeLinejoin = source.wireframeLinejoin;
  25654. this.skinning = source.skinning;
  25655. this.morphTargets = source.morphTargets;
  25656. this.morphNormals = source.morphNormals;
  25657. this.vertexTangents = source.vertexTangents;
  25658. return this;
  25659. };
  25660. /**
  25661. * parameters = {
  25662. * clearcoat: <float>,
  25663. * clearcoatMap: new THREE.Texture( <Image> ),
  25664. * clearcoatRoughness: <float>,
  25665. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  25666. * clearcoatNormalScale: <Vector2>,
  25667. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  25668. *
  25669. * reflectivity: <float>,
  25670. *
  25671. * sheen: <Color>,
  25672. *
  25673. * transmission: <float>,
  25674. * transmissionMap: new THREE.Texture( <Image> )
  25675. * }
  25676. */
  25677. function MeshPhysicalMaterial( parameters ) {
  25678. MeshStandardMaterial.call( this );
  25679. this.defines = {
  25680. 'STANDARD': '',
  25681. 'PHYSICAL': ''
  25682. };
  25683. this.type = 'MeshPhysicalMaterial';
  25684. this.clearcoat = 0.0;
  25685. this.clearcoatMap = null;
  25686. this.clearcoatRoughness = 0.0;
  25687. this.clearcoatRoughnessMap = null;
  25688. this.clearcoatNormalScale = new Vector2( 1, 1 );
  25689. this.clearcoatNormalMap = null;
  25690. this.reflectivity = 0.5; // maps to F0 = 0.04
  25691. this.sheen = null; // null will disable sheen bsdf
  25692. this.transmission = 0.0;
  25693. this.transmissionMap = null;
  25694. this.setValues( parameters );
  25695. }
  25696. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  25697. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  25698. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  25699. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  25700. MeshStandardMaterial.prototype.copy.call( this, source );
  25701. this.defines = {
  25702. 'STANDARD': '',
  25703. 'PHYSICAL': ''
  25704. };
  25705. this.clearcoat = source.clearcoat;
  25706. this.clearcoatMap = source.clearcoatMap;
  25707. this.clearcoatRoughness = source.clearcoatRoughness;
  25708. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  25709. this.clearcoatNormalMap = source.clearcoatNormalMap;
  25710. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  25711. this.reflectivity = source.reflectivity;
  25712. if ( source.sheen ) {
  25713. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  25714. } else {
  25715. this.sheen = null;
  25716. }
  25717. this.transmission = source.transmission;
  25718. this.transmissionMap = source.transmissionMap;
  25719. return this;
  25720. };
  25721. /**
  25722. * parameters = {
  25723. * color: <hex>,
  25724. * specular: <hex>,
  25725. * shininess: <float>,
  25726. * opacity: <float>,
  25727. *
  25728. * map: new THREE.Texture( <Image> ),
  25729. *
  25730. * lightMap: new THREE.Texture( <Image> ),
  25731. * lightMapIntensity: <float>
  25732. *
  25733. * aoMap: new THREE.Texture( <Image> ),
  25734. * aoMapIntensity: <float>
  25735. *
  25736. * emissive: <hex>,
  25737. * emissiveIntensity: <float>
  25738. * emissiveMap: new THREE.Texture( <Image> ),
  25739. *
  25740. * bumpMap: new THREE.Texture( <Image> ),
  25741. * bumpScale: <float>,
  25742. *
  25743. * normalMap: new THREE.Texture( <Image> ),
  25744. * normalMapType: THREE.TangentSpaceNormalMap,
  25745. * normalScale: <Vector2>,
  25746. *
  25747. * displacementMap: new THREE.Texture( <Image> ),
  25748. * displacementScale: <float>,
  25749. * displacementBias: <float>,
  25750. *
  25751. * specularMap: new THREE.Texture( <Image> ),
  25752. *
  25753. * alphaMap: new THREE.Texture( <Image> ),
  25754. *
  25755. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25756. * combine: THREE.MultiplyOperation,
  25757. * reflectivity: <float>,
  25758. * refractionRatio: <float>,
  25759. *
  25760. * wireframe: <boolean>,
  25761. * wireframeLinewidth: <float>,
  25762. *
  25763. * skinning: <bool>,
  25764. * morphTargets: <bool>,
  25765. * morphNormals: <bool>
  25766. * }
  25767. */
  25768. function MeshPhongMaterial( parameters ) {
  25769. Material.call( this );
  25770. this.type = 'MeshPhongMaterial';
  25771. this.color = new Color( 0xffffff ); // diffuse
  25772. this.specular = new Color( 0x111111 );
  25773. this.shininess = 30;
  25774. this.map = null;
  25775. this.lightMap = null;
  25776. this.lightMapIntensity = 1.0;
  25777. this.aoMap = null;
  25778. this.aoMapIntensity = 1.0;
  25779. this.emissive = new Color( 0x000000 );
  25780. this.emissiveIntensity = 1.0;
  25781. this.emissiveMap = null;
  25782. this.bumpMap = null;
  25783. this.bumpScale = 1;
  25784. this.normalMap = null;
  25785. this.normalMapType = TangentSpaceNormalMap;
  25786. this.normalScale = new Vector2( 1, 1 );
  25787. this.displacementMap = null;
  25788. this.displacementScale = 1;
  25789. this.displacementBias = 0;
  25790. this.specularMap = null;
  25791. this.alphaMap = null;
  25792. this.envMap = null;
  25793. this.combine = MultiplyOperation;
  25794. this.reflectivity = 1;
  25795. this.refractionRatio = 0.98;
  25796. this.wireframe = false;
  25797. this.wireframeLinewidth = 1;
  25798. this.wireframeLinecap = 'round';
  25799. this.wireframeLinejoin = 'round';
  25800. this.skinning = false;
  25801. this.morphTargets = false;
  25802. this.morphNormals = false;
  25803. this.setValues( parameters );
  25804. }
  25805. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  25806. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  25807. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  25808. MeshPhongMaterial.prototype.copy = function ( source ) {
  25809. Material.prototype.copy.call( this, source );
  25810. this.color.copy( source.color );
  25811. this.specular.copy( source.specular );
  25812. this.shininess = source.shininess;
  25813. this.map = source.map;
  25814. this.lightMap = source.lightMap;
  25815. this.lightMapIntensity = source.lightMapIntensity;
  25816. this.aoMap = source.aoMap;
  25817. this.aoMapIntensity = source.aoMapIntensity;
  25818. this.emissive.copy( source.emissive );
  25819. this.emissiveMap = source.emissiveMap;
  25820. this.emissiveIntensity = source.emissiveIntensity;
  25821. this.bumpMap = source.bumpMap;
  25822. this.bumpScale = source.bumpScale;
  25823. this.normalMap = source.normalMap;
  25824. this.normalMapType = source.normalMapType;
  25825. this.normalScale.copy( source.normalScale );
  25826. this.displacementMap = source.displacementMap;
  25827. this.displacementScale = source.displacementScale;
  25828. this.displacementBias = source.displacementBias;
  25829. this.specularMap = source.specularMap;
  25830. this.alphaMap = source.alphaMap;
  25831. this.envMap = source.envMap;
  25832. this.combine = source.combine;
  25833. this.reflectivity = source.reflectivity;
  25834. this.refractionRatio = source.refractionRatio;
  25835. this.wireframe = source.wireframe;
  25836. this.wireframeLinewidth = source.wireframeLinewidth;
  25837. this.wireframeLinecap = source.wireframeLinecap;
  25838. this.wireframeLinejoin = source.wireframeLinejoin;
  25839. this.skinning = source.skinning;
  25840. this.morphTargets = source.morphTargets;
  25841. this.morphNormals = source.morphNormals;
  25842. return this;
  25843. };
  25844. /**
  25845. * parameters = {
  25846. * color: <hex>,
  25847. *
  25848. * map: new THREE.Texture( <Image> ),
  25849. * gradientMap: new THREE.Texture( <Image> ),
  25850. *
  25851. * lightMap: new THREE.Texture( <Image> ),
  25852. * lightMapIntensity: <float>
  25853. *
  25854. * aoMap: new THREE.Texture( <Image> ),
  25855. * aoMapIntensity: <float>
  25856. *
  25857. * emissive: <hex>,
  25858. * emissiveIntensity: <float>
  25859. * emissiveMap: new THREE.Texture( <Image> ),
  25860. *
  25861. * bumpMap: new THREE.Texture( <Image> ),
  25862. * bumpScale: <float>,
  25863. *
  25864. * normalMap: new THREE.Texture( <Image> ),
  25865. * normalMapType: THREE.TangentSpaceNormalMap,
  25866. * normalScale: <Vector2>,
  25867. *
  25868. * displacementMap: new THREE.Texture( <Image> ),
  25869. * displacementScale: <float>,
  25870. * displacementBias: <float>,
  25871. *
  25872. * alphaMap: new THREE.Texture( <Image> ),
  25873. *
  25874. * wireframe: <boolean>,
  25875. * wireframeLinewidth: <float>,
  25876. *
  25877. * skinning: <bool>,
  25878. * morphTargets: <bool>,
  25879. * morphNormals: <bool>
  25880. * }
  25881. */
  25882. function MeshToonMaterial( parameters ) {
  25883. Material.call( this );
  25884. this.defines = { 'TOON': '' };
  25885. this.type = 'MeshToonMaterial';
  25886. this.color = new Color( 0xffffff );
  25887. this.map = null;
  25888. this.gradientMap = null;
  25889. this.lightMap = null;
  25890. this.lightMapIntensity = 1.0;
  25891. this.aoMap = null;
  25892. this.aoMapIntensity = 1.0;
  25893. this.emissive = new Color( 0x000000 );
  25894. this.emissiveIntensity = 1.0;
  25895. this.emissiveMap = null;
  25896. this.bumpMap = null;
  25897. this.bumpScale = 1;
  25898. this.normalMap = null;
  25899. this.normalMapType = TangentSpaceNormalMap;
  25900. this.normalScale = new Vector2( 1, 1 );
  25901. this.displacementMap = null;
  25902. this.displacementScale = 1;
  25903. this.displacementBias = 0;
  25904. this.alphaMap = null;
  25905. this.wireframe = false;
  25906. this.wireframeLinewidth = 1;
  25907. this.wireframeLinecap = 'round';
  25908. this.wireframeLinejoin = 'round';
  25909. this.skinning = false;
  25910. this.morphTargets = false;
  25911. this.morphNormals = false;
  25912. this.setValues( parameters );
  25913. }
  25914. MeshToonMaterial.prototype = Object.create( Material.prototype );
  25915. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  25916. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  25917. MeshToonMaterial.prototype.copy = function ( source ) {
  25918. Material.prototype.copy.call( this, source );
  25919. this.color.copy( source.color );
  25920. this.map = source.map;
  25921. this.gradientMap = source.gradientMap;
  25922. this.lightMap = source.lightMap;
  25923. this.lightMapIntensity = source.lightMapIntensity;
  25924. this.aoMap = source.aoMap;
  25925. this.aoMapIntensity = source.aoMapIntensity;
  25926. this.emissive.copy( source.emissive );
  25927. this.emissiveMap = source.emissiveMap;
  25928. this.emissiveIntensity = source.emissiveIntensity;
  25929. this.bumpMap = source.bumpMap;
  25930. this.bumpScale = source.bumpScale;
  25931. this.normalMap = source.normalMap;
  25932. this.normalMapType = source.normalMapType;
  25933. this.normalScale.copy( source.normalScale );
  25934. this.displacementMap = source.displacementMap;
  25935. this.displacementScale = source.displacementScale;
  25936. this.displacementBias = source.displacementBias;
  25937. this.alphaMap = source.alphaMap;
  25938. this.wireframe = source.wireframe;
  25939. this.wireframeLinewidth = source.wireframeLinewidth;
  25940. this.wireframeLinecap = source.wireframeLinecap;
  25941. this.wireframeLinejoin = source.wireframeLinejoin;
  25942. this.skinning = source.skinning;
  25943. this.morphTargets = source.morphTargets;
  25944. this.morphNormals = source.morphNormals;
  25945. return this;
  25946. };
  25947. /**
  25948. * parameters = {
  25949. * opacity: <float>,
  25950. *
  25951. * bumpMap: new THREE.Texture( <Image> ),
  25952. * bumpScale: <float>,
  25953. *
  25954. * normalMap: new THREE.Texture( <Image> ),
  25955. * normalMapType: THREE.TangentSpaceNormalMap,
  25956. * normalScale: <Vector2>,
  25957. *
  25958. * displacementMap: new THREE.Texture( <Image> ),
  25959. * displacementScale: <float>,
  25960. * displacementBias: <float>,
  25961. *
  25962. * wireframe: <boolean>,
  25963. * wireframeLinewidth: <float>
  25964. *
  25965. * skinning: <bool>,
  25966. * morphTargets: <bool>,
  25967. * morphNormals: <bool>
  25968. * }
  25969. */
  25970. function MeshNormalMaterial( parameters ) {
  25971. Material.call( this );
  25972. this.type = 'MeshNormalMaterial';
  25973. this.bumpMap = null;
  25974. this.bumpScale = 1;
  25975. this.normalMap = null;
  25976. this.normalMapType = TangentSpaceNormalMap;
  25977. this.normalScale = new Vector2( 1, 1 );
  25978. this.displacementMap = null;
  25979. this.displacementScale = 1;
  25980. this.displacementBias = 0;
  25981. this.wireframe = false;
  25982. this.wireframeLinewidth = 1;
  25983. this.fog = false;
  25984. this.skinning = false;
  25985. this.morphTargets = false;
  25986. this.morphNormals = false;
  25987. this.setValues( parameters );
  25988. }
  25989. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  25990. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  25991. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  25992. MeshNormalMaterial.prototype.copy = function ( source ) {
  25993. Material.prototype.copy.call( this, source );
  25994. this.bumpMap = source.bumpMap;
  25995. this.bumpScale = source.bumpScale;
  25996. this.normalMap = source.normalMap;
  25997. this.normalMapType = source.normalMapType;
  25998. this.normalScale.copy( source.normalScale );
  25999. this.displacementMap = source.displacementMap;
  26000. this.displacementScale = source.displacementScale;
  26001. this.displacementBias = source.displacementBias;
  26002. this.wireframe = source.wireframe;
  26003. this.wireframeLinewidth = source.wireframeLinewidth;
  26004. this.skinning = source.skinning;
  26005. this.morphTargets = source.morphTargets;
  26006. this.morphNormals = source.morphNormals;
  26007. return this;
  26008. };
  26009. /**
  26010. * parameters = {
  26011. * color: <hex>,
  26012. * opacity: <float>,
  26013. *
  26014. * map: new THREE.Texture( <Image> ),
  26015. *
  26016. * lightMap: new THREE.Texture( <Image> ),
  26017. * lightMapIntensity: <float>
  26018. *
  26019. * aoMap: new THREE.Texture( <Image> ),
  26020. * aoMapIntensity: <float>
  26021. *
  26022. * emissive: <hex>,
  26023. * emissiveIntensity: <float>
  26024. * emissiveMap: new THREE.Texture( <Image> ),
  26025. *
  26026. * specularMap: new THREE.Texture( <Image> ),
  26027. *
  26028. * alphaMap: new THREE.Texture( <Image> ),
  26029. *
  26030. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  26031. * combine: THREE.Multiply,
  26032. * reflectivity: <float>,
  26033. * refractionRatio: <float>,
  26034. *
  26035. * wireframe: <boolean>,
  26036. * wireframeLinewidth: <float>,
  26037. *
  26038. * skinning: <bool>,
  26039. * morphTargets: <bool>,
  26040. * morphNormals: <bool>
  26041. * }
  26042. */
  26043. function MeshLambertMaterial( parameters ) {
  26044. Material.call( this );
  26045. this.type = 'MeshLambertMaterial';
  26046. this.color = new Color( 0xffffff ); // diffuse
  26047. this.map = null;
  26048. this.lightMap = null;
  26049. this.lightMapIntensity = 1.0;
  26050. this.aoMap = null;
  26051. this.aoMapIntensity = 1.0;
  26052. this.emissive = new Color( 0x000000 );
  26053. this.emissiveIntensity = 1.0;
  26054. this.emissiveMap = null;
  26055. this.specularMap = null;
  26056. this.alphaMap = null;
  26057. this.envMap = null;
  26058. this.combine = MultiplyOperation;
  26059. this.reflectivity = 1;
  26060. this.refractionRatio = 0.98;
  26061. this.wireframe = false;
  26062. this.wireframeLinewidth = 1;
  26063. this.wireframeLinecap = 'round';
  26064. this.wireframeLinejoin = 'round';
  26065. this.skinning = false;
  26066. this.morphTargets = false;
  26067. this.morphNormals = false;
  26068. this.setValues( parameters );
  26069. }
  26070. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  26071. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  26072. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  26073. MeshLambertMaterial.prototype.copy = function ( source ) {
  26074. Material.prototype.copy.call( this, source );
  26075. this.color.copy( source.color );
  26076. this.map = source.map;
  26077. this.lightMap = source.lightMap;
  26078. this.lightMapIntensity = source.lightMapIntensity;
  26079. this.aoMap = source.aoMap;
  26080. this.aoMapIntensity = source.aoMapIntensity;
  26081. this.emissive.copy( source.emissive );
  26082. this.emissiveMap = source.emissiveMap;
  26083. this.emissiveIntensity = source.emissiveIntensity;
  26084. this.specularMap = source.specularMap;
  26085. this.alphaMap = source.alphaMap;
  26086. this.envMap = source.envMap;
  26087. this.combine = source.combine;
  26088. this.reflectivity = source.reflectivity;
  26089. this.refractionRatio = source.refractionRatio;
  26090. this.wireframe = source.wireframe;
  26091. this.wireframeLinewidth = source.wireframeLinewidth;
  26092. this.wireframeLinecap = source.wireframeLinecap;
  26093. this.wireframeLinejoin = source.wireframeLinejoin;
  26094. this.skinning = source.skinning;
  26095. this.morphTargets = source.morphTargets;
  26096. this.morphNormals = source.morphNormals;
  26097. return this;
  26098. };
  26099. /**
  26100. * parameters = {
  26101. * color: <hex>,
  26102. * opacity: <float>,
  26103. *
  26104. * matcap: new THREE.Texture( <Image> ),
  26105. *
  26106. * map: new THREE.Texture( <Image> ),
  26107. *
  26108. * bumpMap: new THREE.Texture( <Image> ),
  26109. * bumpScale: <float>,
  26110. *
  26111. * normalMap: new THREE.Texture( <Image> ),
  26112. * normalMapType: THREE.TangentSpaceNormalMap,
  26113. * normalScale: <Vector2>,
  26114. *
  26115. * displacementMap: new THREE.Texture( <Image> ),
  26116. * displacementScale: <float>,
  26117. * displacementBias: <float>,
  26118. *
  26119. * alphaMap: new THREE.Texture( <Image> ),
  26120. *
  26121. * skinning: <bool>,
  26122. * morphTargets: <bool>,
  26123. * morphNormals: <bool>
  26124. * }
  26125. */
  26126. function MeshMatcapMaterial( parameters ) {
  26127. Material.call( this );
  26128. this.defines = { 'MATCAP': '' };
  26129. this.type = 'MeshMatcapMaterial';
  26130. this.color = new Color( 0xffffff ); // diffuse
  26131. this.matcap = null;
  26132. this.map = null;
  26133. this.bumpMap = null;
  26134. this.bumpScale = 1;
  26135. this.normalMap = null;
  26136. this.normalMapType = TangentSpaceNormalMap;
  26137. this.normalScale = new Vector2( 1, 1 );
  26138. this.displacementMap = null;
  26139. this.displacementScale = 1;
  26140. this.displacementBias = 0;
  26141. this.alphaMap = null;
  26142. this.skinning = false;
  26143. this.morphTargets = false;
  26144. this.morphNormals = false;
  26145. this.setValues( parameters );
  26146. }
  26147. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  26148. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  26149. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  26150. MeshMatcapMaterial.prototype.copy = function ( source ) {
  26151. Material.prototype.copy.call( this, source );
  26152. this.defines = { 'MATCAP': '' };
  26153. this.color.copy( source.color );
  26154. this.matcap = source.matcap;
  26155. this.map = source.map;
  26156. this.bumpMap = source.bumpMap;
  26157. this.bumpScale = source.bumpScale;
  26158. this.normalMap = source.normalMap;
  26159. this.normalMapType = source.normalMapType;
  26160. this.normalScale.copy( source.normalScale );
  26161. this.displacementMap = source.displacementMap;
  26162. this.displacementScale = source.displacementScale;
  26163. this.displacementBias = source.displacementBias;
  26164. this.alphaMap = source.alphaMap;
  26165. this.skinning = source.skinning;
  26166. this.morphTargets = source.morphTargets;
  26167. this.morphNormals = source.morphNormals;
  26168. return this;
  26169. };
  26170. /**
  26171. * parameters = {
  26172. * color: <hex>,
  26173. * opacity: <float>,
  26174. *
  26175. * linewidth: <float>,
  26176. *
  26177. * scale: <float>,
  26178. * dashSize: <float>,
  26179. * gapSize: <float>
  26180. * }
  26181. */
  26182. function LineDashedMaterial( parameters ) {
  26183. LineBasicMaterial.call( this );
  26184. this.type = 'LineDashedMaterial';
  26185. this.scale = 1;
  26186. this.dashSize = 3;
  26187. this.gapSize = 1;
  26188. this.setValues( parameters );
  26189. }
  26190. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  26191. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  26192. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  26193. LineDashedMaterial.prototype.copy = function ( source ) {
  26194. LineBasicMaterial.prototype.copy.call( this, source );
  26195. this.scale = source.scale;
  26196. this.dashSize = source.dashSize;
  26197. this.gapSize = source.gapSize;
  26198. return this;
  26199. };
  26200. var Materials = /*#__PURE__*/Object.freeze({
  26201. __proto__: null,
  26202. ShadowMaterial: ShadowMaterial,
  26203. SpriteMaterial: SpriteMaterial,
  26204. RawShaderMaterial: RawShaderMaterial,
  26205. ShaderMaterial: ShaderMaterial,
  26206. PointsMaterial: PointsMaterial,
  26207. MeshPhysicalMaterial: MeshPhysicalMaterial,
  26208. MeshStandardMaterial: MeshStandardMaterial,
  26209. MeshPhongMaterial: MeshPhongMaterial,
  26210. MeshToonMaterial: MeshToonMaterial,
  26211. MeshNormalMaterial: MeshNormalMaterial,
  26212. MeshLambertMaterial: MeshLambertMaterial,
  26213. MeshDepthMaterial: MeshDepthMaterial,
  26214. MeshDistanceMaterial: MeshDistanceMaterial,
  26215. MeshBasicMaterial: MeshBasicMaterial,
  26216. MeshMatcapMaterial: MeshMatcapMaterial,
  26217. LineDashedMaterial: LineDashedMaterial,
  26218. LineBasicMaterial: LineBasicMaterial,
  26219. Material: Material
  26220. });
  26221. var AnimationUtils = {
  26222. // same as Array.prototype.slice, but also works on typed arrays
  26223. arraySlice: function ( array, from, to ) {
  26224. if ( AnimationUtils.isTypedArray( array ) ) {
  26225. // in ios9 array.subarray(from, undefined) will return empty array
  26226. // but array.subarray(from) or array.subarray(from, len) is correct
  26227. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  26228. }
  26229. return array.slice( from, to );
  26230. },
  26231. // converts an array to a specific type
  26232. convertArray: function ( array, type, forceClone ) {
  26233. if ( ! array || // let 'undefined' and 'null' pass
  26234. ! forceClone && array.constructor === type ) { return array; }
  26235. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  26236. return new type( array ); // create typed array
  26237. }
  26238. return Array.prototype.slice.call( array ); // create Array
  26239. },
  26240. isTypedArray: function ( object ) {
  26241. return ArrayBuffer.isView( object ) &&
  26242. ! ( object instanceof DataView );
  26243. },
  26244. // returns an array by which times and values can be sorted
  26245. getKeyframeOrder: function ( times ) {
  26246. function compareTime( i, j ) {
  26247. return times[ i ] - times[ j ];
  26248. }
  26249. var n = times.length;
  26250. var result = new Array( n );
  26251. for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; }
  26252. result.sort( compareTime );
  26253. return result;
  26254. },
  26255. // uses the array previously returned by 'getKeyframeOrder' to sort data
  26256. sortedArray: function ( values, stride, order ) {
  26257. var nValues = values.length;
  26258. var result = new values.constructor( nValues );
  26259. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  26260. var srcOffset = order[ i ] * stride;
  26261. for ( var j = 0; j !== stride; ++ j ) {
  26262. result[ dstOffset ++ ] = values[ srcOffset + j ];
  26263. }
  26264. }
  26265. return result;
  26266. },
  26267. // function for parsing AOS keyframe formats
  26268. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  26269. var i = 1, key = jsonKeys[ 0 ];
  26270. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  26271. key = jsonKeys[ i ++ ];
  26272. }
  26273. if ( key === undefined ) { return; } // no data
  26274. var value = key[ valuePropertyName ];
  26275. if ( value === undefined ) { return; } // no data
  26276. if ( Array.isArray( value ) ) {
  26277. do {
  26278. value = key[ valuePropertyName ];
  26279. if ( value !== undefined ) {
  26280. times.push( key.time );
  26281. values.push.apply( values, value ); // push all elements
  26282. }
  26283. key = jsonKeys[ i ++ ];
  26284. } while ( key !== undefined );
  26285. } else if ( value.toArray !== undefined ) {
  26286. // ...assume THREE.Math-ish
  26287. do {
  26288. value = key[ valuePropertyName ];
  26289. if ( value !== undefined ) {
  26290. times.push( key.time );
  26291. value.toArray( values, values.length );
  26292. }
  26293. key = jsonKeys[ i ++ ];
  26294. } while ( key !== undefined );
  26295. } else {
  26296. // otherwise push as-is
  26297. do {
  26298. value = key[ valuePropertyName ];
  26299. if ( value !== undefined ) {
  26300. times.push( key.time );
  26301. values.push( value );
  26302. }
  26303. key = jsonKeys[ i ++ ];
  26304. } while ( key !== undefined );
  26305. }
  26306. },
  26307. subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {
  26308. fps = fps || 30;
  26309. var clip = sourceClip.clone();
  26310. clip.name = name;
  26311. var tracks = [];
  26312. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  26313. var track = clip.tracks[ i ];
  26314. var valueSize = track.getValueSize();
  26315. var times = [];
  26316. var values = [];
  26317. for ( var j = 0; j < track.times.length; ++ j ) {
  26318. var frame = track.times[ j ] * fps;
  26319. if ( frame < startFrame || frame >= endFrame ) { continue; }
  26320. times.push( track.times[ j ] );
  26321. for ( var k = 0; k < valueSize; ++ k ) {
  26322. values.push( track.values[ j * valueSize + k ] );
  26323. }
  26324. }
  26325. if ( times.length === 0 ) { continue; }
  26326. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  26327. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  26328. tracks.push( track );
  26329. }
  26330. clip.tracks = tracks;
  26331. // find minimum .times value across all tracks in the trimmed clip
  26332. var minStartTime = Infinity;
  26333. for ( var i$1 = 0; i$1 < clip.tracks.length; ++ i$1 ) {
  26334. if ( minStartTime > clip.tracks[ i$1 ].times[ 0 ] ) {
  26335. minStartTime = clip.tracks[ i$1 ].times[ 0 ];
  26336. }
  26337. }
  26338. // shift all tracks such that clip begins at t=0
  26339. for ( var i$2 = 0; i$2 < clip.tracks.length; ++ i$2 ) {
  26340. clip.tracks[ i$2 ].shift( - 1 * minStartTime );
  26341. }
  26342. clip.resetDuration();
  26343. return clip;
  26344. },
  26345. makeClipAdditive: function ( targetClip, referenceFrame, referenceClip, fps ) {
  26346. if ( referenceFrame === undefined ) { referenceFrame = 0; }
  26347. if ( referenceClip === undefined ) { referenceClip = targetClip; }
  26348. if ( fps === undefined || fps <= 0 ) { fps = 30; }
  26349. var numTracks = targetClip.tracks.length;
  26350. var referenceTime = referenceFrame / fps;
  26351. // Make each track's values relative to the values at the reference frame
  26352. var loop = function ( i ) {
  26353. var referenceTrack = referenceClip.tracks[ i ];
  26354. var referenceTrackType = referenceTrack.ValueTypeName;
  26355. // Skip this track if it's non-numeric
  26356. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) { return; }
  26357. // Find the track in the target clip whose name and type matches the reference track
  26358. var targetTrack = targetClip.tracks.find( function ( track ) {
  26359. return track.name === referenceTrack.name
  26360. && track.ValueTypeName === referenceTrackType;
  26361. } );
  26362. if ( targetTrack === undefined ) { return; }
  26363. var valueSize = referenceTrack.getValueSize();
  26364. var lastIndex = referenceTrack.times.length - 1;
  26365. var referenceValue = (void 0);
  26366. // Find the value to subtract out of the track
  26367. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  26368. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  26369. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, 0, referenceTrack.valueSize );
  26370. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  26371. // Reference frame is after the last keyframe, so just use the last keyframe
  26372. var startIndex = lastIndex * valueSize;
  26373. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex );
  26374. } else {
  26375. // Interpolate to the reference value
  26376. var interpolant = referenceTrack.createInterpolant();
  26377. interpolant.evaluate( referenceTime );
  26378. referenceValue = interpolant.resultBuffer;
  26379. }
  26380. // Conjugate the quaternion
  26381. if ( referenceTrackType === 'quaternion' ) {
  26382. var referenceQuat = new Quaternion(
  26383. referenceValue[ 0 ],
  26384. referenceValue[ 1 ],
  26385. referenceValue[ 2 ],
  26386. referenceValue[ 3 ]
  26387. ).normalize().conjugate();
  26388. referenceQuat.toArray( referenceValue );
  26389. }
  26390. // Subtract the reference value from all of the track values
  26391. var numTimes = targetTrack.times.length;
  26392. for ( var j = 0; j < numTimes; ++ j ) {
  26393. var valueStart = j * valueSize;
  26394. if ( referenceTrackType === 'quaternion' ) {
  26395. // Multiply the conjugate for quaternion track types
  26396. Quaternion.multiplyQuaternionsFlat(
  26397. targetTrack.values,
  26398. valueStart,
  26399. referenceValue,
  26400. 0,
  26401. targetTrack.values,
  26402. valueStart
  26403. );
  26404. } else {
  26405. // Subtract each value for all other numeric track types
  26406. for ( var k = 0; k < valueSize; ++ k ) {
  26407. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  26408. }
  26409. }
  26410. }
  26411. };
  26412. for ( var i = 0; i < numTracks; ++ i ) loop( i );
  26413. targetClip.blendMode = AdditiveAnimationBlendMode;
  26414. return targetClip;
  26415. }
  26416. };
  26417. /**
  26418. * Abstract base class of interpolants over parametric samples.
  26419. *
  26420. * The parameter domain is one dimensional, typically the time or a path
  26421. * along a curve defined by the data.
  26422. *
  26423. * The sample values can have any dimensionality and derived classes may
  26424. * apply special interpretations to the data.
  26425. *
  26426. * This class provides the interval seek in a Template Method, deferring
  26427. * the actual interpolation to derived classes.
  26428. *
  26429. * Time complexity is O(1) for linear access crossing at most two points
  26430. * and O(log N) for random access, where N is the number of positions.
  26431. *
  26432. * References:
  26433. *
  26434. * http://www.oodesign.com/template-method-pattern.html
  26435. *
  26436. */
  26437. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26438. this.parameterPositions = parameterPositions;
  26439. this._cachedIndex = 0;
  26440. this.resultBuffer = resultBuffer !== undefined ?
  26441. resultBuffer : new sampleValues.constructor( sampleSize );
  26442. this.sampleValues = sampleValues;
  26443. this.valueSize = sampleSize;
  26444. }
  26445. Object.assign( Interpolant.prototype, {
  26446. evaluate: function ( t ) {
  26447. var pp = this.parameterPositions,
  26448. i1 = this._cachedIndex,
  26449. t1 = pp[ i1 ],
  26450. t0 = pp[ i1 - 1 ];
  26451. validate_interval: {
  26452. seek: {
  26453. var right;
  26454. linear_scan: {
  26455. //- See http://jsperf.com/comparison-to-undefined/3
  26456. //- slower code:
  26457. //-
  26458. //- if ( t >= t1 || t1 === undefined ) {
  26459. forward_scan: if ( ! ( t < t1 ) ) {
  26460. for ( var giveUpAt = i1 + 2; ; ) {
  26461. if ( t1 === undefined ) {
  26462. if ( t < t0 ) { break forward_scan; }
  26463. // after end
  26464. i1 = pp.length;
  26465. this._cachedIndex = i1;
  26466. return this.afterEnd_( i1 - 1, t, t0 );
  26467. }
  26468. if ( i1 === giveUpAt ) { break; } // this loop
  26469. t0 = t1;
  26470. t1 = pp[ ++ i1 ];
  26471. if ( t < t1 ) {
  26472. // we have arrived at the sought interval
  26473. break seek;
  26474. }
  26475. }
  26476. // prepare binary search on the right side of the index
  26477. right = pp.length;
  26478. break linear_scan;
  26479. }
  26480. //- slower code:
  26481. //- if ( t < t0 || t0 === undefined ) {
  26482. if ( ! ( t >= t0 ) ) {
  26483. // looping?
  26484. var t1global = pp[ 1 ];
  26485. if ( t < t1global ) {
  26486. i1 = 2; // + 1, using the scan for the details
  26487. t0 = t1global;
  26488. }
  26489. // linear reverse scan
  26490. for ( var giveUpAt$1 = i1 - 2; ; ) {
  26491. if ( t0 === undefined ) {
  26492. // before start
  26493. this._cachedIndex = 0;
  26494. return this.beforeStart_( 0, t, t1 );
  26495. }
  26496. if ( i1 === giveUpAt$1 ) { break; } // this loop
  26497. t1 = t0;
  26498. t0 = pp[ -- i1 - 1 ];
  26499. if ( t >= t0 ) {
  26500. // we have arrived at the sought interval
  26501. break seek;
  26502. }
  26503. }
  26504. // prepare binary search on the left side of the index
  26505. right = i1;
  26506. i1 = 0;
  26507. break linear_scan;
  26508. }
  26509. // the interval is valid
  26510. break validate_interval;
  26511. } // linear scan
  26512. // binary search
  26513. while ( i1 < right ) {
  26514. var mid = ( i1 + right ) >>> 1;
  26515. if ( t < pp[ mid ] ) {
  26516. right = mid;
  26517. } else {
  26518. i1 = mid + 1;
  26519. }
  26520. }
  26521. t1 = pp[ i1 ];
  26522. t0 = pp[ i1 - 1 ];
  26523. // check boundary cases, again
  26524. if ( t0 === undefined ) {
  26525. this._cachedIndex = 0;
  26526. return this.beforeStart_( 0, t, t1 );
  26527. }
  26528. if ( t1 === undefined ) {
  26529. i1 = pp.length;
  26530. this._cachedIndex = i1;
  26531. return this.afterEnd_( i1 - 1, t0, t );
  26532. }
  26533. } // seek
  26534. this._cachedIndex = i1;
  26535. this.intervalChanged_( i1, t0, t1 );
  26536. } // validate_interval
  26537. return this.interpolate_( i1, t0, t, t1 );
  26538. },
  26539. settings: null, // optional, subclass-specific settings structure
  26540. // Note: The indirection allows central control of many interpolants.
  26541. // --- Protected interface
  26542. DefaultSettings_: {},
  26543. getSettings_: function () {
  26544. return this.settings || this.DefaultSettings_;
  26545. },
  26546. copySampleValue_: function ( index ) {
  26547. // copies a sample value to the result buffer
  26548. var result = this.resultBuffer,
  26549. values = this.sampleValues,
  26550. stride = this.valueSize,
  26551. offset = index * stride;
  26552. for ( var i = 0; i !== stride; ++ i ) {
  26553. result[ i ] = values[ offset + i ];
  26554. }
  26555. return result;
  26556. },
  26557. // Template methods for derived classes:
  26558. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  26559. throw new Error( 'call to abstract method' );
  26560. // implementations shall return this.resultBuffer
  26561. },
  26562. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  26563. // empty
  26564. }
  26565. } );
  26566. // DECLARE ALIAS AFTER assign prototype
  26567. Object.assign( Interpolant.prototype, {
  26568. //( 0, t, t0 ), returns this.resultBuffer
  26569. beforeStart_: Interpolant.prototype.copySampleValue_,
  26570. //( N-1, tN-1, t ), returns this.resultBuffer
  26571. afterEnd_: Interpolant.prototype.copySampleValue_,
  26572. } );
  26573. /**
  26574. * Fast and simple cubic spline interpolant.
  26575. *
  26576. * It was derived from a Hermitian construction setting the first derivative
  26577. * at each sample position to the linear slope between neighboring positions
  26578. * over their parameter interval.
  26579. */
  26580. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26581. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26582. this._weightPrev = - 0;
  26583. this._offsetPrev = - 0;
  26584. this._weightNext = - 0;
  26585. this._offsetNext = - 0;
  26586. }
  26587. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26588. constructor: CubicInterpolant,
  26589. DefaultSettings_: {
  26590. endingStart: ZeroCurvatureEnding,
  26591. endingEnd: ZeroCurvatureEnding
  26592. },
  26593. intervalChanged_: function ( i1, t0, t1 ) {
  26594. var pp = this.parameterPositions,
  26595. iPrev = i1 - 2,
  26596. iNext = i1 + 1,
  26597. tPrev = pp[ iPrev ],
  26598. tNext = pp[ iNext ];
  26599. if ( tPrev === undefined ) {
  26600. switch ( this.getSettings_().endingStart ) {
  26601. case ZeroSlopeEnding:
  26602. // f'(t0) = 0
  26603. iPrev = i1;
  26604. tPrev = 2 * t0 - t1;
  26605. break;
  26606. case WrapAroundEnding:
  26607. // use the other end of the curve
  26608. iPrev = pp.length - 2;
  26609. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  26610. break;
  26611. default: // ZeroCurvatureEnding
  26612. // f''(t0) = 0 a.k.a. Natural Spline
  26613. iPrev = i1;
  26614. tPrev = t1;
  26615. }
  26616. }
  26617. if ( tNext === undefined ) {
  26618. switch ( this.getSettings_().endingEnd ) {
  26619. case ZeroSlopeEnding:
  26620. // f'(tN) = 0
  26621. iNext = i1;
  26622. tNext = 2 * t1 - t0;
  26623. break;
  26624. case WrapAroundEnding:
  26625. // use the other end of the curve
  26626. iNext = 1;
  26627. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  26628. break;
  26629. default: // ZeroCurvatureEnding
  26630. // f''(tN) = 0, a.k.a. Natural Spline
  26631. iNext = i1 - 1;
  26632. tNext = t0;
  26633. }
  26634. }
  26635. var halfDt = ( t1 - t0 ) * 0.5,
  26636. stride = this.valueSize;
  26637. this._weightPrev = halfDt / ( t0 - tPrev );
  26638. this._weightNext = halfDt / ( tNext - t1 );
  26639. this._offsetPrev = iPrev * stride;
  26640. this._offsetNext = iNext * stride;
  26641. },
  26642. interpolate_: function ( i1, t0, t, t1 ) {
  26643. var result = this.resultBuffer,
  26644. values = this.sampleValues,
  26645. stride = this.valueSize,
  26646. o1 = i1 * stride, o0 = o1 - stride,
  26647. oP = this._offsetPrev, oN = this._offsetNext,
  26648. wP = this._weightPrev, wN = this._weightNext,
  26649. p = ( t - t0 ) / ( t1 - t0 ),
  26650. pp = p * p,
  26651. ppp = pp * p;
  26652. // evaluate polynomials
  26653. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  26654. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  26655. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  26656. var sN = wN * ppp - wN * pp;
  26657. // combine data linearly
  26658. for ( var i = 0; i !== stride; ++ i ) {
  26659. result[ i ] =
  26660. sP * values[ oP + i ] +
  26661. s0 * values[ o0 + i ] +
  26662. s1 * values[ o1 + i ] +
  26663. sN * values[ oN + i ];
  26664. }
  26665. return result;
  26666. }
  26667. } );
  26668. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26669. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26670. }
  26671. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26672. constructor: LinearInterpolant,
  26673. interpolate_: function ( i1, t0, t, t1 ) {
  26674. var result = this.resultBuffer,
  26675. values = this.sampleValues,
  26676. stride = this.valueSize,
  26677. offset1 = i1 * stride,
  26678. offset0 = offset1 - stride,
  26679. weight1 = ( t - t0 ) / ( t1 - t0 ),
  26680. weight0 = 1 - weight1;
  26681. for ( var i = 0; i !== stride; ++ i ) {
  26682. result[ i ] =
  26683. values[ offset0 + i ] * weight0 +
  26684. values[ offset1 + i ] * weight1;
  26685. }
  26686. return result;
  26687. }
  26688. } );
  26689. /**
  26690. *
  26691. * Interpolant that evaluates to the sample value at the position preceeding
  26692. * the parameter.
  26693. */
  26694. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26695. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26696. }
  26697. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26698. constructor: DiscreteInterpolant,
  26699. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  26700. return this.copySampleValue_( i1 - 1 );
  26701. }
  26702. } );
  26703. function KeyframeTrack( name, times, values, interpolation ) {
  26704. if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); }
  26705. if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); }
  26706. this.name = name;
  26707. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  26708. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  26709. this.setInterpolation( interpolation || this.DefaultInterpolation );
  26710. }
  26711. // Static methods
  26712. Object.assign( KeyframeTrack, {
  26713. // Serialization (in static context, because of constructor invocation
  26714. // and automatic invocation of .toJSON):
  26715. toJSON: function ( track ) {
  26716. var trackType = track.constructor;
  26717. var json;
  26718. // derived classes can define a static toJSON method
  26719. if ( trackType.toJSON !== undefined ) {
  26720. json = trackType.toJSON( track );
  26721. } else {
  26722. // by default, we assume the data can be serialized as-is
  26723. json = {
  26724. 'name': track.name,
  26725. 'times': AnimationUtils.convertArray( track.times, Array ),
  26726. 'values': AnimationUtils.convertArray( track.values, Array )
  26727. };
  26728. var interpolation = track.getInterpolation();
  26729. if ( interpolation !== track.DefaultInterpolation ) {
  26730. json.interpolation = interpolation;
  26731. }
  26732. }
  26733. json.type = track.ValueTypeName; // mandatory
  26734. return json;
  26735. }
  26736. } );
  26737. Object.assign( KeyframeTrack.prototype, {
  26738. constructor: KeyframeTrack,
  26739. TimeBufferType: Float32Array,
  26740. ValueBufferType: Float32Array,
  26741. DefaultInterpolation: InterpolateLinear,
  26742. InterpolantFactoryMethodDiscrete: function ( result ) {
  26743. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  26744. },
  26745. InterpolantFactoryMethodLinear: function ( result ) {
  26746. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  26747. },
  26748. InterpolantFactoryMethodSmooth: function ( result ) {
  26749. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  26750. },
  26751. setInterpolation: function ( interpolation ) {
  26752. var factoryMethod;
  26753. switch ( interpolation ) {
  26754. case InterpolateDiscrete:
  26755. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  26756. break;
  26757. case InterpolateLinear:
  26758. factoryMethod = this.InterpolantFactoryMethodLinear;
  26759. break;
  26760. case InterpolateSmooth:
  26761. factoryMethod = this.InterpolantFactoryMethodSmooth;
  26762. break;
  26763. }
  26764. if ( factoryMethod === undefined ) {
  26765. var message = "unsupported interpolation for " +
  26766. this.ValueTypeName + " keyframe track named " + this.name;
  26767. if ( this.createInterpolant === undefined ) {
  26768. // fall back to default, unless the default itself is messed up
  26769. if ( interpolation !== this.DefaultInterpolation ) {
  26770. this.setInterpolation( this.DefaultInterpolation );
  26771. } else {
  26772. throw new Error( message ); // fatal, in this case
  26773. }
  26774. }
  26775. console.warn( 'THREE.KeyframeTrack:', message );
  26776. return this;
  26777. }
  26778. this.createInterpolant = factoryMethod;
  26779. return this;
  26780. },
  26781. getInterpolation: function () {
  26782. switch ( this.createInterpolant ) {
  26783. case this.InterpolantFactoryMethodDiscrete:
  26784. return InterpolateDiscrete;
  26785. case this.InterpolantFactoryMethodLinear:
  26786. return InterpolateLinear;
  26787. case this.InterpolantFactoryMethodSmooth:
  26788. return InterpolateSmooth;
  26789. }
  26790. },
  26791. getValueSize: function () {
  26792. return this.values.length / this.times.length;
  26793. },
  26794. // move all keyframes either forwards or backwards in time
  26795. shift: function ( timeOffset ) {
  26796. if ( timeOffset !== 0.0 ) {
  26797. var times = this.times;
  26798. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  26799. times[ i ] += timeOffset;
  26800. }
  26801. }
  26802. return this;
  26803. },
  26804. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  26805. scale: function ( timeScale ) {
  26806. if ( timeScale !== 1.0 ) {
  26807. var times = this.times;
  26808. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  26809. times[ i ] *= timeScale;
  26810. }
  26811. }
  26812. return this;
  26813. },
  26814. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  26815. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  26816. trim: function ( startTime, endTime ) {
  26817. var times = this.times,
  26818. nKeys = times.length;
  26819. var from = 0,
  26820. to = nKeys - 1;
  26821. while ( from !== nKeys && times[ from ] < startTime ) {
  26822. ++ from;
  26823. }
  26824. while ( to !== - 1 && times[ to ] > endTime ) {
  26825. -- to;
  26826. }
  26827. ++ to; // inclusive -> exclusive bound
  26828. if ( from !== 0 || to !== nKeys ) {
  26829. // empty tracks are forbidden, so keep at least one keyframe
  26830. if ( from >= to ) {
  26831. to = Math.max( to, 1 );
  26832. from = to - 1;
  26833. }
  26834. var stride = this.getValueSize();
  26835. this.times = AnimationUtils.arraySlice( times, from, to );
  26836. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  26837. }
  26838. return this;
  26839. },
  26840. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  26841. validate: function () {
  26842. var valid = true;
  26843. var valueSize = this.getValueSize();
  26844. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  26845. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  26846. valid = false;
  26847. }
  26848. var times = this.times,
  26849. values = this.values,
  26850. nKeys = times.length;
  26851. if ( nKeys === 0 ) {
  26852. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  26853. valid = false;
  26854. }
  26855. var prevTime = null;
  26856. for ( var i = 0; i !== nKeys; i ++ ) {
  26857. var currTime = times[ i ];
  26858. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  26859. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  26860. valid = false;
  26861. break;
  26862. }
  26863. if ( prevTime !== null && prevTime > currTime ) {
  26864. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  26865. valid = false;
  26866. break;
  26867. }
  26868. prevTime = currTime;
  26869. }
  26870. if ( values !== undefined ) {
  26871. if ( AnimationUtils.isTypedArray( values ) ) {
  26872. for ( var i$1 = 0, n = values.length; i$1 !== n; ++ i$1 ) {
  26873. var value = values[ i$1 ];
  26874. if ( isNaN( value ) ) {
  26875. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i$1, value );
  26876. valid = false;
  26877. break;
  26878. }
  26879. }
  26880. }
  26881. }
  26882. return valid;
  26883. },
  26884. // removes equivalent sequential keys as common in morph target sequences
  26885. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  26886. optimize: function () {
  26887. // times or values may be shared with other tracks, so overwriting is unsafe
  26888. var times = AnimationUtils.arraySlice( this.times ),
  26889. values = AnimationUtils.arraySlice( this.values ),
  26890. stride = this.getValueSize(),
  26891. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  26892. lastIndex = times.length - 1;
  26893. var writeIndex = 1;
  26894. for ( var i = 1; i < lastIndex; ++ i ) {
  26895. var keep = false;
  26896. var time = times[ i ];
  26897. var timeNext = times[ i + 1 ];
  26898. // remove adjacent keyframes scheduled at the same time
  26899. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  26900. if ( ! smoothInterpolation ) {
  26901. // remove unnecessary keyframes same as their neighbors
  26902. var offset = i * stride,
  26903. offsetP = offset - stride,
  26904. offsetN = offset + stride;
  26905. for ( var j = 0; j !== stride; ++ j ) {
  26906. var value = values[ offset + j ];
  26907. if ( value !== values[ offsetP + j ] ||
  26908. value !== values[ offsetN + j ] ) {
  26909. keep = true;
  26910. break;
  26911. }
  26912. }
  26913. } else {
  26914. keep = true;
  26915. }
  26916. }
  26917. // in-place compaction
  26918. if ( keep ) {
  26919. if ( i !== writeIndex ) {
  26920. times[ writeIndex ] = times[ i ];
  26921. var readOffset = i * stride,
  26922. writeOffset = writeIndex * stride;
  26923. for ( var j$1 = 0; j$1 !== stride; ++ j$1 ) {
  26924. values[ writeOffset + j$1 ] = values[ readOffset + j$1 ];
  26925. }
  26926. }
  26927. ++ writeIndex;
  26928. }
  26929. }
  26930. // flush last keyframe (compaction looks ahead)
  26931. if ( lastIndex > 0 ) {
  26932. times[ writeIndex ] = times[ lastIndex ];
  26933. for ( var readOffset$1 = lastIndex * stride, writeOffset$1 = writeIndex * stride, j$2 = 0; j$2 !== stride; ++ j$2 ) {
  26934. values[ writeOffset$1 + j$2 ] = values[ readOffset$1 + j$2 ];
  26935. }
  26936. ++ writeIndex;
  26937. }
  26938. if ( writeIndex !== times.length ) {
  26939. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  26940. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  26941. } else {
  26942. this.times = times;
  26943. this.values = values;
  26944. }
  26945. return this;
  26946. },
  26947. clone: function () {
  26948. var times = AnimationUtils.arraySlice( this.times, 0 );
  26949. var values = AnimationUtils.arraySlice( this.values, 0 );
  26950. var TypedKeyframeTrack = this.constructor;
  26951. var track = new TypedKeyframeTrack( this.name, times, values );
  26952. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  26953. track.createInterpolant = this.createInterpolant;
  26954. return track;
  26955. }
  26956. } );
  26957. /**
  26958. * A Track of Boolean keyframe values.
  26959. */
  26960. function BooleanKeyframeTrack( name, times, values ) {
  26961. KeyframeTrack.call( this, name, times, values );
  26962. }
  26963. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26964. constructor: BooleanKeyframeTrack,
  26965. ValueTypeName: 'bool',
  26966. ValueBufferType: Array,
  26967. DefaultInterpolation: InterpolateDiscrete,
  26968. InterpolantFactoryMethodLinear: undefined,
  26969. InterpolantFactoryMethodSmooth: undefined
  26970. // Note: Actually this track could have a optimized / compressed
  26971. // representation of a single value and a custom interpolant that
  26972. // computes "firstValue ^ isOdd( index )".
  26973. } );
  26974. /**
  26975. * A Track of keyframe values that represent color.
  26976. */
  26977. function ColorKeyframeTrack( name, times, values, interpolation ) {
  26978. KeyframeTrack.call( this, name, times, values, interpolation );
  26979. }
  26980. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26981. constructor: ColorKeyframeTrack,
  26982. ValueTypeName: 'color'
  26983. // ValueBufferType is inherited
  26984. // DefaultInterpolation is inherited
  26985. // Note: Very basic implementation and nothing special yet.
  26986. // However, this is the place for color space parameterization.
  26987. } );
  26988. /**
  26989. * A Track of numeric keyframe values.
  26990. */
  26991. function NumberKeyframeTrack( name, times, values, interpolation ) {
  26992. KeyframeTrack.call( this, name, times, values, interpolation );
  26993. }
  26994. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26995. constructor: NumberKeyframeTrack,
  26996. ValueTypeName: 'number'
  26997. // ValueBufferType is inherited
  26998. // DefaultInterpolation is inherited
  26999. } );
  27000. /**
  27001. * Spherical linear unit quaternion interpolant.
  27002. */
  27003. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  27004. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  27005. }
  27006. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  27007. constructor: QuaternionLinearInterpolant,
  27008. interpolate_: function ( i1, t0, t, t1 ) {
  27009. var result = this.resultBuffer,
  27010. values = this.sampleValues,
  27011. stride = this.valueSize,
  27012. alpha = ( t - t0 ) / ( t1 - t0 );
  27013. var offset = i1 * stride;
  27014. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  27015. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  27016. }
  27017. return result;
  27018. }
  27019. } );
  27020. /**
  27021. * A Track of quaternion keyframe values.
  27022. */
  27023. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  27024. KeyframeTrack.call( this, name, times, values, interpolation );
  27025. }
  27026. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  27027. constructor: QuaternionKeyframeTrack,
  27028. ValueTypeName: 'quaternion',
  27029. // ValueBufferType is inherited
  27030. DefaultInterpolation: InterpolateLinear,
  27031. InterpolantFactoryMethodLinear: function ( result ) {
  27032. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  27033. },
  27034. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  27035. } );
  27036. /**
  27037. * A Track that interpolates Strings
  27038. */
  27039. function StringKeyframeTrack( name, times, values, interpolation ) {
  27040. KeyframeTrack.call( this, name, times, values, interpolation );
  27041. }
  27042. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  27043. constructor: StringKeyframeTrack,
  27044. ValueTypeName: 'string',
  27045. ValueBufferType: Array,
  27046. DefaultInterpolation: InterpolateDiscrete,
  27047. InterpolantFactoryMethodLinear: undefined,
  27048. InterpolantFactoryMethodSmooth: undefined
  27049. } );
  27050. /**
  27051. * A Track of vectored keyframe values.
  27052. */
  27053. function VectorKeyframeTrack( name, times, values, interpolation ) {
  27054. KeyframeTrack.call( this, name, times, values, interpolation );
  27055. }
  27056. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  27057. constructor: VectorKeyframeTrack,
  27058. ValueTypeName: 'vector'
  27059. // ValueBufferType is inherited
  27060. // DefaultInterpolation is inherited
  27061. } );
  27062. function AnimationClip( name, duration, tracks, blendMode ) {
  27063. this.name = name;
  27064. this.tracks = tracks;
  27065. this.duration = ( duration !== undefined ) ? duration : - 1;
  27066. this.blendMode = ( blendMode !== undefined ) ? blendMode : NormalAnimationBlendMode;
  27067. this.uuid = MathUtils.generateUUID();
  27068. // this means it should figure out its duration by scanning the tracks
  27069. if ( this.duration < 0 ) {
  27070. this.resetDuration();
  27071. }
  27072. }
  27073. function getTrackTypeForValueTypeName( typeName ) {
  27074. switch ( typeName.toLowerCase() ) {
  27075. case 'scalar':
  27076. case 'double':
  27077. case 'float':
  27078. case 'number':
  27079. case 'integer':
  27080. return NumberKeyframeTrack;
  27081. case 'vector':
  27082. case 'vector2':
  27083. case 'vector3':
  27084. case 'vector4':
  27085. return VectorKeyframeTrack;
  27086. case 'color':
  27087. return ColorKeyframeTrack;
  27088. case 'quaternion':
  27089. return QuaternionKeyframeTrack;
  27090. case 'bool':
  27091. case 'boolean':
  27092. return BooleanKeyframeTrack;
  27093. case 'string':
  27094. return StringKeyframeTrack;
  27095. }
  27096. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  27097. }
  27098. function parseKeyframeTrack( json ) {
  27099. if ( json.type === undefined ) {
  27100. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  27101. }
  27102. var trackType = getTrackTypeForValueTypeName( json.type );
  27103. if ( json.times === undefined ) {
  27104. var times = [], values = [];
  27105. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  27106. json.times = times;
  27107. json.values = values;
  27108. }
  27109. // derived classes can define a static parse method
  27110. if ( trackType.parse !== undefined ) {
  27111. return trackType.parse( json );
  27112. } else {
  27113. // by default, we assume a constructor compatible with the base
  27114. return new trackType( json.name, json.times, json.values, json.interpolation );
  27115. }
  27116. }
  27117. Object.assign( AnimationClip, {
  27118. parse: function ( json ) {
  27119. var tracks = [],
  27120. jsonTracks = json.tracks,
  27121. frameTime = 1.0 / ( json.fps || 1.0 );
  27122. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  27123. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  27124. }
  27125. return new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  27126. },
  27127. toJSON: function ( clip ) {
  27128. var tracks = [],
  27129. clipTracks = clip.tracks;
  27130. var json = {
  27131. 'name': clip.name,
  27132. 'duration': clip.duration,
  27133. 'tracks': tracks,
  27134. 'uuid': clip.uuid,
  27135. 'blendMode': clip.blendMode
  27136. };
  27137. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  27138. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  27139. }
  27140. return json;
  27141. },
  27142. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  27143. var numMorphTargets = morphTargetSequence.length;
  27144. var tracks = [];
  27145. for ( var i = 0; i < numMorphTargets; i ++ ) {
  27146. var times = [];
  27147. var values = [];
  27148. times.push(
  27149. ( i + numMorphTargets - 1 ) % numMorphTargets,
  27150. i,
  27151. ( i + 1 ) % numMorphTargets );
  27152. values.push( 0, 1, 0 );
  27153. var order = AnimationUtils.getKeyframeOrder( times );
  27154. times = AnimationUtils.sortedArray( times, 1, order );
  27155. values = AnimationUtils.sortedArray( values, 1, order );
  27156. // if there is a key at the first frame, duplicate it as the
  27157. // last frame as well for perfect loop.
  27158. if ( ! noLoop && times[ 0 ] === 0 ) {
  27159. times.push( numMorphTargets );
  27160. values.push( values[ 0 ] );
  27161. }
  27162. tracks.push(
  27163. new NumberKeyframeTrack(
  27164. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  27165. times, values
  27166. ).scale( 1.0 / fps ) );
  27167. }
  27168. return new AnimationClip( name, - 1, tracks );
  27169. },
  27170. findByName: function ( objectOrClipArray, name ) {
  27171. var clipArray = objectOrClipArray;
  27172. if ( ! Array.isArray( objectOrClipArray ) ) {
  27173. var o = objectOrClipArray;
  27174. clipArray = o.geometry && o.geometry.animations || o.animations;
  27175. }
  27176. for ( var i = 0; i < clipArray.length; i ++ ) {
  27177. if ( clipArray[ i ].name === name ) {
  27178. return clipArray[ i ];
  27179. }
  27180. }
  27181. return null;
  27182. },
  27183. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  27184. var animationToMorphTargets = {};
  27185. // tested with https://regex101.com/ on trick sequences
  27186. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  27187. var pattern = /^([\w-]*?)([\d]+)$/;
  27188. // sort morph target names into animation groups based
  27189. // patterns like Walk_001, Walk_002, Run_001, Run_002
  27190. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  27191. var morphTarget = morphTargets[ i ];
  27192. var parts = morphTarget.name.match( pattern );
  27193. if ( parts && parts.length > 1 ) {
  27194. var name = parts[ 1 ];
  27195. var animationMorphTargets = animationToMorphTargets[ name ];
  27196. if ( ! animationMorphTargets ) {
  27197. animationToMorphTargets[ name ] = animationMorphTargets = [];
  27198. }
  27199. animationMorphTargets.push( morphTarget );
  27200. }
  27201. }
  27202. var clips = [];
  27203. for ( var name$1 in animationToMorphTargets ) {
  27204. clips.push( AnimationClip.CreateFromMorphTargetSequence( name$1, animationToMorphTargets[ name$1 ], fps, noLoop ) );
  27205. }
  27206. return clips;
  27207. },
  27208. // parse the animation.hierarchy format
  27209. parseAnimation: function ( animation, bones ) {
  27210. if ( ! animation ) {
  27211. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  27212. return null;
  27213. }
  27214. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  27215. // only return track if there are actually keys.
  27216. if ( animationKeys.length !== 0 ) {
  27217. var times = [];
  27218. var values = [];
  27219. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  27220. // empty keys are filtered out, so check again
  27221. if ( times.length !== 0 ) {
  27222. destTracks.push( new trackType( trackName, times, values ) );
  27223. }
  27224. }
  27225. };
  27226. var tracks = [];
  27227. var clipName = animation.name || 'default';
  27228. var fps = animation.fps || 30;
  27229. var blendMode = animation.blendMode;
  27230. // automatic length determination in AnimationClip.
  27231. var duration = animation.length || - 1;
  27232. var hierarchyTracks = animation.hierarchy || [];
  27233. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  27234. var animationKeys = hierarchyTracks[ h ].keys;
  27235. // skip empty tracks
  27236. if ( ! animationKeys || animationKeys.length === 0 ) { continue; }
  27237. // process morph targets
  27238. if ( animationKeys[ 0 ].morphTargets ) {
  27239. // figure out all morph targets used in this track
  27240. var morphTargetNames = {};
  27241. var k = (void 0);
  27242. for ( k = 0; k < animationKeys.length; k ++ ) {
  27243. if ( animationKeys[ k ].morphTargets ) {
  27244. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  27245. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  27246. }
  27247. }
  27248. }
  27249. // create a track for each morph target with all zero
  27250. // morphTargetInfluences except for the keys in which
  27251. // the morphTarget is named.
  27252. for ( var morphTargetName in morphTargetNames ) {
  27253. var times = [];
  27254. var values = [];
  27255. for ( var m$1 = 0; m$1 !== animationKeys[ k ].morphTargets.length; ++ m$1 ) {
  27256. var animationKey = animationKeys[ k ];
  27257. times.push( animationKey.time );
  27258. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  27259. }
  27260. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  27261. }
  27262. duration = morphTargetNames.length * ( fps || 1.0 );
  27263. } else {
  27264. // ...assume skeletal animation
  27265. var boneName = '.bones[' + bones[ h ].name + ']';
  27266. addNonemptyTrack(
  27267. VectorKeyframeTrack, boneName + '.position',
  27268. animationKeys, 'pos', tracks );
  27269. addNonemptyTrack(
  27270. QuaternionKeyframeTrack, boneName + '.quaternion',
  27271. animationKeys, 'rot', tracks );
  27272. addNonemptyTrack(
  27273. VectorKeyframeTrack, boneName + '.scale',
  27274. animationKeys, 'scl', tracks );
  27275. }
  27276. }
  27277. if ( tracks.length === 0 ) {
  27278. return null;
  27279. }
  27280. var clip = new AnimationClip( clipName, duration, tracks, blendMode );
  27281. return clip;
  27282. }
  27283. } );
  27284. Object.assign( AnimationClip.prototype, {
  27285. resetDuration: function () {
  27286. var tracks = this.tracks;
  27287. var duration = 0;
  27288. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  27289. var track = this.tracks[ i ];
  27290. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  27291. }
  27292. this.duration = duration;
  27293. return this;
  27294. },
  27295. trim: function () {
  27296. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27297. this.tracks[ i ].trim( 0, this.duration );
  27298. }
  27299. return this;
  27300. },
  27301. validate: function () {
  27302. var valid = true;
  27303. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27304. valid = valid && this.tracks[ i ].validate();
  27305. }
  27306. return valid;
  27307. },
  27308. optimize: function () {
  27309. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27310. this.tracks[ i ].optimize();
  27311. }
  27312. return this;
  27313. },
  27314. clone: function () {
  27315. var tracks = [];
  27316. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27317. tracks.push( this.tracks[ i ].clone() );
  27318. }
  27319. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  27320. }
  27321. } );
  27322. var Cache = {
  27323. enabled: false,
  27324. files: {},
  27325. add: function ( key, file ) {
  27326. if ( this.enabled === false ) { return; }
  27327. // console.log( 'THREE.Cache', 'Adding key:', key );
  27328. this.files[ key ] = file;
  27329. },
  27330. get: function ( key ) {
  27331. if ( this.enabled === false ) { return; }
  27332. // console.log( 'THREE.Cache', 'Checking key:', key );
  27333. return this.files[ key ];
  27334. },
  27335. remove: function ( key ) {
  27336. delete this.files[ key ];
  27337. },
  27338. clear: function () {
  27339. this.files = {};
  27340. }
  27341. };
  27342. function LoadingManager( onLoad, onProgress, onError ) {
  27343. var scope = this;
  27344. var isLoading = false;
  27345. var itemsLoaded = 0;
  27346. var itemsTotal = 0;
  27347. var urlModifier = undefined;
  27348. var handlers = [];
  27349. // Refer to #5689 for the reason why we don't set .onStart
  27350. // in the constructor
  27351. this.onStart = undefined;
  27352. this.onLoad = onLoad;
  27353. this.onProgress = onProgress;
  27354. this.onError = onError;
  27355. this.itemStart = function ( url ) {
  27356. itemsTotal ++;
  27357. if ( isLoading === false ) {
  27358. if ( scope.onStart !== undefined ) {
  27359. scope.onStart( url, itemsLoaded, itemsTotal );
  27360. }
  27361. }
  27362. isLoading = true;
  27363. };
  27364. this.itemEnd = function ( url ) {
  27365. itemsLoaded ++;
  27366. if ( scope.onProgress !== undefined ) {
  27367. scope.onProgress( url, itemsLoaded, itemsTotal );
  27368. }
  27369. if ( itemsLoaded === itemsTotal ) {
  27370. isLoading = false;
  27371. if ( scope.onLoad !== undefined ) {
  27372. scope.onLoad();
  27373. }
  27374. }
  27375. };
  27376. this.itemError = function ( url ) {
  27377. if ( scope.onError !== undefined ) {
  27378. scope.onError( url );
  27379. }
  27380. };
  27381. this.resolveURL = function ( url ) {
  27382. if ( urlModifier ) {
  27383. return urlModifier( url );
  27384. }
  27385. return url;
  27386. };
  27387. this.setURLModifier = function ( transform ) {
  27388. urlModifier = transform;
  27389. return this;
  27390. };
  27391. this.addHandler = function ( regex, loader ) {
  27392. handlers.push( regex, loader );
  27393. return this;
  27394. };
  27395. this.removeHandler = function ( regex ) {
  27396. var index = handlers.indexOf( regex );
  27397. if ( index !== - 1 ) {
  27398. handlers.splice( index, 2 );
  27399. }
  27400. return this;
  27401. };
  27402. this.getHandler = function ( file ) {
  27403. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  27404. var regex = handlers[ i ];
  27405. var loader = handlers[ i + 1 ];
  27406. if ( regex.global ) { regex.lastIndex = 0; } // see #17920
  27407. if ( regex.test( file ) ) {
  27408. return loader;
  27409. }
  27410. }
  27411. return null;
  27412. };
  27413. }
  27414. var DefaultLoadingManager = new LoadingManager();
  27415. function Loader( manager ) {
  27416. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27417. this.crossOrigin = 'anonymous';
  27418. this.path = '';
  27419. this.resourcePath = '';
  27420. this.requestHeader = {};
  27421. }
  27422. Object.assign( Loader.prototype, {
  27423. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  27424. loadAsync: function ( url, onProgress ) {
  27425. var scope = this;
  27426. return new Promise( function ( resolve, reject ) {
  27427. scope.load( url, resolve, onProgress, reject );
  27428. } );
  27429. },
  27430. parse: function ( /* data */ ) {},
  27431. setCrossOrigin: function ( crossOrigin ) {
  27432. this.crossOrigin = crossOrigin;
  27433. return this;
  27434. },
  27435. setPath: function ( path ) {
  27436. this.path = path;
  27437. return this;
  27438. },
  27439. setResourcePath: function ( resourcePath ) {
  27440. this.resourcePath = resourcePath;
  27441. return this;
  27442. },
  27443. setRequestHeader: function ( requestHeader ) {
  27444. this.requestHeader = requestHeader;
  27445. return this;
  27446. }
  27447. } );
  27448. var loading = {};
  27449. function FileLoader( manager ) {
  27450. Loader.call( this, manager );
  27451. }
  27452. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27453. constructor: FileLoader,
  27454. load: function ( url, onLoad, onProgress, onError ) {
  27455. if ( url === undefined ) { url = ''; }
  27456. if ( this.path !== undefined ) { url = this.path + url; }
  27457. url = this.manager.resolveURL( url );
  27458. var scope = this;
  27459. var cached = Cache.get( url );
  27460. if ( cached !== undefined ) {
  27461. scope.manager.itemStart( url );
  27462. setTimeout( function () {
  27463. if ( onLoad ) { onLoad( cached ); }
  27464. scope.manager.itemEnd( url );
  27465. }, 0 );
  27466. return cached;
  27467. }
  27468. // Check if request is duplicate
  27469. if ( loading[ url ] !== undefined ) {
  27470. loading[ url ].push( {
  27471. onLoad: onLoad,
  27472. onProgress: onProgress,
  27473. onError: onError
  27474. } );
  27475. return;
  27476. }
  27477. // Check for data: URI
  27478. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  27479. var dataUriRegexResult = url.match( dataUriRegex );
  27480. var request;
  27481. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  27482. if ( dataUriRegexResult ) {
  27483. var mimeType = dataUriRegexResult[ 1 ];
  27484. var isBase64 = !! dataUriRegexResult[ 2 ];
  27485. var data = dataUriRegexResult[ 3 ];
  27486. data = decodeURIComponent( data );
  27487. if ( isBase64 ) { data = atob( data ); }
  27488. try {
  27489. var response;
  27490. var responseType = ( this.responseType || '' ).toLowerCase();
  27491. switch ( responseType ) {
  27492. case 'arraybuffer':
  27493. case 'blob':
  27494. var view = new Uint8Array( data.length );
  27495. for ( var i = 0; i < data.length; i ++ ) {
  27496. view[ i ] = data.charCodeAt( i );
  27497. }
  27498. if ( responseType === 'blob' ) {
  27499. response = new Blob( [ view.buffer ], { type: mimeType } );
  27500. } else {
  27501. response = view.buffer;
  27502. }
  27503. break;
  27504. case 'document':
  27505. var parser = new DOMParser();
  27506. response = parser.parseFromString( data, mimeType );
  27507. break;
  27508. case 'json':
  27509. response = JSON.parse( data );
  27510. break;
  27511. default: // 'text' or other
  27512. response = data;
  27513. break;
  27514. }
  27515. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27516. setTimeout( function () {
  27517. if ( onLoad ) { onLoad( response ); }
  27518. scope.manager.itemEnd( url );
  27519. }, 0 );
  27520. } catch ( error ) {
  27521. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27522. setTimeout( function () {
  27523. if ( onError ) { onError( error ); }
  27524. scope.manager.itemError( url );
  27525. scope.manager.itemEnd( url );
  27526. }, 0 );
  27527. }
  27528. } else {
  27529. // Initialise array for duplicate requests
  27530. loading[ url ] = [];
  27531. loading[ url ].push( {
  27532. onLoad: onLoad,
  27533. onProgress: onProgress,
  27534. onError: onError
  27535. } );
  27536. request = new XMLHttpRequest();
  27537. request.open( 'GET', url, true );
  27538. request.addEventListener( 'load', function ( event ) {
  27539. var response = this.response;
  27540. var callbacks = loading[ url ];
  27541. delete loading[ url ];
  27542. if ( this.status === 200 || this.status === 0 ) {
  27543. // Some browsers return HTTP Status 0 when using non-http protocol
  27544. // e.g. 'file://' or 'data://'. Handle as success.
  27545. if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); }
  27546. // Add to cache only on HTTP success, so that we do not cache
  27547. // error response bodies as proper responses to requests.
  27548. Cache.add( url, response );
  27549. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27550. var callback = callbacks[ i ];
  27551. if ( callback.onLoad ) { callback.onLoad( response ); }
  27552. }
  27553. scope.manager.itemEnd( url );
  27554. } else {
  27555. for ( var i$1 = 0, il$1 = callbacks.length; i$1 < il$1; i$1 ++ ) {
  27556. var callback$1 = callbacks[ i$1 ];
  27557. if ( callback$1.onError ) { callback$1.onError( event ); }
  27558. }
  27559. scope.manager.itemError( url );
  27560. scope.manager.itemEnd( url );
  27561. }
  27562. }, false );
  27563. request.addEventListener( 'progress', function ( event ) {
  27564. var callbacks = loading[ url ];
  27565. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27566. var callback = callbacks[ i ];
  27567. if ( callback.onProgress ) { callback.onProgress( event ); }
  27568. }
  27569. }, false );
  27570. request.addEventListener( 'error', function ( event ) {
  27571. var callbacks = loading[ url ];
  27572. delete loading[ url ];
  27573. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27574. var callback = callbacks[ i ];
  27575. if ( callback.onError ) { callback.onError( event ); }
  27576. }
  27577. scope.manager.itemError( url );
  27578. scope.manager.itemEnd( url );
  27579. }, false );
  27580. request.addEventListener( 'abort', function ( event ) {
  27581. var callbacks = loading[ url ];
  27582. delete loading[ url ];
  27583. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27584. var callback = callbacks[ i ];
  27585. if ( callback.onError ) { callback.onError( event ); }
  27586. }
  27587. scope.manager.itemError( url );
  27588. scope.manager.itemEnd( url );
  27589. }, false );
  27590. if ( this.responseType !== undefined ) { request.responseType = this.responseType; }
  27591. if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; }
  27592. if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); }
  27593. for ( var header in this.requestHeader ) {
  27594. request.setRequestHeader( header, this.requestHeader[ header ] );
  27595. }
  27596. request.send( null );
  27597. }
  27598. scope.manager.itemStart( url );
  27599. return request;
  27600. },
  27601. setResponseType: function ( value ) {
  27602. this.responseType = value;
  27603. return this;
  27604. },
  27605. setWithCredentials: function ( value ) {
  27606. this.withCredentials = value;
  27607. return this;
  27608. },
  27609. setMimeType: function ( value ) {
  27610. this.mimeType = value;
  27611. return this;
  27612. }
  27613. } );
  27614. function AnimationLoader( manager ) {
  27615. Loader.call( this, manager );
  27616. }
  27617. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27618. constructor: AnimationLoader,
  27619. load: function ( url, onLoad, onProgress, onError ) {
  27620. var scope = this;
  27621. var loader = new FileLoader( scope.manager );
  27622. loader.setPath( scope.path );
  27623. loader.setRequestHeader( scope.requestHeader );
  27624. loader.load( url, function ( text ) {
  27625. try {
  27626. onLoad( scope.parse( JSON.parse( text ) ) );
  27627. } catch ( e ) {
  27628. if ( onError ) {
  27629. onError( e );
  27630. } else {
  27631. console.error( e );
  27632. }
  27633. scope.manager.itemError( url );
  27634. }
  27635. }, onProgress, onError );
  27636. },
  27637. parse: function ( json ) {
  27638. var animations = [];
  27639. for ( var i = 0; i < json.length; i ++ ) {
  27640. var clip = AnimationClip.parse( json[ i ] );
  27641. animations.push( clip );
  27642. }
  27643. return animations;
  27644. }
  27645. } );
  27646. /**
  27647. * Abstract Base class to block based textures loader (dds, pvr, ...)
  27648. *
  27649. * Sub classes have to implement the parse() method which will be used in load().
  27650. */
  27651. function CompressedTextureLoader( manager ) {
  27652. Loader.call( this, manager );
  27653. }
  27654. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27655. constructor: CompressedTextureLoader,
  27656. load: function ( url, onLoad, onProgress, onError ) {
  27657. var scope = this;
  27658. var images = [];
  27659. var texture = new CompressedTexture();
  27660. texture.image = images;
  27661. var loader = new FileLoader( this.manager );
  27662. loader.setPath( this.path );
  27663. loader.setResponseType( 'arraybuffer' );
  27664. loader.setRequestHeader( this.requestHeader );
  27665. var loaded = 0;
  27666. function loadTexture( i ) {
  27667. loader.load( url[ i ], function ( buffer ) {
  27668. var texDatas = scope.parse( buffer, true );
  27669. images[ i ] = {
  27670. width: texDatas.width,
  27671. height: texDatas.height,
  27672. format: texDatas.format,
  27673. mipmaps: texDatas.mipmaps
  27674. };
  27675. loaded += 1;
  27676. if ( loaded === 6 ) {
  27677. if ( texDatas.mipmapCount === 1 )
  27678. { texture.minFilter = LinearFilter; }
  27679. texture.format = texDatas.format;
  27680. texture.needsUpdate = true;
  27681. if ( onLoad ) { onLoad( texture ); }
  27682. }
  27683. }, onProgress, onError );
  27684. }
  27685. if ( Array.isArray( url ) ) {
  27686. for ( var i = 0, il = url.length; i < il; ++ i ) {
  27687. loadTexture( i );
  27688. }
  27689. } else {
  27690. // compressed cubemap texture stored in a single DDS file
  27691. loader.load( url, function ( buffer ) {
  27692. var texDatas = scope.parse( buffer, true );
  27693. if ( texDatas.isCubemap ) {
  27694. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  27695. for ( var f = 0; f < faces; f ++ ) {
  27696. images[ f ] = { mipmaps: [] };
  27697. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  27698. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  27699. images[ f ].format = texDatas.format;
  27700. images[ f ].width = texDatas.width;
  27701. images[ f ].height = texDatas.height;
  27702. }
  27703. }
  27704. } else {
  27705. texture.image.width = texDatas.width;
  27706. texture.image.height = texDatas.height;
  27707. texture.mipmaps = texDatas.mipmaps;
  27708. }
  27709. if ( texDatas.mipmapCount === 1 ) {
  27710. texture.minFilter = LinearFilter;
  27711. }
  27712. texture.format = texDatas.format;
  27713. texture.needsUpdate = true;
  27714. if ( onLoad ) { onLoad( texture ); }
  27715. }, onProgress, onError );
  27716. }
  27717. return texture;
  27718. }
  27719. } );
  27720. /**
  27721. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  27722. *
  27723. * Sub classes have to implement the parse() method which will be used in load().
  27724. */
  27725. function DataTextureLoader( manager ) {
  27726. Loader.call( this, manager );
  27727. }
  27728. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27729. constructor: DataTextureLoader,
  27730. load: function ( url, onLoad, onProgress, onError ) {
  27731. var scope = this;
  27732. var texture = new DataTexture();
  27733. var loader = new FileLoader( this.manager );
  27734. loader.setResponseType( 'arraybuffer' );
  27735. loader.setRequestHeader( this.requestHeader );
  27736. loader.setPath( this.path );
  27737. loader.load( url, function ( buffer ) {
  27738. var texData = scope.parse( buffer );
  27739. if ( ! texData ) { return; }
  27740. if ( texData.image !== undefined ) {
  27741. texture.image = texData.image;
  27742. } else if ( texData.data !== undefined ) {
  27743. texture.image.width = texData.width;
  27744. texture.image.height = texData.height;
  27745. texture.image.data = texData.data;
  27746. }
  27747. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  27748. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  27749. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  27750. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  27751. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  27752. if ( texData.format !== undefined ) {
  27753. texture.format = texData.format;
  27754. }
  27755. if ( texData.type !== undefined ) {
  27756. texture.type = texData.type;
  27757. }
  27758. if ( texData.mipmaps !== undefined ) {
  27759. texture.mipmaps = texData.mipmaps;
  27760. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  27761. }
  27762. if ( texData.mipmapCount === 1 ) {
  27763. texture.minFilter = LinearFilter;
  27764. }
  27765. texture.needsUpdate = true;
  27766. if ( onLoad ) { onLoad( texture, texData ); }
  27767. }, onProgress, onError );
  27768. return texture;
  27769. }
  27770. } );
  27771. function ImageLoader( manager ) {
  27772. Loader.call( this, manager );
  27773. }
  27774. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27775. constructor: ImageLoader,
  27776. load: function ( url, onLoad, onProgress, onError ) {
  27777. if ( this.path !== undefined ) { url = this.path + url; }
  27778. url = this.manager.resolveURL( url );
  27779. var scope = this;
  27780. var cached = Cache.get( url );
  27781. if ( cached !== undefined ) {
  27782. scope.manager.itemStart( url );
  27783. setTimeout( function () {
  27784. if ( onLoad ) { onLoad( cached ); }
  27785. scope.manager.itemEnd( url );
  27786. }, 0 );
  27787. return cached;
  27788. }
  27789. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  27790. function onImageLoad() {
  27791. image.removeEventListener( 'load', onImageLoad, false );
  27792. image.removeEventListener( 'error', onImageError, false );
  27793. Cache.add( url, this );
  27794. if ( onLoad ) { onLoad( this ); }
  27795. scope.manager.itemEnd( url );
  27796. }
  27797. function onImageError( event ) {
  27798. image.removeEventListener( 'load', onImageLoad, false );
  27799. image.removeEventListener( 'error', onImageError, false );
  27800. if ( onError ) { onError( event ); }
  27801. scope.manager.itemError( url );
  27802. scope.manager.itemEnd( url );
  27803. }
  27804. image.addEventListener( 'load', onImageLoad, false );
  27805. image.addEventListener( 'error', onImageError, false );
  27806. if ( url.substr( 0, 5 ) !== 'data:' ) {
  27807. if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; }
  27808. }
  27809. scope.manager.itemStart( url );
  27810. image.src = url;
  27811. return image;
  27812. }
  27813. } );
  27814. function CubeTextureLoader( manager ) {
  27815. Loader.call( this, manager );
  27816. }
  27817. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27818. constructor: CubeTextureLoader,
  27819. load: function ( urls, onLoad, onProgress, onError ) {
  27820. var texture = new CubeTexture();
  27821. var loader = new ImageLoader( this.manager );
  27822. loader.setCrossOrigin( this.crossOrigin );
  27823. loader.setPath( this.path );
  27824. var loaded = 0;
  27825. function loadTexture( i ) {
  27826. loader.load( urls[ i ], function ( image ) {
  27827. texture.images[ i ] = image;
  27828. loaded ++;
  27829. if ( loaded === 6 ) {
  27830. texture.needsUpdate = true;
  27831. if ( onLoad ) { onLoad( texture ); }
  27832. }
  27833. }, undefined, onError );
  27834. }
  27835. for ( var i = 0; i < urls.length; ++ i ) {
  27836. loadTexture( i );
  27837. }
  27838. return texture;
  27839. }
  27840. } );
  27841. function TextureLoader( manager ) {
  27842. Loader.call( this, manager );
  27843. }
  27844. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27845. constructor: TextureLoader,
  27846. load: function ( url, onLoad, onProgress, onError ) {
  27847. var texture = new Texture();
  27848. var loader = new ImageLoader( this.manager );
  27849. loader.setCrossOrigin( this.crossOrigin );
  27850. loader.setPath( this.path );
  27851. loader.load( url, function ( image ) {
  27852. texture.image = image;
  27853. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  27854. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  27855. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  27856. texture.needsUpdate = true;
  27857. if ( onLoad !== undefined ) {
  27858. onLoad( texture );
  27859. }
  27860. }, onProgress, onError );
  27861. return texture;
  27862. }
  27863. } );
  27864. /**
  27865. * Extensible curve object.
  27866. *
  27867. * Some common of curve methods:
  27868. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  27869. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  27870. * .getPoints(), .getSpacedPoints()
  27871. * .getLength()
  27872. * .updateArcLengths()
  27873. *
  27874. * This following curves inherit from THREE.Curve:
  27875. *
  27876. * -- 2D curves --
  27877. * THREE.ArcCurve
  27878. * THREE.CubicBezierCurve
  27879. * THREE.EllipseCurve
  27880. * THREE.LineCurve
  27881. * THREE.QuadraticBezierCurve
  27882. * THREE.SplineCurve
  27883. *
  27884. * -- 3D curves --
  27885. * THREE.CatmullRomCurve3
  27886. * THREE.CubicBezierCurve3
  27887. * THREE.LineCurve3
  27888. * THREE.QuadraticBezierCurve3
  27889. *
  27890. * A series of curves can be represented as a THREE.CurvePath.
  27891. *
  27892. **/
  27893. function Curve() {
  27894. this.type = 'Curve';
  27895. this.arcLengthDivisions = 200;
  27896. }
  27897. Object.assign( Curve.prototype, {
  27898. // Virtual base class method to overwrite and implement in subclasses
  27899. // - t [0 .. 1]
  27900. getPoint: function ( /* t, optionalTarget */ ) {
  27901. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  27902. return null;
  27903. },
  27904. // Get point at relative position in curve according to arc length
  27905. // - u [0 .. 1]
  27906. getPointAt: function ( u, optionalTarget ) {
  27907. var t = this.getUtoTmapping( u );
  27908. return this.getPoint( t, optionalTarget );
  27909. },
  27910. // Get sequence of points using getPoint( t )
  27911. getPoints: function ( divisions ) {
  27912. if ( divisions === undefined ) { divisions = 5; }
  27913. var points = [];
  27914. for ( var d = 0; d <= divisions; d ++ ) {
  27915. points.push( this.getPoint( d / divisions ) );
  27916. }
  27917. return points;
  27918. },
  27919. // Get sequence of points using getPointAt( u )
  27920. getSpacedPoints: function ( divisions ) {
  27921. if ( divisions === undefined ) { divisions = 5; }
  27922. var points = [];
  27923. for ( var d = 0; d <= divisions; d ++ ) {
  27924. points.push( this.getPointAt( d / divisions ) );
  27925. }
  27926. return points;
  27927. },
  27928. // Get total curve arc length
  27929. getLength: function () {
  27930. var lengths = this.getLengths();
  27931. return lengths[ lengths.length - 1 ];
  27932. },
  27933. // Get list of cumulative segment lengths
  27934. getLengths: function ( divisions ) {
  27935. if ( divisions === undefined ) { divisions = this.arcLengthDivisions; }
  27936. if ( this.cacheArcLengths &&
  27937. ( this.cacheArcLengths.length === divisions + 1 ) &&
  27938. ! this.needsUpdate ) {
  27939. return this.cacheArcLengths;
  27940. }
  27941. this.needsUpdate = false;
  27942. var cache = [];
  27943. var current, last = this.getPoint( 0 );
  27944. var sum = 0;
  27945. cache.push( 0 );
  27946. for ( var p = 1; p <= divisions; p ++ ) {
  27947. current = this.getPoint( p / divisions );
  27948. sum += current.distanceTo( last );
  27949. cache.push( sum );
  27950. last = current;
  27951. }
  27952. this.cacheArcLengths = cache;
  27953. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  27954. },
  27955. updateArcLengths: function () {
  27956. this.needsUpdate = true;
  27957. this.getLengths();
  27958. },
  27959. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  27960. getUtoTmapping: function ( u, distance ) {
  27961. var arcLengths = this.getLengths();
  27962. var i = 0, il = arcLengths.length;
  27963. var targetArcLength; // The targeted u distance value to get
  27964. if ( distance ) {
  27965. targetArcLength = distance;
  27966. } else {
  27967. targetArcLength = u * arcLengths[ il - 1 ];
  27968. }
  27969. // binary search for the index with largest value smaller than target u distance
  27970. var low = 0, high = il - 1, comparison;
  27971. while ( low <= high ) {
  27972. 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
  27973. comparison = arcLengths[ i ] - targetArcLength;
  27974. if ( comparison < 0 ) {
  27975. low = i + 1;
  27976. } else if ( comparison > 0 ) {
  27977. high = i - 1;
  27978. } else {
  27979. high = i;
  27980. break;
  27981. // DONE
  27982. }
  27983. }
  27984. i = high;
  27985. if ( arcLengths[ i ] === targetArcLength ) {
  27986. return i / ( il - 1 );
  27987. }
  27988. // we could get finer grain at lengths, or use simple interpolation between two points
  27989. var lengthBefore = arcLengths[ i ];
  27990. var lengthAfter = arcLengths[ i + 1 ];
  27991. var segmentLength = lengthAfter - lengthBefore;
  27992. // determine where we are between the 'before' and 'after' points
  27993. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  27994. // add that fractional amount to t
  27995. var t = ( i + segmentFraction ) / ( il - 1 );
  27996. return t;
  27997. },
  27998. // Returns a unit vector tangent at t
  27999. // In case any sub curve does not implement its tangent derivation,
  28000. // 2 points a small delta apart will be used to find its gradient
  28001. // which seems to give a reasonable approximation
  28002. getTangent: function ( t, optionalTarget ) {
  28003. var delta = 0.0001;
  28004. var t1 = t - delta;
  28005. var t2 = t + delta;
  28006. // Capping in case of danger
  28007. if ( t1 < 0 ) { t1 = 0; }
  28008. if ( t2 > 1 ) { t2 = 1; }
  28009. var pt1 = this.getPoint( t1 );
  28010. var pt2 = this.getPoint( t2 );
  28011. var tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  28012. tangent.copy( pt2 ).sub( pt1 ).normalize();
  28013. return tangent;
  28014. },
  28015. getTangentAt: function ( u, optionalTarget ) {
  28016. var t = this.getUtoTmapping( u );
  28017. return this.getTangent( t, optionalTarget );
  28018. },
  28019. computeFrenetFrames: function ( segments, closed ) {
  28020. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  28021. var normal = new Vector3();
  28022. var tangents = [];
  28023. var normals = [];
  28024. var binormals = [];
  28025. var vec = new Vector3();
  28026. var mat = new Matrix4();
  28027. // compute the tangent vectors for each segment on the curve
  28028. for ( var i = 0; i <= segments; i ++ ) {
  28029. var u = i / segments;
  28030. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  28031. tangents[ i ].normalize();
  28032. }
  28033. // select an initial normal vector perpendicular to the first tangent vector,
  28034. // and in the direction of the minimum tangent xyz component
  28035. normals[ 0 ] = new Vector3();
  28036. binormals[ 0 ] = new Vector3();
  28037. var min = Number.MAX_VALUE;
  28038. var tx = Math.abs( tangents[ 0 ].x );
  28039. var ty = Math.abs( tangents[ 0 ].y );
  28040. var tz = Math.abs( tangents[ 0 ].z );
  28041. if ( tx <= min ) {
  28042. min = tx;
  28043. normal.set( 1, 0, 0 );
  28044. }
  28045. if ( ty <= min ) {
  28046. min = ty;
  28047. normal.set( 0, 1, 0 );
  28048. }
  28049. if ( tz <= min ) {
  28050. normal.set( 0, 0, 1 );
  28051. }
  28052. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  28053. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  28054. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  28055. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  28056. for ( var i$1 = 1; i$1 <= segments; i$1 ++ ) {
  28057. normals[ i$1 ] = normals[ i$1 - 1 ].clone();
  28058. binormals[ i$1 ] = binormals[ i$1 - 1 ].clone();
  28059. vec.crossVectors( tangents[ i$1 - 1 ], tangents[ i$1 ] );
  28060. if ( vec.length() > Number.EPSILON ) {
  28061. vec.normalize();
  28062. var theta = Math.acos( MathUtils.clamp( tangents[ i$1 - 1 ].dot( tangents[ i$1 ] ), - 1, 1 ) ); // clamp for floating pt errors
  28063. normals[ i$1 ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  28064. }
  28065. binormals[ i$1 ].crossVectors( tangents[ i$1 ], normals[ i$1 ] );
  28066. }
  28067. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  28068. if ( closed === true ) {
  28069. var theta$1 = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  28070. theta$1 /= segments;
  28071. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  28072. theta$1 = - theta$1;
  28073. }
  28074. for ( var i$2 = 1; i$2 <= segments; i$2 ++ ) {
  28075. // twist a little...
  28076. normals[ i$2 ].applyMatrix4( mat.makeRotationAxis( tangents[ i$2 ], theta$1 * i$2 ) );
  28077. binormals[ i$2 ].crossVectors( tangents[ i$2 ], normals[ i$2 ] );
  28078. }
  28079. }
  28080. return {
  28081. tangents: tangents,
  28082. normals: normals,
  28083. binormals: binormals
  28084. };
  28085. },
  28086. clone: function () {
  28087. return new this.constructor().copy( this );
  28088. },
  28089. copy: function ( source ) {
  28090. this.arcLengthDivisions = source.arcLengthDivisions;
  28091. return this;
  28092. },
  28093. toJSON: function () {
  28094. var data = {
  28095. metadata: {
  28096. version: 4.5,
  28097. type: 'Curve',
  28098. generator: 'Curve.toJSON'
  28099. }
  28100. };
  28101. data.arcLengthDivisions = this.arcLengthDivisions;
  28102. data.type = this.type;
  28103. return data;
  28104. },
  28105. fromJSON: function ( json ) {
  28106. this.arcLengthDivisions = json.arcLengthDivisions;
  28107. return this;
  28108. }
  28109. } );
  28110. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28111. Curve.call( this );
  28112. this.type = 'EllipseCurve';
  28113. this.aX = aX || 0;
  28114. this.aY = aY || 0;
  28115. this.xRadius = xRadius || 1;
  28116. this.yRadius = yRadius || 1;
  28117. this.aStartAngle = aStartAngle || 0;
  28118. this.aEndAngle = aEndAngle || 2 * Math.PI;
  28119. this.aClockwise = aClockwise || false;
  28120. this.aRotation = aRotation || 0;
  28121. }
  28122. EllipseCurve.prototype = Object.create( Curve.prototype );
  28123. EllipseCurve.prototype.constructor = EllipseCurve;
  28124. EllipseCurve.prototype.isEllipseCurve = true;
  28125. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28126. var point = optionalTarget || new Vector2();
  28127. var twoPi = Math.PI * 2;
  28128. var deltaAngle = this.aEndAngle - this.aStartAngle;
  28129. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  28130. // ensures that deltaAngle is 0 .. 2 PI
  28131. while ( deltaAngle < 0 ) { deltaAngle += twoPi; }
  28132. while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; }
  28133. if ( deltaAngle < Number.EPSILON ) {
  28134. if ( samePoints ) {
  28135. deltaAngle = 0;
  28136. } else {
  28137. deltaAngle = twoPi;
  28138. }
  28139. }
  28140. if ( this.aClockwise === true && ! samePoints ) {
  28141. if ( deltaAngle === twoPi ) {
  28142. deltaAngle = - twoPi;
  28143. } else {
  28144. deltaAngle = deltaAngle - twoPi;
  28145. }
  28146. }
  28147. var angle = this.aStartAngle + t * deltaAngle;
  28148. var x = this.aX + this.xRadius * Math.cos( angle );
  28149. var y = this.aY + this.yRadius * Math.sin( angle );
  28150. if ( this.aRotation !== 0 ) {
  28151. var cos = Math.cos( this.aRotation );
  28152. var sin = Math.sin( this.aRotation );
  28153. var tx = x - this.aX;
  28154. var ty = y - this.aY;
  28155. // Rotate the point about the center of the ellipse.
  28156. x = tx * cos - ty * sin + this.aX;
  28157. y = tx * sin + ty * cos + this.aY;
  28158. }
  28159. return point.set( x, y );
  28160. };
  28161. EllipseCurve.prototype.copy = function ( source ) {
  28162. Curve.prototype.copy.call( this, source );
  28163. this.aX = source.aX;
  28164. this.aY = source.aY;
  28165. this.xRadius = source.xRadius;
  28166. this.yRadius = source.yRadius;
  28167. this.aStartAngle = source.aStartAngle;
  28168. this.aEndAngle = source.aEndAngle;
  28169. this.aClockwise = source.aClockwise;
  28170. this.aRotation = source.aRotation;
  28171. return this;
  28172. };
  28173. EllipseCurve.prototype.toJSON = function () {
  28174. var data = Curve.prototype.toJSON.call( this );
  28175. data.aX = this.aX;
  28176. data.aY = this.aY;
  28177. data.xRadius = this.xRadius;
  28178. data.yRadius = this.yRadius;
  28179. data.aStartAngle = this.aStartAngle;
  28180. data.aEndAngle = this.aEndAngle;
  28181. data.aClockwise = this.aClockwise;
  28182. data.aRotation = this.aRotation;
  28183. return data;
  28184. };
  28185. EllipseCurve.prototype.fromJSON = function ( json ) {
  28186. Curve.prototype.fromJSON.call( this, json );
  28187. this.aX = json.aX;
  28188. this.aY = json.aY;
  28189. this.xRadius = json.xRadius;
  28190. this.yRadius = json.yRadius;
  28191. this.aStartAngle = json.aStartAngle;
  28192. this.aEndAngle = json.aEndAngle;
  28193. this.aClockwise = json.aClockwise;
  28194. this.aRotation = json.aRotation;
  28195. return this;
  28196. };
  28197. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28198. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28199. this.type = 'ArcCurve';
  28200. }
  28201. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  28202. ArcCurve.prototype.constructor = ArcCurve;
  28203. ArcCurve.prototype.isArcCurve = true;
  28204. /**
  28205. * Centripetal CatmullRom Curve - which is useful for avoiding
  28206. * cusps and self-intersections in non-uniform catmull rom curves.
  28207. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28208. *
  28209. * curve.type accepts centripetal(default), chordal and catmullrom
  28210. * curve.tension is used for catmullrom which defaults to 0.5
  28211. */
  28212. /*
  28213. Based on an optimized c++ solution in
  28214. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28215. - http://ideone.com/NoEbVM
  28216. This CubicPoly class could be used for reusing some variables and calculations,
  28217. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28218. which can be placed in CurveUtils.
  28219. */
  28220. function CubicPoly() {
  28221. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  28222. /*
  28223. * Compute coefficients for a cubic polynomial
  28224. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28225. * such that
  28226. * p(0) = x0, p(1) = x1
  28227. * and
  28228. * p'(0) = t0, p'(1) = t1.
  28229. */
  28230. function init( x0, x1, t0, t1 ) {
  28231. c0 = x0;
  28232. c1 = t0;
  28233. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  28234. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28235. }
  28236. return {
  28237. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  28238. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  28239. },
  28240. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  28241. // compute tangents when parameterized in [t1,t2]
  28242. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  28243. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  28244. // rescale tangents for parametrization in [0,1]
  28245. t1 *= dt1;
  28246. t2 *= dt1;
  28247. init( x1, x2, t1, t2 );
  28248. },
  28249. calc: function ( t ) {
  28250. var t2 = t * t;
  28251. var t3 = t2 * t;
  28252. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28253. }
  28254. };
  28255. }
  28256. //
  28257. var tmp = new Vector3();
  28258. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  28259. function CatmullRomCurve3( points, closed, curveType, tension ) {
  28260. Curve.call( this );
  28261. this.type = 'CatmullRomCurve3';
  28262. this.points = points || [];
  28263. this.closed = closed || false;
  28264. this.curveType = curveType || 'centripetal';
  28265. this.tension = ( tension !== undefined ) ? tension : 0.5;
  28266. }
  28267. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  28268. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28269. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  28270. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28271. var point = optionalTarget || new Vector3();
  28272. var points = this.points;
  28273. var l = points.length;
  28274. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  28275. var intPoint = Math.floor( p );
  28276. var weight = p - intPoint;
  28277. if ( this.closed ) {
  28278. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  28279. } else if ( weight === 0 && intPoint === l - 1 ) {
  28280. intPoint = l - 2;
  28281. weight = 1;
  28282. }
  28283. var p0, p1, p2, p3; // 4 points
  28284. if ( this.closed || intPoint > 0 ) {
  28285. p0 = points[ ( intPoint - 1 ) % l ];
  28286. } else {
  28287. // extrapolate first point
  28288. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  28289. p0 = tmp;
  28290. }
  28291. p1 = points[ intPoint % l ];
  28292. p2 = points[ ( intPoint + 1 ) % l ];
  28293. if ( this.closed || intPoint + 2 < l ) {
  28294. p3 = points[ ( intPoint + 2 ) % l ];
  28295. } else {
  28296. // extrapolate last point
  28297. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  28298. p3 = tmp;
  28299. }
  28300. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  28301. // init Centripetal / Chordal Catmull-Rom
  28302. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  28303. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  28304. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  28305. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  28306. // safety check for repeated points
  28307. if ( dt1 < 1e-4 ) { dt1 = 1.0; }
  28308. if ( dt0 < 1e-4 ) { dt0 = dt1; }
  28309. if ( dt2 < 1e-4 ) { dt2 = dt1; }
  28310. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  28311. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  28312. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  28313. } else if ( this.curveType === 'catmullrom' ) {
  28314. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  28315. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  28316. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  28317. }
  28318. point.set(
  28319. px.calc( weight ),
  28320. py.calc( weight ),
  28321. pz.calc( weight )
  28322. );
  28323. return point;
  28324. };
  28325. CatmullRomCurve3.prototype.copy = function ( source ) {
  28326. Curve.prototype.copy.call( this, source );
  28327. this.points = [];
  28328. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  28329. var point = source.points[ i ];
  28330. this.points.push( point.clone() );
  28331. }
  28332. this.closed = source.closed;
  28333. this.curveType = source.curveType;
  28334. this.tension = source.tension;
  28335. return this;
  28336. };
  28337. CatmullRomCurve3.prototype.toJSON = function () {
  28338. var data = Curve.prototype.toJSON.call( this );
  28339. data.points = [];
  28340. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  28341. var point = this.points[ i ];
  28342. data.points.push( point.toArray() );
  28343. }
  28344. data.closed = this.closed;
  28345. data.curveType = this.curveType;
  28346. data.tension = this.tension;
  28347. return data;
  28348. };
  28349. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  28350. Curve.prototype.fromJSON.call( this, json );
  28351. this.points = [];
  28352. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  28353. var point = json.points[ i ];
  28354. this.points.push( new Vector3().fromArray( point ) );
  28355. }
  28356. this.closed = json.closed;
  28357. this.curveType = json.curveType;
  28358. this.tension = json.tension;
  28359. return this;
  28360. };
  28361. /**
  28362. * Bezier Curves formulas obtained from
  28363. * http://en.wikipedia.org/wiki/Bézier_curve
  28364. */
  28365. function CatmullRom( t, p0, p1, p2, p3 ) {
  28366. var v0 = ( p2 - p0 ) * 0.5;
  28367. var v1 = ( p3 - p1 ) * 0.5;
  28368. var t2 = t * t;
  28369. var t3 = t * t2;
  28370. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  28371. }
  28372. //
  28373. function QuadraticBezierP0( t, p ) {
  28374. var k = 1 - t;
  28375. return k * k * p;
  28376. }
  28377. function QuadraticBezierP1( t, p ) {
  28378. return 2 * ( 1 - t ) * t * p;
  28379. }
  28380. function QuadraticBezierP2( t, p ) {
  28381. return t * t * p;
  28382. }
  28383. function QuadraticBezier( t, p0, p1, p2 ) {
  28384. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  28385. QuadraticBezierP2( t, p2 );
  28386. }
  28387. //
  28388. function CubicBezierP0( t, p ) {
  28389. var k = 1 - t;
  28390. return k * k * k * p;
  28391. }
  28392. function CubicBezierP1( t, p ) {
  28393. var k = 1 - t;
  28394. return 3 * k * k * t * p;
  28395. }
  28396. function CubicBezierP2( t, p ) {
  28397. return 3 * ( 1 - t ) * t * t * p;
  28398. }
  28399. function CubicBezierP3( t, p ) {
  28400. return t * t * t * p;
  28401. }
  28402. function CubicBezier( t, p0, p1, p2, p3 ) {
  28403. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  28404. CubicBezierP3( t, p3 );
  28405. }
  28406. function CubicBezierCurve( v0, v1, v2, v3 ) {
  28407. Curve.call( this );
  28408. this.type = 'CubicBezierCurve';
  28409. this.v0 = v0 || new Vector2();
  28410. this.v1 = v1 || new Vector2();
  28411. this.v2 = v2 || new Vector2();
  28412. this.v3 = v3 || new Vector2();
  28413. }
  28414. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  28415. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  28416. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  28417. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28418. var point = optionalTarget || new Vector2();
  28419. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  28420. point.set(
  28421. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  28422. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  28423. );
  28424. return point;
  28425. };
  28426. CubicBezierCurve.prototype.copy = function ( source ) {
  28427. Curve.prototype.copy.call( this, source );
  28428. this.v0.copy( source.v0 );
  28429. this.v1.copy( source.v1 );
  28430. this.v2.copy( source.v2 );
  28431. this.v3.copy( source.v3 );
  28432. return this;
  28433. };
  28434. CubicBezierCurve.prototype.toJSON = function () {
  28435. var data = Curve.prototype.toJSON.call( this );
  28436. data.v0 = this.v0.toArray();
  28437. data.v1 = this.v1.toArray();
  28438. data.v2 = this.v2.toArray();
  28439. data.v3 = this.v3.toArray();
  28440. return data;
  28441. };
  28442. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  28443. Curve.prototype.fromJSON.call( this, json );
  28444. this.v0.fromArray( json.v0 );
  28445. this.v1.fromArray( json.v1 );
  28446. this.v2.fromArray( json.v2 );
  28447. this.v3.fromArray( json.v3 );
  28448. return this;
  28449. };
  28450. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  28451. Curve.call( this );
  28452. this.type = 'CubicBezierCurve3';
  28453. this.v0 = v0 || new Vector3();
  28454. this.v1 = v1 || new Vector3();
  28455. this.v2 = v2 || new Vector3();
  28456. this.v3 = v3 || new Vector3();
  28457. }
  28458. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  28459. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  28460. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  28461. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28462. var point = optionalTarget || new Vector3();
  28463. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  28464. point.set(
  28465. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  28466. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  28467. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  28468. );
  28469. return point;
  28470. };
  28471. CubicBezierCurve3.prototype.copy = function ( source ) {
  28472. Curve.prototype.copy.call( this, source );
  28473. this.v0.copy( source.v0 );
  28474. this.v1.copy( source.v1 );
  28475. this.v2.copy( source.v2 );
  28476. this.v3.copy( source.v3 );
  28477. return this;
  28478. };
  28479. CubicBezierCurve3.prototype.toJSON = function () {
  28480. var data = Curve.prototype.toJSON.call( this );
  28481. data.v0 = this.v0.toArray();
  28482. data.v1 = this.v1.toArray();
  28483. data.v2 = this.v2.toArray();
  28484. data.v3 = this.v3.toArray();
  28485. return data;
  28486. };
  28487. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  28488. Curve.prototype.fromJSON.call( this, json );
  28489. this.v0.fromArray( json.v0 );
  28490. this.v1.fromArray( json.v1 );
  28491. this.v2.fromArray( json.v2 );
  28492. this.v3.fromArray( json.v3 );
  28493. return this;
  28494. };
  28495. function LineCurve( v1, v2 ) {
  28496. Curve.call( this );
  28497. this.type = 'LineCurve';
  28498. this.v1 = v1 || new Vector2();
  28499. this.v2 = v2 || new Vector2();
  28500. }
  28501. LineCurve.prototype = Object.create( Curve.prototype );
  28502. LineCurve.prototype.constructor = LineCurve;
  28503. LineCurve.prototype.isLineCurve = true;
  28504. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28505. var point = optionalTarget || new Vector2();
  28506. if ( t === 1 ) {
  28507. point.copy( this.v2 );
  28508. } else {
  28509. point.copy( this.v2 ).sub( this.v1 );
  28510. point.multiplyScalar( t ).add( this.v1 );
  28511. }
  28512. return point;
  28513. };
  28514. // Line curve is linear, so we can overwrite default getPointAt
  28515. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  28516. return this.getPoint( u, optionalTarget );
  28517. };
  28518. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  28519. var tangent = optionalTarget || new Vector2();
  28520. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  28521. return tangent;
  28522. };
  28523. LineCurve.prototype.copy = function ( source ) {
  28524. Curve.prototype.copy.call( this, source );
  28525. this.v1.copy( source.v1 );
  28526. this.v2.copy( source.v2 );
  28527. return this;
  28528. };
  28529. LineCurve.prototype.toJSON = function () {
  28530. var data = Curve.prototype.toJSON.call( this );
  28531. data.v1 = this.v1.toArray();
  28532. data.v2 = this.v2.toArray();
  28533. return data;
  28534. };
  28535. LineCurve.prototype.fromJSON = function ( json ) {
  28536. Curve.prototype.fromJSON.call( this, json );
  28537. this.v1.fromArray( json.v1 );
  28538. this.v2.fromArray( json.v2 );
  28539. return this;
  28540. };
  28541. function LineCurve3( v1, v2 ) {
  28542. Curve.call( this );
  28543. this.type = 'LineCurve3';
  28544. this.v1 = v1 || new Vector3();
  28545. this.v2 = v2 || new Vector3();
  28546. }
  28547. LineCurve3.prototype = Object.create( Curve.prototype );
  28548. LineCurve3.prototype.constructor = LineCurve3;
  28549. LineCurve3.prototype.isLineCurve3 = true;
  28550. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28551. var point = optionalTarget || new Vector3();
  28552. if ( t === 1 ) {
  28553. point.copy( this.v2 );
  28554. } else {
  28555. point.copy( this.v2 ).sub( this.v1 );
  28556. point.multiplyScalar( t ).add( this.v1 );
  28557. }
  28558. return point;
  28559. };
  28560. // Line curve is linear, so we can overwrite default getPointAt
  28561. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  28562. return this.getPoint( u, optionalTarget );
  28563. };
  28564. LineCurve3.prototype.copy = function ( source ) {
  28565. Curve.prototype.copy.call( this, source );
  28566. this.v1.copy( source.v1 );
  28567. this.v2.copy( source.v2 );
  28568. return this;
  28569. };
  28570. LineCurve3.prototype.toJSON = function () {
  28571. var data = Curve.prototype.toJSON.call( this );
  28572. data.v1 = this.v1.toArray();
  28573. data.v2 = this.v2.toArray();
  28574. return data;
  28575. };
  28576. LineCurve3.prototype.fromJSON = function ( json ) {
  28577. Curve.prototype.fromJSON.call( this, json );
  28578. this.v1.fromArray( json.v1 );
  28579. this.v2.fromArray( json.v2 );
  28580. return this;
  28581. };
  28582. function QuadraticBezierCurve( v0, v1, v2 ) {
  28583. Curve.call( this );
  28584. this.type = 'QuadraticBezierCurve';
  28585. this.v0 = v0 || new Vector2();
  28586. this.v1 = v1 || new Vector2();
  28587. this.v2 = v2 || new Vector2();
  28588. }
  28589. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  28590. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  28591. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  28592. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28593. var point = optionalTarget || new Vector2();
  28594. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  28595. point.set(
  28596. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  28597. QuadraticBezier( t, v0.y, v1.y, v2.y )
  28598. );
  28599. return point;
  28600. };
  28601. QuadraticBezierCurve.prototype.copy = function ( source ) {
  28602. Curve.prototype.copy.call( this, source );
  28603. this.v0.copy( source.v0 );
  28604. this.v1.copy( source.v1 );
  28605. this.v2.copy( source.v2 );
  28606. return this;
  28607. };
  28608. QuadraticBezierCurve.prototype.toJSON = function () {
  28609. var data = Curve.prototype.toJSON.call( this );
  28610. data.v0 = this.v0.toArray();
  28611. data.v1 = this.v1.toArray();
  28612. data.v2 = this.v2.toArray();
  28613. return data;
  28614. };
  28615. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  28616. Curve.prototype.fromJSON.call( this, json );
  28617. this.v0.fromArray( json.v0 );
  28618. this.v1.fromArray( json.v1 );
  28619. this.v2.fromArray( json.v2 );
  28620. return this;
  28621. };
  28622. function QuadraticBezierCurve3( v0, v1, v2 ) {
  28623. Curve.call( this );
  28624. this.type = 'QuadraticBezierCurve3';
  28625. this.v0 = v0 || new Vector3();
  28626. this.v1 = v1 || new Vector3();
  28627. this.v2 = v2 || new Vector3();
  28628. }
  28629. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  28630. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  28631. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  28632. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28633. var point = optionalTarget || new Vector3();
  28634. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  28635. point.set(
  28636. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  28637. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  28638. QuadraticBezier( t, v0.z, v1.z, v2.z )
  28639. );
  28640. return point;
  28641. };
  28642. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  28643. Curve.prototype.copy.call( this, source );
  28644. this.v0.copy( source.v0 );
  28645. this.v1.copy( source.v1 );
  28646. this.v2.copy( source.v2 );
  28647. return this;
  28648. };
  28649. QuadraticBezierCurve3.prototype.toJSON = function () {
  28650. var data = Curve.prototype.toJSON.call( this );
  28651. data.v0 = this.v0.toArray();
  28652. data.v1 = this.v1.toArray();
  28653. data.v2 = this.v2.toArray();
  28654. return data;
  28655. };
  28656. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  28657. Curve.prototype.fromJSON.call( this, json );
  28658. this.v0.fromArray( json.v0 );
  28659. this.v1.fromArray( json.v1 );
  28660. this.v2.fromArray( json.v2 );
  28661. return this;
  28662. };
  28663. function SplineCurve( points ) {
  28664. Curve.call( this );
  28665. this.type = 'SplineCurve';
  28666. this.points = points || [];
  28667. }
  28668. SplineCurve.prototype = Object.create( Curve.prototype );
  28669. SplineCurve.prototype.constructor = SplineCurve;
  28670. SplineCurve.prototype.isSplineCurve = true;
  28671. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28672. var point = optionalTarget || new Vector2();
  28673. var points = this.points;
  28674. var p = ( points.length - 1 ) * t;
  28675. var intPoint = Math.floor( p );
  28676. var weight = p - intPoint;
  28677. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  28678. var p1 = points[ intPoint ];
  28679. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  28680. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  28681. point.set(
  28682. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  28683. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  28684. );
  28685. return point;
  28686. };
  28687. SplineCurve.prototype.copy = function ( source ) {
  28688. Curve.prototype.copy.call( this, source );
  28689. this.points = [];
  28690. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  28691. var point = source.points[ i ];
  28692. this.points.push( point.clone() );
  28693. }
  28694. return this;
  28695. };
  28696. SplineCurve.prototype.toJSON = function () {
  28697. var data = Curve.prototype.toJSON.call( this );
  28698. data.points = [];
  28699. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  28700. var point = this.points[ i ];
  28701. data.points.push( point.toArray() );
  28702. }
  28703. return data;
  28704. };
  28705. SplineCurve.prototype.fromJSON = function ( json ) {
  28706. Curve.prototype.fromJSON.call( this, json );
  28707. this.points = [];
  28708. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  28709. var point = json.points[ i ];
  28710. this.points.push( new Vector2().fromArray( point ) );
  28711. }
  28712. return this;
  28713. };
  28714. var Curves = /*#__PURE__*/Object.freeze({
  28715. __proto__: null,
  28716. ArcCurve: ArcCurve,
  28717. CatmullRomCurve3: CatmullRomCurve3,
  28718. CubicBezierCurve: CubicBezierCurve,
  28719. CubicBezierCurve3: CubicBezierCurve3,
  28720. EllipseCurve: EllipseCurve,
  28721. LineCurve: LineCurve,
  28722. LineCurve3: LineCurve3,
  28723. QuadraticBezierCurve: QuadraticBezierCurve,
  28724. QuadraticBezierCurve3: QuadraticBezierCurve3,
  28725. SplineCurve: SplineCurve
  28726. });
  28727. /**************************************************************
  28728. * Curved Path - a curve path is simply a array of connected
  28729. * curves, but retains the api of a curve
  28730. **************************************************************/
  28731. function CurvePath() {
  28732. Curve.call( this );
  28733. this.type = 'CurvePath';
  28734. this.curves = [];
  28735. this.autoClose = false; // Automatically closes the path
  28736. }
  28737. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  28738. constructor: CurvePath,
  28739. add: function ( curve ) {
  28740. this.curves.push( curve );
  28741. },
  28742. closePath: function () {
  28743. // Add a line curve if start and end of lines are not connected
  28744. var startPoint = this.curves[ 0 ].getPoint( 0 );
  28745. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  28746. if ( ! startPoint.equals( endPoint ) ) {
  28747. this.curves.push( new LineCurve( endPoint, startPoint ) );
  28748. }
  28749. },
  28750. // To get accurate point with reference to
  28751. // entire path distance at time t,
  28752. // following has to be done:
  28753. // 1. Length of each sub path have to be known
  28754. // 2. Locate and identify type of curve
  28755. // 3. Get t for the curve
  28756. // 4. Return curve.getPointAt(t')
  28757. getPoint: function ( t ) {
  28758. var d = t * this.getLength();
  28759. var curveLengths = this.getCurveLengths();
  28760. var i = 0;
  28761. // To think about boundaries points.
  28762. while ( i < curveLengths.length ) {
  28763. if ( curveLengths[ i ] >= d ) {
  28764. var diff = curveLengths[ i ] - d;
  28765. var curve = this.curves[ i ];
  28766. var segmentLength = curve.getLength();
  28767. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  28768. return curve.getPointAt( u );
  28769. }
  28770. i ++;
  28771. }
  28772. return null;
  28773. // loop where sum != 0, sum > d , sum+1 <d
  28774. },
  28775. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  28776. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  28777. // getPoint() depends on getLength
  28778. getLength: function () {
  28779. var lens = this.getCurveLengths();
  28780. return lens[ lens.length - 1 ];
  28781. },
  28782. // cacheLengths must be recalculated.
  28783. updateArcLengths: function () {
  28784. this.needsUpdate = true;
  28785. this.cacheLengths = null;
  28786. this.getCurveLengths();
  28787. },
  28788. // Compute lengths and cache them
  28789. // We cannot overwrite getLengths() because UtoT mapping uses it.
  28790. getCurveLengths: function () {
  28791. // We use cache values if curves and cache array are same length
  28792. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  28793. return this.cacheLengths;
  28794. }
  28795. // Get length of sub-curve
  28796. // Push sums into cached array
  28797. var lengths = [];
  28798. var sums = 0;
  28799. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28800. sums += this.curves[ i ].getLength();
  28801. lengths.push( sums );
  28802. }
  28803. this.cacheLengths = lengths;
  28804. return lengths;
  28805. },
  28806. getSpacedPoints: function ( divisions ) {
  28807. if ( divisions === undefined ) { divisions = 40; }
  28808. var points = [];
  28809. for ( var i = 0; i <= divisions; i ++ ) {
  28810. points.push( this.getPoint( i / divisions ) );
  28811. }
  28812. if ( this.autoClose ) {
  28813. points.push( points[ 0 ] );
  28814. }
  28815. return points;
  28816. },
  28817. getPoints: function ( divisions ) {
  28818. divisions = divisions || 12;
  28819. var points = [];
  28820. var last;
  28821. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  28822. var curve = curves[ i ];
  28823. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  28824. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  28825. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  28826. : divisions;
  28827. var pts = curve.getPoints( resolution );
  28828. for ( var j = 0; j < pts.length; j ++ ) {
  28829. var point = pts[ j ];
  28830. if ( last && last.equals( point ) ) { continue; } // ensures no consecutive points are duplicates
  28831. points.push( point );
  28832. last = point;
  28833. }
  28834. }
  28835. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  28836. points.push( points[ 0 ] );
  28837. }
  28838. return points;
  28839. },
  28840. copy: function ( source ) {
  28841. Curve.prototype.copy.call( this, source );
  28842. this.curves = [];
  28843. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  28844. var curve = source.curves[ i ];
  28845. this.curves.push( curve.clone() );
  28846. }
  28847. this.autoClose = source.autoClose;
  28848. return this;
  28849. },
  28850. toJSON: function () {
  28851. var data = Curve.prototype.toJSON.call( this );
  28852. data.autoClose = this.autoClose;
  28853. data.curves = [];
  28854. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28855. var curve = this.curves[ i ];
  28856. data.curves.push( curve.toJSON() );
  28857. }
  28858. return data;
  28859. },
  28860. fromJSON: function ( json ) {
  28861. Curve.prototype.fromJSON.call( this, json );
  28862. this.autoClose = json.autoClose;
  28863. this.curves = [];
  28864. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  28865. var curve = json.curves[ i ];
  28866. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  28867. }
  28868. return this;
  28869. }
  28870. } );
  28871. function Path( points ) {
  28872. CurvePath.call( this );
  28873. this.type = 'Path';
  28874. this.currentPoint = new Vector2();
  28875. if ( points ) {
  28876. this.setFromPoints( points );
  28877. }
  28878. }
  28879. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  28880. constructor: Path,
  28881. setFromPoints: function ( points ) {
  28882. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  28883. for ( var i = 1, l = points.length; i < l; i ++ ) {
  28884. this.lineTo( points[ i ].x, points[ i ].y );
  28885. }
  28886. return this;
  28887. },
  28888. moveTo: function ( x, y ) {
  28889. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  28890. return this;
  28891. },
  28892. lineTo: function ( x, y ) {
  28893. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  28894. this.curves.push( curve );
  28895. this.currentPoint.set( x, y );
  28896. return this;
  28897. },
  28898. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  28899. var curve = new QuadraticBezierCurve(
  28900. this.currentPoint.clone(),
  28901. new Vector2( aCPx, aCPy ),
  28902. new Vector2( aX, aY )
  28903. );
  28904. this.curves.push( curve );
  28905. this.currentPoint.set( aX, aY );
  28906. return this;
  28907. },
  28908. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28909. var curve = new CubicBezierCurve(
  28910. this.currentPoint.clone(),
  28911. new Vector2( aCP1x, aCP1y ),
  28912. new Vector2( aCP2x, aCP2y ),
  28913. new Vector2( aX, aY )
  28914. );
  28915. this.curves.push( curve );
  28916. this.currentPoint.set( aX, aY );
  28917. return this;
  28918. },
  28919. splineThru: function ( pts /*Array of Vector*/ ) {
  28920. var npts = [ this.currentPoint.clone() ].concat( pts );
  28921. var curve = new SplineCurve( npts );
  28922. this.curves.push( curve );
  28923. this.currentPoint.copy( pts[ pts.length - 1 ] );
  28924. return this;
  28925. },
  28926. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28927. var x0 = this.currentPoint.x;
  28928. var y0 = this.currentPoint.y;
  28929. this.absarc( aX + x0, aY + y0, aRadius,
  28930. aStartAngle, aEndAngle, aClockwise );
  28931. return this;
  28932. },
  28933. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28934. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28935. return this;
  28936. },
  28937. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28938. var x0 = this.currentPoint.x;
  28939. var y0 = this.currentPoint.y;
  28940. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28941. return this;
  28942. },
  28943. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28944. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28945. if ( this.curves.length > 0 ) {
  28946. // if a previous curve is present, attempt to join
  28947. var firstPoint = curve.getPoint( 0 );
  28948. if ( ! firstPoint.equals( this.currentPoint ) ) {
  28949. this.lineTo( firstPoint.x, firstPoint.y );
  28950. }
  28951. }
  28952. this.curves.push( curve );
  28953. var lastPoint = curve.getPoint( 1 );
  28954. this.currentPoint.copy( lastPoint );
  28955. return this;
  28956. },
  28957. copy: function ( source ) {
  28958. CurvePath.prototype.copy.call( this, source );
  28959. this.currentPoint.copy( source.currentPoint );
  28960. return this;
  28961. },
  28962. toJSON: function () {
  28963. var data = CurvePath.prototype.toJSON.call( this );
  28964. data.currentPoint = this.currentPoint.toArray();
  28965. return data;
  28966. },
  28967. fromJSON: function ( json ) {
  28968. CurvePath.prototype.fromJSON.call( this, json );
  28969. this.currentPoint.fromArray( json.currentPoint );
  28970. return this;
  28971. }
  28972. } );
  28973. function Shape( points ) {
  28974. Path.call( this, points );
  28975. this.uuid = MathUtils.generateUUID();
  28976. this.type = 'Shape';
  28977. this.holes = [];
  28978. }
  28979. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  28980. constructor: Shape,
  28981. getPointsHoles: function ( divisions ) {
  28982. var holesPts = [];
  28983. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  28984. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  28985. }
  28986. return holesPts;
  28987. },
  28988. // get points of shape and holes (keypoints based on segments parameter)
  28989. extractPoints: function ( divisions ) {
  28990. return {
  28991. shape: this.getPoints( divisions ),
  28992. holes: this.getPointsHoles( divisions )
  28993. };
  28994. },
  28995. copy: function ( source ) {
  28996. Path.prototype.copy.call( this, source );
  28997. this.holes = [];
  28998. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  28999. var hole = source.holes[ i ];
  29000. this.holes.push( hole.clone() );
  29001. }
  29002. return this;
  29003. },
  29004. toJSON: function () {
  29005. var data = Path.prototype.toJSON.call( this );
  29006. data.uuid = this.uuid;
  29007. data.holes = [];
  29008. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  29009. var hole = this.holes[ i ];
  29010. data.holes.push( hole.toJSON() );
  29011. }
  29012. return data;
  29013. },
  29014. fromJSON: function ( json ) {
  29015. Path.prototype.fromJSON.call( this, json );
  29016. this.uuid = json.uuid;
  29017. this.holes = [];
  29018. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  29019. var hole = json.holes[ i ];
  29020. this.holes.push( new Path().fromJSON( hole ) );
  29021. }
  29022. return this;
  29023. }
  29024. } );
  29025. function Light( color, intensity ) {
  29026. Object3D.call( this );
  29027. this.type = 'Light';
  29028. this.color = new Color( color );
  29029. this.intensity = intensity !== undefined ? intensity : 1;
  29030. this.receiveShadow = undefined;
  29031. }
  29032. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  29033. constructor: Light,
  29034. isLight: true,
  29035. copy: function ( source ) {
  29036. Object3D.prototype.copy.call( this, source );
  29037. this.color.copy( source.color );
  29038. this.intensity = source.intensity;
  29039. return this;
  29040. },
  29041. toJSON: function ( meta ) {
  29042. var data = Object3D.prototype.toJSON.call( this, meta );
  29043. data.object.color = this.color.getHex();
  29044. data.object.intensity = this.intensity;
  29045. if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); }
  29046. if ( this.distance !== undefined ) { data.object.distance = this.distance; }
  29047. if ( this.angle !== undefined ) { data.object.angle = this.angle; }
  29048. if ( this.decay !== undefined ) { data.object.decay = this.decay; }
  29049. if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; }
  29050. if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); }
  29051. return data;
  29052. }
  29053. } );
  29054. function HemisphereLight( skyColor, groundColor, intensity ) {
  29055. Light.call( this, skyColor, intensity );
  29056. this.type = 'HemisphereLight';
  29057. this.castShadow = undefined;
  29058. this.position.copy( Object3D.DefaultUp );
  29059. this.updateMatrix();
  29060. this.groundColor = new Color( groundColor );
  29061. }
  29062. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29063. constructor: HemisphereLight,
  29064. isHemisphereLight: true,
  29065. copy: function ( source ) {
  29066. Light.prototype.copy.call( this, source );
  29067. this.groundColor.copy( source.groundColor );
  29068. return this;
  29069. }
  29070. } );
  29071. function LightShadow( camera ) {
  29072. this.camera = camera;
  29073. this.bias = 0;
  29074. this.normalBias = 0;
  29075. this.radius = 1;
  29076. this.mapSize = new Vector2( 512, 512 );
  29077. this.map = null;
  29078. this.mapPass = null;
  29079. this.matrix = new Matrix4();
  29080. this.autoUpdate = true;
  29081. this.needsUpdate = false;
  29082. this._frustum = new Frustum();
  29083. this._frameExtents = new Vector2( 1, 1 );
  29084. this._viewportCount = 1;
  29085. this._viewports = [
  29086. new Vector4( 0, 0, 1, 1 )
  29087. ];
  29088. }
  29089. Object.assign( LightShadow.prototype, {
  29090. _projScreenMatrix: new Matrix4(),
  29091. _lightPositionWorld: new Vector3(),
  29092. _lookTarget: new Vector3(),
  29093. getViewportCount: function () {
  29094. return this._viewportCount;
  29095. },
  29096. getFrustum: function () {
  29097. return this._frustum;
  29098. },
  29099. updateMatrices: function ( light ) {
  29100. var shadowCamera = this.camera,
  29101. shadowMatrix = this.matrix,
  29102. projScreenMatrix = this._projScreenMatrix,
  29103. lookTarget = this._lookTarget,
  29104. lightPositionWorld = this._lightPositionWorld;
  29105. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  29106. shadowCamera.position.copy( lightPositionWorld );
  29107. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  29108. shadowCamera.lookAt( lookTarget );
  29109. shadowCamera.updateMatrixWorld();
  29110. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  29111. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  29112. shadowMatrix.set(
  29113. 0.5, 0.0, 0.0, 0.5,
  29114. 0.0, 0.5, 0.0, 0.5,
  29115. 0.0, 0.0, 0.5, 0.5,
  29116. 0.0, 0.0, 0.0, 1.0
  29117. );
  29118. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  29119. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  29120. },
  29121. getViewport: function ( viewportIndex ) {
  29122. return this._viewports[ viewportIndex ];
  29123. },
  29124. getFrameExtents: function () {
  29125. return this._frameExtents;
  29126. },
  29127. copy: function ( source ) {
  29128. this.camera = source.camera.clone();
  29129. this.bias = source.bias;
  29130. this.radius = source.radius;
  29131. this.mapSize.copy( source.mapSize );
  29132. return this;
  29133. },
  29134. clone: function () {
  29135. return new this.constructor().copy( this );
  29136. },
  29137. toJSON: function () {
  29138. var object = {};
  29139. if ( this.bias !== 0 ) { object.bias = this.bias; }
  29140. if ( this.normalBias !== 0 ) { object.normalBias = this.normalBias; }
  29141. if ( this.radius !== 1 ) { object.radius = this.radius; }
  29142. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); }
  29143. object.camera = this.camera.toJSON( false ).object;
  29144. delete object.camera.matrix;
  29145. return object;
  29146. }
  29147. } );
  29148. function SpotLightShadow() {
  29149. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  29150. }
  29151. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29152. constructor: SpotLightShadow,
  29153. isSpotLightShadow: true,
  29154. updateMatrices: function ( light ) {
  29155. var camera = this.camera;
  29156. var fov = MathUtils.RAD2DEG * 2 * light.angle;
  29157. var aspect = this.mapSize.width / this.mapSize.height;
  29158. var far = light.distance || camera.far;
  29159. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  29160. camera.fov = fov;
  29161. camera.aspect = aspect;
  29162. camera.far = far;
  29163. camera.updateProjectionMatrix();
  29164. }
  29165. LightShadow.prototype.updateMatrices.call( this, light );
  29166. }
  29167. } );
  29168. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  29169. Light.call( this, color, intensity );
  29170. this.type = 'SpotLight';
  29171. this.position.copy( Object3D.DefaultUp );
  29172. this.updateMatrix();
  29173. this.target = new Object3D();
  29174. Object.defineProperty( this, 'power', {
  29175. get: function () {
  29176. // intensity = power per solid angle.
  29177. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29178. return this.intensity * Math.PI;
  29179. },
  29180. set: function ( power ) {
  29181. // intensity = power per solid angle.
  29182. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29183. this.intensity = power / Math.PI;
  29184. }
  29185. } );
  29186. this.distance = ( distance !== undefined ) ? distance : 0;
  29187. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  29188. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  29189. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  29190. this.shadow = new SpotLightShadow();
  29191. }
  29192. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29193. constructor: SpotLight,
  29194. isSpotLight: true,
  29195. copy: function ( source ) {
  29196. Light.prototype.copy.call( this, source );
  29197. this.distance = source.distance;
  29198. this.angle = source.angle;
  29199. this.penumbra = source.penumbra;
  29200. this.decay = source.decay;
  29201. this.target = source.target.clone();
  29202. this.shadow = source.shadow.clone();
  29203. return this;
  29204. }
  29205. } );
  29206. function PointLightShadow() {
  29207. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  29208. this._frameExtents = new Vector2( 4, 2 );
  29209. this._viewportCount = 6;
  29210. this._viewports = [
  29211. // These viewports map a cube-map onto a 2D texture with the
  29212. // following orientation:
  29213. //
  29214. // xzXZ
  29215. // y Y
  29216. //
  29217. // X - Positive x direction
  29218. // x - Negative x direction
  29219. // Y - Positive y direction
  29220. // y - Negative y direction
  29221. // Z - Positive z direction
  29222. // z - Negative z direction
  29223. // positive X
  29224. new Vector4( 2, 1, 1, 1 ),
  29225. // negative X
  29226. new Vector4( 0, 1, 1, 1 ),
  29227. // positive Z
  29228. new Vector4( 3, 1, 1, 1 ),
  29229. // negative Z
  29230. new Vector4( 1, 1, 1, 1 ),
  29231. // positive Y
  29232. new Vector4( 3, 0, 1, 1 ),
  29233. // negative Y
  29234. new Vector4( 1, 0, 1, 1 )
  29235. ];
  29236. this._cubeDirections = [
  29237. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  29238. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  29239. ];
  29240. this._cubeUps = [
  29241. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  29242. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  29243. ];
  29244. }
  29245. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29246. constructor: PointLightShadow,
  29247. isPointLightShadow: true,
  29248. updateMatrices: function ( light, viewportIndex ) {
  29249. if ( viewportIndex === undefined ) { viewportIndex = 0; }
  29250. var camera = this.camera,
  29251. shadowMatrix = this.matrix,
  29252. lightPositionWorld = this._lightPositionWorld,
  29253. lookTarget = this._lookTarget,
  29254. projScreenMatrix = this._projScreenMatrix;
  29255. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  29256. camera.position.copy( lightPositionWorld );
  29257. lookTarget.copy( camera.position );
  29258. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  29259. camera.up.copy( this._cubeUps[ viewportIndex ] );
  29260. camera.lookAt( lookTarget );
  29261. camera.updateMatrixWorld();
  29262. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  29263. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  29264. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  29265. }
  29266. } );
  29267. function PointLight( color, intensity, distance, decay ) {
  29268. Light.call( this, color, intensity );
  29269. this.type = 'PointLight';
  29270. Object.defineProperty( this, 'power', {
  29271. get: function () {
  29272. // intensity = power per solid angle.
  29273. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29274. return this.intensity * 4 * Math.PI;
  29275. },
  29276. set: function ( power ) {
  29277. // intensity = power per solid angle.
  29278. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29279. this.intensity = power / ( 4 * Math.PI );
  29280. }
  29281. } );
  29282. this.distance = ( distance !== undefined ) ? distance : 0;
  29283. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  29284. this.shadow = new PointLightShadow();
  29285. }
  29286. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29287. constructor: PointLight,
  29288. isPointLight: true,
  29289. copy: function ( source ) {
  29290. Light.prototype.copy.call( this, source );
  29291. this.distance = source.distance;
  29292. this.decay = source.decay;
  29293. this.shadow = source.shadow.clone();
  29294. return this;
  29295. }
  29296. } );
  29297. function OrthographicCamera( left, right, top, bottom, near, far ) {
  29298. Camera.call( this );
  29299. this.type = 'OrthographicCamera';
  29300. this.zoom = 1;
  29301. this.view = null;
  29302. this.left = ( left !== undefined ) ? left : - 1;
  29303. this.right = ( right !== undefined ) ? right : 1;
  29304. this.top = ( top !== undefined ) ? top : 1;
  29305. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  29306. this.near = ( near !== undefined ) ? near : 0.1;
  29307. this.far = ( far !== undefined ) ? far : 2000;
  29308. this.updateProjectionMatrix();
  29309. }
  29310. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  29311. constructor: OrthographicCamera,
  29312. isOrthographicCamera: true,
  29313. copy: function ( source, recursive ) {
  29314. Camera.prototype.copy.call( this, source, recursive );
  29315. this.left = source.left;
  29316. this.right = source.right;
  29317. this.top = source.top;
  29318. this.bottom = source.bottom;
  29319. this.near = source.near;
  29320. this.far = source.far;
  29321. this.zoom = source.zoom;
  29322. this.view = source.view === null ? null : Object.assign( {}, source.view );
  29323. return this;
  29324. },
  29325. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  29326. if ( this.view === null ) {
  29327. this.view = {
  29328. enabled: true,
  29329. fullWidth: 1,
  29330. fullHeight: 1,
  29331. offsetX: 0,
  29332. offsetY: 0,
  29333. width: 1,
  29334. height: 1
  29335. };
  29336. }
  29337. this.view.enabled = true;
  29338. this.view.fullWidth = fullWidth;
  29339. this.view.fullHeight = fullHeight;
  29340. this.view.offsetX = x;
  29341. this.view.offsetY = y;
  29342. this.view.width = width;
  29343. this.view.height = height;
  29344. this.updateProjectionMatrix();
  29345. },
  29346. clearViewOffset: function () {
  29347. if ( this.view !== null ) {
  29348. this.view.enabled = false;
  29349. }
  29350. this.updateProjectionMatrix();
  29351. },
  29352. updateProjectionMatrix: function () {
  29353. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  29354. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  29355. var cx = ( this.right + this.left ) / 2;
  29356. var cy = ( this.top + this.bottom ) / 2;
  29357. var left = cx - dx;
  29358. var right = cx + dx;
  29359. var top = cy + dy;
  29360. var bottom = cy - dy;
  29361. if ( this.view !== null && this.view.enabled ) {
  29362. var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  29363. var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  29364. left += scaleW * this.view.offsetX;
  29365. right = left + scaleW * this.view.width;
  29366. top -= scaleH * this.view.offsetY;
  29367. bottom = top - scaleH * this.view.height;
  29368. }
  29369. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  29370. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  29371. },
  29372. toJSON: function ( meta ) {
  29373. var data = Object3D.prototype.toJSON.call( this, meta );
  29374. data.object.zoom = this.zoom;
  29375. data.object.left = this.left;
  29376. data.object.right = this.right;
  29377. data.object.top = this.top;
  29378. data.object.bottom = this.bottom;
  29379. data.object.near = this.near;
  29380. data.object.far = this.far;
  29381. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  29382. return data;
  29383. }
  29384. } );
  29385. function DirectionalLightShadow() {
  29386. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  29387. }
  29388. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29389. constructor: DirectionalLightShadow,
  29390. isDirectionalLightShadow: true,
  29391. updateMatrices: function ( light ) {
  29392. LightShadow.prototype.updateMatrices.call( this, light );
  29393. }
  29394. } );
  29395. function DirectionalLight( color, intensity ) {
  29396. Light.call( this, color, intensity );
  29397. this.type = 'DirectionalLight';
  29398. this.position.copy( Object3D.DefaultUp );
  29399. this.updateMatrix();
  29400. this.target = new Object3D();
  29401. this.shadow = new DirectionalLightShadow();
  29402. }
  29403. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29404. constructor: DirectionalLight,
  29405. isDirectionalLight: true,
  29406. copy: function ( source ) {
  29407. Light.prototype.copy.call( this, source );
  29408. this.target = source.target.clone();
  29409. this.shadow = source.shadow.clone();
  29410. return this;
  29411. }
  29412. } );
  29413. function AmbientLight( color, intensity ) {
  29414. Light.call( this, color, intensity );
  29415. this.type = 'AmbientLight';
  29416. this.castShadow = undefined;
  29417. }
  29418. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29419. constructor: AmbientLight,
  29420. isAmbientLight: true
  29421. } );
  29422. function RectAreaLight( color, intensity, width, height ) {
  29423. Light.call( this, color, intensity );
  29424. this.type = 'RectAreaLight';
  29425. this.width = ( width !== undefined ) ? width : 10;
  29426. this.height = ( height !== undefined ) ? height : 10;
  29427. }
  29428. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29429. constructor: RectAreaLight,
  29430. isRectAreaLight: true,
  29431. copy: function ( source ) {
  29432. Light.prototype.copy.call( this, source );
  29433. this.width = source.width;
  29434. this.height = source.height;
  29435. return this;
  29436. },
  29437. toJSON: function ( meta ) {
  29438. var data = Light.prototype.toJSON.call( this, meta );
  29439. data.object.width = this.width;
  29440. data.object.height = this.height;
  29441. return data;
  29442. }
  29443. } );
  29444. /**
  29445. * Primary reference:
  29446. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29447. *
  29448. * Secondary reference:
  29449. * https://www.ppsloan.org/publications/StupidSH36.pdf
  29450. */
  29451. // 3-band SH defined by 9 coefficients
  29452. function SphericalHarmonics3() {
  29453. this.coefficients = [];
  29454. for ( var i = 0; i < 9; i ++ ) {
  29455. this.coefficients.push( new Vector3() );
  29456. }
  29457. }
  29458. Object.assign( SphericalHarmonics3.prototype, {
  29459. isSphericalHarmonics3: true,
  29460. set: function ( coefficients ) {
  29461. for ( var i = 0; i < 9; i ++ ) {
  29462. this.coefficients[ i ].copy( coefficients[ i ] );
  29463. }
  29464. return this;
  29465. },
  29466. zero: function () {
  29467. for ( var i = 0; i < 9; i ++ ) {
  29468. this.coefficients[ i ].set( 0, 0, 0 );
  29469. }
  29470. return this;
  29471. },
  29472. // get the radiance in the direction of the normal
  29473. // target is a Vector3
  29474. getAt: function ( normal, target ) {
  29475. // normal is assumed to be unit length
  29476. var x = normal.x, y = normal.y, z = normal.z;
  29477. var coeff = this.coefficients;
  29478. // band 0
  29479. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  29480. // band 1
  29481. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  29482. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  29483. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  29484. // band 2
  29485. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  29486. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  29487. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  29488. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  29489. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  29490. return target;
  29491. },
  29492. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  29493. // target is a Vector3
  29494. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29495. getIrradianceAt: function ( normal, target ) {
  29496. // normal is assumed to be unit length
  29497. var x = normal.x, y = normal.y, z = normal.z;
  29498. var coeff = this.coefficients;
  29499. // band 0
  29500. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  29501. // band 1
  29502. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  29503. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  29504. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  29505. // band 2
  29506. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  29507. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  29508. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  29509. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  29510. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  29511. return target;
  29512. },
  29513. add: function ( sh ) {
  29514. for ( var i = 0; i < 9; i ++ ) {
  29515. this.coefficients[ i ].add( sh.coefficients[ i ] );
  29516. }
  29517. return this;
  29518. },
  29519. addScaledSH: function ( sh, s ) {
  29520. for ( var i = 0; i < 9; i ++ ) {
  29521. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  29522. }
  29523. return this;
  29524. },
  29525. scale: function ( s ) {
  29526. for ( var i = 0; i < 9; i ++ ) {
  29527. this.coefficients[ i ].multiplyScalar( s );
  29528. }
  29529. return this;
  29530. },
  29531. lerp: function ( sh, alpha ) {
  29532. for ( var i = 0; i < 9; i ++ ) {
  29533. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  29534. }
  29535. return this;
  29536. },
  29537. equals: function ( sh ) {
  29538. for ( var i = 0; i < 9; i ++ ) {
  29539. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  29540. return false;
  29541. }
  29542. }
  29543. return true;
  29544. },
  29545. copy: function ( sh ) {
  29546. return this.set( sh.coefficients );
  29547. },
  29548. clone: function () {
  29549. return new this.constructor().copy( this );
  29550. },
  29551. fromArray: function ( array, offset ) {
  29552. if ( offset === undefined ) { offset = 0; }
  29553. var coefficients = this.coefficients;
  29554. for ( var i = 0; i < 9; i ++ ) {
  29555. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  29556. }
  29557. return this;
  29558. },
  29559. toArray: function ( array, offset ) {
  29560. if ( array === undefined ) { array = []; }
  29561. if ( offset === undefined ) { offset = 0; }
  29562. var coefficients = this.coefficients;
  29563. for ( var i = 0; i < 9; i ++ ) {
  29564. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  29565. }
  29566. return array;
  29567. }
  29568. } );
  29569. Object.assign( SphericalHarmonics3, {
  29570. // evaluate the basis functions
  29571. // shBasis is an Array[ 9 ]
  29572. getBasisAt: function ( normal, shBasis ) {
  29573. // normal is assumed to be unit length
  29574. var x = normal.x, y = normal.y, z = normal.z;
  29575. // band 0
  29576. shBasis[ 0 ] = 0.282095;
  29577. // band 1
  29578. shBasis[ 1 ] = 0.488603 * y;
  29579. shBasis[ 2 ] = 0.488603 * z;
  29580. shBasis[ 3 ] = 0.488603 * x;
  29581. // band 2
  29582. shBasis[ 4 ] = 1.092548 * x * y;
  29583. shBasis[ 5 ] = 1.092548 * y * z;
  29584. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  29585. shBasis[ 7 ] = 1.092548 * x * z;
  29586. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  29587. }
  29588. } );
  29589. function LightProbe( sh, intensity ) {
  29590. Light.call( this, undefined, intensity );
  29591. this.type = 'LightProbe';
  29592. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  29593. }
  29594. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  29595. constructor: LightProbe,
  29596. isLightProbe: true,
  29597. copy: function ( source ) {
  29598. Light.prototype.copy.call( this, source );
  29599. this.sh.copy( source.sh );
  29600. return this;
  29601. },
  29602. fromJSON: function ( json ) {
  29603. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  29604. this.sh.fromArray( json.sh );
  29605. return this;
  29606. },
  29607. toJSON: function ( meta ) {
  29608. var data = Light.prototype.toJSON.call( this, meta );
  29609. data.object.sh = this.sh.toArray();
  29610. return data;
  29611. }
  29612. } );
  29613. function MaterialLoader( manager ) {
  29614. Loader.call( this, manager );
  29615. this.textures = {};
  29616. }
  29617. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29618. constructor: MaterialLoader,
  29619. load: function ( url, onLoad, onProgress, onError ) {
  29620. var scope = this;
  29621. var loader = new FileLoader( scope.manager );
  29622. loader.setPath( scope.path );
  29623. loader.setRequestHeader( scope.requestHeader );
  29624. loader.load( url, function ( text ) {
  29625. try {
  29626. onLoad( scope.parse( JSON.parse( text ) ) );
  29627. } catch ( e ) {
  29628. if ( onError ) {
  29629. onError( e );
  29630. } else {
  29631. console.error( e );
  29632. }
  29633. scope.manager.itemError( url );
  29634. }
  29635. }, onProgress, onError );
  29636. },
  29637. parse: function ( json ) {
  29638. var textures = this.textures;
  29639. function getTexture( name ) {
  29640. if ( textures[ name ] === undefined ) {
  29641. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  29642. }
  29643. return textures[ name ];
  29644. }
  29645. var material = new Materials[ json.type ]();
  29646. if ( json.uuid !== undefined ) { material.uuid = json.uuid; }
  29647. if ( json.name !== undefined ) { material.name = json.name; }
  29648. if ( json.color !== undefined ) { material.color.setHex( json.color ); }
  29649. if ( json.roughness !== undefined ) { material.roughness = json.roughness; }
  29650. if ( json.metalness !== undefined ) { material.metalness = json.metalness; }
  29651. if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); }
  29652. if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); }
  29653. if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); }
  29654. if ( json.shininess !== undefined ) { material.shininess = json.shininess; }
  29655. if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; }
  29656. if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; }
  29657. if ( json.fog !== undefined ) { material.fog = json.fog; }
  29658. if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; }
  29659. if ( json.blending !== undefined ) { material.blending = json.blending; }
  29660. if ( json.combine !== undefined ) { material.combine = json.combine; }
  29661. if ( json.side !== undefined ) { material.side = json.side; }
  29662. if ( json.opacity !== undefined ) { material.opacity = json.opacity; }
  29663. if ( json.transparent !== undefined ) { material.transparent = json.transparent; }
  29664. if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; }
  29665. if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; }
  29666. if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; }
  29667. if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; }
  29668. if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; }
  29669. if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; }
  29670. if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; }
  29671. if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; }
  29672. if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; }
  29673. if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; }
  29674. if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; }
  29675. if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; }
  29676. if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; }
  29677. if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; }
  29678. if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; }
  29679. if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; }
  29680. if ( json.rotation !== undefined ) { material.rotation = json.rotation; }
  29681. if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; }
  29682. if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; }
  29683. if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; }
  29684. if ( json.scale !== undefined ) { material.scale = json.scale; }
  29685. if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; }
  29686. if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; }
  29687. if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; }
  29688. if ( json.skinning !== undefined ) { material.skinning = json.skinning; }
  29689. if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; }
  29690. if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; }
  29691. if ( json.dithering !== undefined ) { material.dithering = json.dithering; }
  29692. if ( json.vertexTangents !== undefined ) { material.vertexTangents = json.vertexTangents; }
  29693. if ( json.visible !== undefined ) { material.visible = json.visible; }
  29694. if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; }
  29695. if ( json.userData !== undefined ) { material.userData = json.userData; }
  29696. if ( json.vertexColors !== undefined ) {
  29697. if ( typeof json.vertexColors === 'number' ) {
  29698. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  29699. } else {
  29700. material.vertexColors = json.vertexColors;
  29701. }
  29702. }
  29703. // Shader Material
  29704. if ( json.uniforms !== undefined ) {
  29705. for ( var name in json.uniforms ) {
  29706. var uniform = json.uniforms[ name ];
  29707. material.uniforms[ name ] = {};
  29708. switch ( uniform.type ) {
  29709. case 't':
  29710. material.uniforms[ name ].value = getTexture( uniform.value );
  29711. break;
  29712. case 'c':
  29713. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  29714. break;
  29715. case 'v2':
  29716. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  29717. break;
  29718. case 'v3':
  29719. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  29720. break;
  29721. case 'v4':
  29722. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  29723. break;
  29724. case 'm3':
  29725. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  29726. case 'm4':
  29727. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  29728. break;
  29729. default:
  29730. material.uniforms[ name ].value = uniform.value;
  29731. }
  29732. }
  29733. }
  29734. if ( json.defines !== undefined ) { material.defines = json.defines; }
  29735. if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; }
  29736. if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; }
  29737. if ( json.extensions !== undefined ) {
  29738. for ( var key in json.extensions ) {
  29739. material.extensions[ key ] = json.extensions[ key ];
  29740. }
  29741. }
  29742. // Deprecated
  29743. if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading
  29744. // for PointsMaterial
  29745. if ( json.size !== undefined ) { material.size = json.size; }
  29746. if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; }
  29747. // maps
  29748. if ( json.map !== undefined ) { material.map = getTexture( json.map ); }
  29749. if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); }
  29750. if ( json.alphaMap !== undefined ) { material.alphaMap = getTexture( json.alphaMap ); }
  29751. if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); }
  29752. if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; }
  29753. if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); }
  29754. if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; }
  29755. if ( json.normalScale !== undefined ) {
  29756. var normalScale = json.normalScale;
  29757. if ( Array.isArray( normalScale ) === false ) {
  29758. // Blender exporter used to export a scalar. See #7459
  29759. normalScale = [ normalScale, normalScale ];
  29760. }
  29761. material.normalScale = new Vector2().fromArray( normalScale );
  29762. }
  29763. if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); }
  29764. if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; }
  29765. if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; }
  29766. if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); }
  29767. if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); }
  29768. if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); }
  29769. if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; }
  29770. if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); }
  29771. if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); }
  29772. if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; }
  29773. if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; }
  29774. if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; }
  29775. if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); }
  29776. if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; }
  29777. if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); }
  29778. if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; }
  29779. if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); }
  29780. if ( json.clearcoatMap !== undefined ) { material.clearcoatMap = getTexture( json.clearcoatMap ); }
  29781. if ( json.clearcoatRoughnessMap !== undefined ) { material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); }
  29782. if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); }
  29783. if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); }
  29784. if ( json.transmission !== undefined ) { material.transmission = json.transmission; }
  29785. if ( json.transmissionMap !== undefined ) { material.transmissionMap = getTexture( json.transmissionMap ); }
  29786. return material;
  29787. },
  29788. setTextures: function ( value ) {
  29789. this.textures = value;
  29790. return this;
  29791. }
  29792. } );
  29793. var LoaderUtils = {
  29794. decodeText: function ( array ) {
  29795. if ( typeof TextDecoder !== 'undefined' ) {
  29796. return new TextDecoder().decode( array );
  29797. }
  29798. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  29799. // throws a "maximum call stack size exceeded" error for large arrays.
  29800. var s = '';
  29801. for ( var i = 0, il = array.length; i < il; i ++ ) {
  29802. // Implicitly assumes little-endian.
  29803. s += String.fromCharCode( array[ i ] );
  29804. }
  29805. try {
  29806. // merges multi-byte utf-8 characters.
  29807. return decodeURIComponent( escape( s ) );
  29808. } catch ( e ) { // see #16358
  29809. return s;
  29810. }
  29811. },
  29812. extractUrlBase: function ( url ) {
  29813. var index = url.lastIndexOf( '/' );
  29814. if ( index === - 1 ) { return './'; }
  29815. return url.substr( 0, index + 1 );
  29816. }
  29817. };
  29818. function InstancedBufferGeometry() {
  29819. BufferGeometry.call( this );
  29820. this.type = 'InstancedBufferGeometry';
  29821. this.instanceCount = Infinity;
  29822. }
  29823. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29824. constructor: InstancedBufferGeometry,
  29825. isInstancedBufferGeometry: true,
  29826. copy: function ( source ) {
  29827. BufferGeometry.prototype.copy.call( this, source );
  29828. this.instanceCount = source.instanceCount;
  29829. return this;
  29830. },
  29831. clone: function () {
  29832. return new this.constructor().copy( this );
  29833. },
  29834. toJSON: function () {
  29835. var data = BufferGeometry.prototype.toJSON.call( this );
  29836. data.instanceCount = this.instanceCount;
  29837. data.isInstancedBufferGeometry = true;
  29838. return data;
  29839. }
  29840. } );
  29841. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  29842. if ( typeof ( normalized ) === 'number' ) {
  29843. meshPerAttribute = normalized;
  29844. normalized = false;
  29845. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  29846. }
  29847. BufferAttribute.call( this, array, itemSize, normalized );
  29848. this.meshPerAttribute = meshPerAttribute || 1;
  29849. }
  29850. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29851. constructor: InstancedBufferAttribute,
  29852. isInstancedBufferAttribute: true,
  29853. copy: function ( source ) {
  29854. BufferAttribute.prototype.copy.call( this, source );
  29855. this.meshPerAttribute = source.meshPerAttribute;
  29856. return this;
  29857. },
  29858. toJSON: function () {
  29859. var data = BufferAttribute.prototype.toJSON.call( this );
  29860. data.meshPerAttribute = this.meshPerAttribute;
  29861. data.isInstancedBufferAttribute = true;
  29862. return data;
  29863. }
  29864. } );
  29865. function BufferGeometryLoader( manager ) {
  29866. Loader.call( this, manager );
  29867. }
  29868. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29869. constructor: BufferGeometryLoader,
  29870. load: function ( url, onLoad, onProgress, onError ) {
  29871. var scope = this;
  29872. var loader = new FileLoader( scope.manager );
  29873. loader.setPath( scope.path );
  29874. loader.setRequestHeader( scope.requestHeader );
  29875. loader.load( url, function ( text ) {
  29876. try {
  29877. onLoad( scope.parse( JSON.parse( text ) ) );
  29878. } catch ( e ) {
  29879. if ( onError ) {
  29880. onError( e );
  29881. } else {
  29882. console.error( e );
  29883. }
  29884. scope.manager.itemError( url );
  29885. }
  29886. }, onProgress, onError );
  29887. },
  29888. parse: function ( json ) {
  29889. var interleavedBufferMap = {};
  29890. var arrayBufferMap = {};
  29891. function getInterleavedBuffer( json, uuid ) {
  29892. if ( interleavedBufferMap[ uuid ] !== undefined ) { return interleavedBufferMap[ uuid ]; }
  29893. var interleavedBuffers = json.interleavedBuffers;
  29894. var interleavedBuffer = interleavedBuffers[ uuid ];
  29895. var buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  29896. var array = new TYPED_ARRAYS[ interleavedBuffer.type ]( buffer );
  29897. var ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  29898. ib.uuid = interleavedBuffer.uuid;
  29899. interleavedBufferMap[ uuid ] = ib;
  29900. return ib;
  29901. }
  29902. function getArrayBuffer( json, uuid ) {
  29903. if ( arrayBufferMap[ uuid ] !== undefined ) { return arrayBufferMap[ uuid ]; }
  29904. var arrayBuffers = json.arrayBuffers;
  29905. var arrayBuffer = arrayBuffers[ uuid ];
  29906. var ab = new Uint32Array( arrayBuffer ).buffer;
  29907. arrayBufferMap[ uuid ] = ab;
  29908. return ab;
  29909. }
  29910. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  29911. var index = json.data.index;
  29912. if ( index !== undefined ) {
  29913. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  29914. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  29915. }
  29916. var attributes = json.data.attributes;
  29917. for ( var key in attributes ) {
  29918. var attribute = attributes[ key ];
  29919. var bufferAttribute = (void 0);
  29920. if ( attribute.isInterleavedBufferAttribute ) {
  29921. var interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  29922. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  29923. } else {
  29924. var typedArray$1 = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  29925. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  29926. bufferAttribute = new bufferAttributeConstr( typedArray$1, attribute.itemSize, attribute.normalized );
  29927. }
  29928. if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
  29929. geometry.setAttribute( key, bufferAttribute );
  29930. }
  29931. var morphAttributes = json.data.morphAttributes;
  29932. if ( morphAttributes ) {
  29933. for ( var key$1 in morphAttributes ) {
  29934. var attributeArray = morphAttributes[ key$1 ];
  29935. var array = [];
  29936. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  29937. var attribute$1 = attributeArray[ i ];
  29938. var bufferAttribute$1 = (void 0);
  29939. if ( attribute$1.isInterleavedBufferAttribute ) {
  29940. var interleavedBuffer$1 = getInterleavedBuffer( json.data, attribute$1.data );
  29941. bufferAttribute$1 = new InterleavedBufferAttribute( interleavedBuffer$1, attribute$1.itemSize, attribute$1.offset, attribute$1.normalized );
  29942. } else {
  29943. var typedArray$2 = new TYPED_ARRAYS[ attribute$1.type ]( attribute$1.array );
  29944. bufferAttribute$1 = new BufferAttribute( typedArray$2, attribute$1.itemSize, attribute$1.normalized );
  29945. }
  29946. if ( attribute$1.name !== undefined ) { bufferAttribute$1.name = attribute$1.name; }
  29947. array.push( bufferAttribute$1 );
  29948. }
  29949. geometry.morphAttributes[ key$1 ] = array;
  29950. }
  29951. }
  29952. var morphTargetsRelative = json.data.morphTargetsRelative;
  29953. if ( morphTargetsRelative ) {
  29954. geometry.morphTargetsRelative = true;
  29955. }
  29956. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  29957. if ( groups !== undefined ) {
  29958. for ( var i$1 = 0, n = groups.length; i$1 !== n; ++ i$1 ) {
  29959. var group = groups[ i$1 ];
  29960. geometry.addGroup( group.start, group.count, group.materialIndex );
  29961. }
  29962. }
  29963. var boundingSphere = json.data.boundingSphere;
  29964. if ( boundingSphere !== undefined ) {
  29965. var center = new Vector3();
  29966. if ( boundingSphere.center !== undefined ) {
  29967. center.fromArray( boundingSphere.center );
  29968. }
  29969. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  29970. }
  29971. if ( json.name ) { geometry.name = json.name; }
  29972. if ( json.userData ) { geometry.userData = json.userData; }
  29973. return geometry;
  29974. }
  29975. } );
  29976. var TYPED_ARRAYS = {
  29977. Int8Array: Int8Array,
  29978. Uint8Array: Uint8Array,
  29979. // Workaround for IE11 pre KB2929437. See #11440
  29980. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  29981. Int16Array: Int16Array,
  29982. Uint16Array: Uint16Array,
  29983. Int32Array: Int32Array,
  29984. Uint32Array: Uint32Array,
  29985. Float32Array: Float32Array,
  29986. Float64Array: Float64Array
  29987. };
  29988. function ObjectLoader( manager ) {
  29989. Loader.call( this, manager );
  29990. }
  29991. ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29992. constructor: ObjectLoader,
  29993. load: function ( url, onLoad, onProgress, onError ) {
  29994. var scope = this;
  29995. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  29996. this.resourcePath = this.resourcePath || path;
  29997. var loader = new FileLoader( scope.manager );
  29998. loader.setPath( this.path );
  29999. loader.setRequestHeader( this.requestHeader );
  30000. loader.load( url, function ( text ) {
  30001. var json = null;
  30002. try {
  30003. json = JSON.parse( text );
  30004. } catch ( error ) {
  30005. if ( onError !== undefined ) { onError( error ); }
  30006. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  30007. return;
  30008. }
  30009. var metadata = json.metadata;
  30010. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  30011. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  30012. return;
  30013. }
  30014. scope.parse( json, onLoad );
  30015. }, onProgress, onError );
  30016. },
  30017. parse: function ( json, onLoad ) {
  30018. var shapes = this.parseShape( json.shapes );
  30019. var geometries = this.parseGeometries( json.geometries, shapes );
  30020. var images = this.parseImages( json.images, function () {
  30021. if ( onLoad !== undefined ) { onLoad( object ); }
  30022. } );
  30023. var textures = this.parseTextures( json.textures, images );
  30024. var materials = this.parseMaterials( json.materials, textures );
  30025. var object = this.parseObject( json.object, geometries, materials );
  30026. if ( json.animations ) {
  30027. object.animations = this.parseAnimations( json.animations );
  30028. }
  30029. if ( json.images === undefined || json.images.length === 0 ) {
  30030. if ( onLoad !== undefined ) { onLoad( object ); }
  30031. }
  30032. return object;
  30033. },
  30034. parseShape: function ( json ) {
  30035. var shapes = {};
  30036. if ( json !== undefined ) {
  30037. for ( var i = 0, l = json.length; i < l; i ++ ) {
  30038. var shape = new Shape().fromJSON( json[ i ] );
  30039. shapes[ shape.uuid ] = shape;
  30040. }
  30041. }
  30042. return shapes;
  30043. },
  30044. parseGeometries: function ( json, shapes ) {
  30045. var geometries = {};
  30046. var geometryShapes;
  30047. if ( json !== undefined ) {
  30048. var bufferGeometryLoader = new BufferGeometryLoader();
  30049. for ( var i = 0, l = json.length; i < l; i ++ ) {
  30050. var geometry = (void 0);
  30051. var data = json[ i ];
  30052. switch ( data.type ) {
  30053. case 'PlaneGeometry':
  30054. case 'PlaneBufferGeometry':
  30055. geometry = new Geometries[ data.type ](
  30056. data.width,
  30057. data.height,
  30058. data.widthSegments,
  30059. data.heightSegments
  30060. );
  30061. break;
  30062. case 'BoxGeometry':
  30063. case 'BoxBufferGeometry':
  30064. case 'CubeGeometry': // backwards compatible
  30065. geometry = new Geometries[ data.type ](
  30066. data.width,
  30067. data.height,
  30068. data.depth,
  30069. data.widthSegments,
  30070. data.heightSegments,
  30071. data.depthSegments
  30072. );
  30073. break;
  30074. case 'CircleGeometry':
  30075. case 'CircleBufferGeometry':
  30076. geometry = new Geometries[ data.type ](
  30077. data.radius,
  30078. data.segments,
  30079. data.thetaStart,
  30080. data.thetaLength
  30081. );
  30082. break;
  30083. case 'CylinderGeometry':
  30084. case 'CylinderBufferGeometry':
  30085. geometry = new Geometries[ data.type ](
  30086. data.radiusTop,
  30087. data.radiusBottom,
  30088. data.height,
  30089. data.radialSegments,
  30090. data.heightSegments,
  30091. data.openEnded,
  30092. data.thetaStart,
  30093. data.thetaLength
  30094. );
  30095. break;
  30096. case 'ConeGeometry':
  30097. case 'ConeBufferGeometry':
  30098. geometry = new Geometries[ data.type ](
  30099. data.radius,
  30100. data.height,
  30101. data.radialSegments,
  30102. data.heightSegments,
  30103. data.openEnded,
  30104. data.thetaStart,
  30105. data.thetaLength
  30106. );
  30107. break;
  30108. case 'SphereGeometry':
  30109. case 'SphereBufferGeometry':
  30110. geometry = new Geometries[ data.type ](
  30111. data.radius,
  30112. data.widthSegments,
  30113. data.heightSegments,
  30114. data.phiStart,
  30115. data.phiLength,
  30116. data.thetaStart,
  30117. data.thetaLength
  30118. );
  30119. break;
  30120. case 'DodecahedronGeometry':
  30121. case 'DodecahedronBufferGeometry':
  30122. case 'IcosahedronGeometry':
  30123. case 'IcosahedronBufferGeometry':
  30124. case 'OctahedronGeometry':
  30125. case 'OctahedronBufferGeometry':
  30126. case 'TetrahedronGeometry':
  30127. case 'TetrahedronBufferGeometry':
  30128. geometry = new Geometries[ data.type ](
  30129. data.radius,
  30130. data.detail
  30131. );
  30132. break;
  30133. case 'RingGeometry':
  30134. case 'RingBufferGeometry':
  30135. geometry = new Geometries[ data.type ](
  30136. data.innerRadius,
  30137. data.outerRadius,
  30138. data.thetaSegments,
  30139. data.phiSegments,
  30140. data.thetaStart,
  30141. data.thetaLength
  30142. );
  30143. break;
  30144. case 'TorusGeometry':
  30145. case 'TorusBufferGeometry':
  30146. geometry = new Geometries[ data.type ](
  30147. data.radius,
  30148. data.tube,
  30149. data.radialSegments,
  30150. data.tubularSegments,
  30151. data.arc
  30152. );
  30153. break;
  30154. case 'TorusKnotGeometry':
  30155. case 'TorusKnotBufferGeometry':
  30156. geometry = new Geometries[ data.type ](
  30157. data.radius,
  30158. data.tube,
  30159. data.tubularSegments,
  30160. data.radialSegments,
  30161. data.p,
  30162. data.q
  30163. );
  30164. break;
  30165. case 'TubeGeometry':
  30166. case 'TubeBufferGeometry':
  30167. // This only works for built-in curves (e.g. CatmullRomCurve3).
  30168. // User defined curves or instances of CurvePath will not be deserialized.
  30169. geometry = new Geometries[ data.type ](
  30170. new Curves[ data.path.type ]().fromJSON( data.path ),
  30171. data.tubularSegments,
  30172. data.radius,
  30173. data.radialSegments,
  30174. data.closed
  30175. );
  30176. break;
  30177. case 'LatheGeometry':
  30178. case 'LatheBufferGeometry':
  30179. geometry = new Geometries[ data.type ](
  30180. data.points,
  30181. data.segments,
  30182. data.phiStart,
  30183. data.phiLength
  30184. );
  30185. break;
  30186. case 'PolyhedronGeometry':
  30187. case 'PolyhedronBufferGeometry':
  30188. geometry = new Geometries[ data.type ](
  30189. data.vertices,
  30190. data.indices,
  30191. data.radius,
  30192. data.details
  30193. );
  30194. break;
  30195. case 'ShapeGeometry':
  30196. case 'ShapeBufferGeometry':
  30197. geometryShapes = [];
  30198. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  30199. var shape = shapes[ data.shapes[ j ] ];
  30200. geometryShapes.push( shape );
  30201. }
  30202. geometry = new Geometries[ data.type ](
  30203. geometryShapes,
  30204. data.curveSegments
  30205. );
  30206. break;
  30207. case 'ExtrudeGeometry':
  30208. case 'ExtrudeBufferGeometry':
  30209. geometryShapes = [];
  30210. for ( var j$1 = 0, jl$1 = data.shapes.length; j$1 < jl$1; j$1 ++ ) {
  30211. var shape$1 = shapes[ data.shapes[ j$1 ] ];
  30212. geometryShapes.push( shape$1 );
  30213. }
  30214. var extrudePath = data.options.extrudePath;
  30215. if ( extrudePath !== undefined ) {
  30216. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  30217. }
  30218. geometry = new Geometries[ data.type ](
  30219. geometryShapes,
  30220. data.options
  30221. );
  30222. break;
  30223. case 'BufferGeometry':
  30224. case 'InstancedBufferGeometry':
  30225. geometry = bufferGeometryLoader.parse( data );
  30226. break;
  30227. case 'Geometry':
  30228. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  30229. break;
  30230. default:
  30231. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  30232. continue;
  30233. }
  30234. geometry.uuid = data.uuid;
  30235. if ( data.name !== undefined ) { geometry.name = data.name; }
  30236. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; }
  30237. geometries[ data.uuid ] = geometry;
  30238. }
  30239. }
  30240. return geometries;
  30241. },
  30242. parseMaterials: function ( json, textures ) {
  30243. var cache = {}; // MultiMaterial
  30244. var materials = {};
  30245. if ( json !== undefined ) {
  30246. var loader = new MaterialLoader();
  30247. loader.setTextures( textures );
  30248. for ( var i = 0, l = json.length; i < l; i ++ ) {
  30249. var data = json[ i ];
  30250. if ( data.type === 'MultiMaterial' ) {
  30251. // Deprecated
  30252. var array = [];
  30253. for ( var j = 0; j < data.materials.length; j ++ ) {
  30254. var material = data.materials[ j ];
  30255. if ( cache[ material.uuid ] === undefined ) {
  30256. cache[ material.uuid ] = loader.parse( material );
  30257. }
  30258. array.push( cache[ material.uuid ] );
  30259. }
  30260. materials[ data.uuid ] = array;
  30261. } else {
  30262. if ( cache[ data.uuid ] === undefined ) {
  30263. cache[ data.uuid ] = loader.parse( data );
  30264. }
  30265. materials[ data.uuid ] = cache[ data.uuid ];
  30266. }
  30267. }
  30268. }
  30269. return materials;
  30270. },
  30271. parseAnimations: function ( json ) {
  30272. var animations = [];
  30273. for ( var i = 0; i < json.length; i ++ ) {
  30274. var data = json[ i ];
  30275. var clip = AnimationClip.parse( data );
  30276. if ( data.uuid !== undefined ) { clip.uuid = data.uuid; }
  30277. animations.push( clip );
  30278. }
  30279. return animations;
  30280. },
  30281. parseImages: function ( json, onLoad ) {
  30282. var scope = this;
  30283. var images = {};
  30284. var loader;
  30285. function loadImage( url ) {
  30286. scope.manager.itemStart( url );
  30287. return loader.load( url, function () {
  30288. scope.manager.itemEnd( url );
  30289. }, undefined, function () {
  30290. scope.manager.itemError( url );
  30291. scope.manager.itemEnd( url );
  30292. } );
  30293. }
  30294. if ( json !== undefined && json.length > 0 ) {
  30295. var manager = new LoadingManager( onLoad );
  30296. loader = new ImageLoader( manager );
  30297. loader.setCrossOrigin( this.crossOrigin );
  30298. for ( var i = 0, il = json.length; i < il; i ++ ) {
  30299. var image = json[ i ];
  30300. var url = image.url;
  30301. if ( Array.isArray( url ) ) {
  30302. // load array of images e.g CubeTexture
  30303. images[ image.uuid ] = [];
  30304. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  30305. var currentUrl = url[ j ];
  30306. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  30307. images[ image.uuid ].push( loadImage( path ) );
  30308. }
  30309. } else {
  30310. // load single image
  30311. var path$1 = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  30312. images[ image.uuid ] = loadImage( path$1 );
  30313. }
  30314. }
  30315. }
  30316. return images;
  30317. },
  30318. parseTextures: function ( json, images ) {
  30319. function parseConstant( value, type ) {
  30320. if ( typeof value === 'number' ) { return value; }
  30321. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  30322. return type[ value ];
  30323. }
  30324. var textures = {};
  30325. if ( json !== undefined ) {
  30326. for ( var i = 0, l = json.length; i < l; i ++ ) {
  30327. var data = json[ i ];
  30328. if ( data.image === undefined ) {
  30329. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  30330. }
  30331. if ( images[ data.image ] === undefined ) {
  30332. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  30333. }
  30334. var texture = (void 0);
  30335. if ( Array.isArray( images[ data.image ] ) ) {
  30336. texture = new CubeTexture( images[ data.image ] );
  30337. } else {
  30338. texture = new Texture( images[ data.image ] );
  30339. }
  30340. texture.needsUpdate = true;
  30341. texture.uuid = data.uuid;
  30342. if ( data.name !== undefined ) { texture.name = data.name; }
  30343. if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); }
  30344. if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); }
  30345. if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); }
  30346. if ( data.center !== undefined ) { texture.center.fromArray( data.center ); }
  30347. if ( data.rotation !== undefined ) { texture.rotation = data.rotation; }
  30348. if ( data.wrap !== undefined ) {
  30349. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  30350. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  30351. }
  30352. if ( data.format !== undefined ) { texture.format = data.format; }
  30353. if ( data.type !== undefined ) { texture.type = data.type; }
  30354. if ( data.encoding !== undefined ) { texture.encoding = data.encoding; }
  30355. if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); }
  30356. if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); }
  30357. if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; }
  30358. if ( data.flipY !== undefined ) { texture.flipY = data.flipY; }
  30359. if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; }
  30360. if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; }
  30361. textures[ data.uuid ] = texture;
  30362. }
  30363. }
  30364. return textures;
  30365. },
  30366. parseObject: function ( data, geometries, materials ) {
  30367. var object;
  30368. function getGeometry( name ) {
  30369. if ( geometries[ name ] === undefined ) {
  30370. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  30371. }
  30372. return geometries[ name ];
  30373. }
  30374. function getMaterial( name ) {
  30375. if ( name === undefined ) { return undefined; }
  30376. if ( Array.isArray( name ) ) {
  30377. var array = [];
  30378. for ( var i = 0, l = name.length; i < l; i ++ ) {
  30379. var uuid = name[ i ];
  30380. if ( materials[ uuid ] === undefined ) {
  30381. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  30382. }
  30383. array.push( materials[ uuid ] );
  30384. }
  30385. return array;
  30386. }
  30387. if ( materials[ name ] === undefined ) {
  30388. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  30389. }
  30390. return materials[ name ];
  30391. }
  30392. var geometry, material;
  30393. switch ( data.type ) {
  30394. case 'Scene':
  30395. object = new Scene();
  30396. if ( data.background !== undefined ) {
  30397. if ( Number.isInteger( data.background ) ) {
  30398. object.background = new Color( data.background );
  30399. }
  30400. }
  30401. if ( data.fog !== undefined ) {
  30402. if ( data.fog.type === 'Fog' ) {
  30403. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  30404. } else if ( data.fog.type === 'FogExp2' ) {
  30405. object.fog = new FogExp2( data.fog.color, data.fog.density );
  30406. }
  30407. }
  30408. break;
  30409. case 'PerspectiveCamera':
  30410. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  30411. if ( data.focus !== undefined ) { object.focus = data.focus; }
  30412. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  30413. if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; }
  30414. if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; }
  30415. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  30416. break;
  30417. case 'OrthographicCamera':
  30418. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  30419. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  30420. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  30421. break;
  30422. case 'AmbientLight':
  30423. object = new AmbientLight( data.color, data.intensity );
  30424. break;
  30425. case 'DirectionalLight':
  30426. object = new DirectionalLight( data.color, data.intensity );
  30427. break;
  30428. case 'PointLight':
  30429. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  30430. break;
  30431. case 'RectAreaLight':
  30432. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  30433. break;
  30434. case 'SpotLight':
  30435. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  30436. break;
  30437. case 'HemisphereLight':
  30438. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  30439. break;
  30440. case 'LightProbe':
  30441. object = new LightProbe().fromJSON( data );
  30442. break;
  30443. case 'SkinnedMesh':
  30444. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  30445. case 'Mesh':
  30446. geometry = getGeometry( data.geometry );
  30447. material = getMaterial( data.material );
  30448. object = new Mesh( geometry, material );
  30449. break;
  30450. case 'InstancedMesh':
  30451. geometry = getGeometry( data.geometry );
  30452. material = getMaterial( data.material );
  30453. var count = data.count;
  30454. var instanceMatrix = data.instanceMatrix;
  30455. object = new InstancedMesh( geometry, material, count );
  30456. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  30457. break;
  30458. case 'LOD':
  30459. object = new LOD();
  30460. break;
  30461. case 'Line':
  30462. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  30463. break;
  30464. case 'LineLoop':
  30465. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  30466. break;
  30467. case 'LineSegments':
  30468. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  30469. break;
  30470. case 'PointCloud':
  30471. case 'Points':
  30472. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  30473. break;
  30474. case 'Sprite':
  30475. object = new Sprite( getMaterial( data.material ) );
  30476. break;
  30477. case 'Group':
  30478. object = new Group();
  30479. break;
  30480. default:
  30481. object = new Object3D();
  30482. }
  30483. object.uuid = data.uuid;
  30484. if ( data.name !== undefined ) { object.name = data.name; }
  30485. if ( data.matrix !== undefined ) {
  30486. object.matrix.fromArray( data.matrix );
  30487. if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; }
  30488. if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); }
  30489. } else {
  30490. if ( data.position !== undefined ) { object.position.fromArray( data.position ); }
  30491. if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); }
  30492. if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); }
  30493. if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); }
  30494. }
  30495. if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; }
  30496. if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; }
  30497. if ( data.shadow ) {
  30498. if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; }
  30499. if ( data.shadow.normalBias !== undefined ) { object.shadow.normalBias = data.shadow.normalBias; }
  30500. if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; }
  30501. if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); }
  30502. if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); }
  30503. }
  30504. if ( data.visible !== undefined ) { object.visible = data.visible; }
  30505. if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; }
  30506. if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; }
  30507. if ( data.userData !== undefined ) { object.userData = data.userData; }
  30508. if ( data.layers !== undefined ) { object.layers.mask = data.layers; }
  30509. if ( data.children !== undefined ) {
  30510. var children = data.children;
  30511. for ( var i = 0; i < children.length; i ++ ) {
  30512. object.add( this.parseObject( children[ i ], geometries, materials ) );
  30513. }
  30514. }
  30515. if ( data.type === 'LOD' ) {
  30516. if ( data.autoUpdate !== undefined ) { object.autoUpdate = data.autoUpdate; }
  30517. var levels = data.levels;
  30518. for ( var l = 0; l < levels.length; l ++ ) {
  30519. var level = levels[ l ];
  30520. var child = object.getObjectByProperty( 'uuid', level.object );
  30521. if ( child !== undefined ) {
  30522. object.addLevel( child, level.distance );
  30523. }
  30524. }
  30525. }
  30526. return object;
  30527. }
  30528. } );
  30529. var TEXTURE_MAPPING = {
  30530. UVMapping: UVMapping,
  30531. CubeReflectionMapping: CubeReflectionMapping,
  30532. CubeRefractionMapping: CubeRefractionMapping,
  30533. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30534. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30535. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30536. CubeUVRefractionMapping: CubeUVRefractionMapping
  30537. };
  30538. var TEXTURE_WRAPPING = {
  30539. RepeatWrapping: RepeatWrapping,
  30540. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30541. MirroredRepeatWrapping: MirroredRepeatWrapping
  30542. };
  30543. var TEXTURE_FILTER = {
  30544. NearestFilter: NearestFilter,
  30545. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30546. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30547. LinearFilter: LinearFilter,
  30548. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30549. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  30550. };
  30551. function ImageBitmapLoader( manager ) {
  30552. if ( typeof createImageBitmap === 'undefined' ) {
  30553. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  30554. }
  30555. if ( typeof fetch === 'undefined' ) {
  30556. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  30557. }
  30558. Loader.call( this, manager );
  30559. this.options = { premultiplyAlpha: 'none' };
  30560. }
  30561. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30562. constructor: ImageBitmapLoader,
  30563. isImageBitmapLoader: true,
  30564. setOptions: function setOptions( options ) {
  30565. this.options = options;
  30566. return this;
  30567. },
  30568. load: function ( url, onLoad, onProgress, onError ) {
  30569. if ( url === undefined ) { url = ''; }
  30570. if ( this.path !== undefined ) { url = this.path + url; }
  30571. url = this.manager.resolveURL( url );
  30572. var scope = this;
  30573. var cached = Cache.get( url );
  30574. if ( cached !== undefined ) {
  30575. scope.manager.itemStart( url );
  30576. setTimeout( function () {
  30577. if ( onLoad ) { onLoad( cached ); }
  30578. scope.manager.itemEnd( url );
  30579. }, 0 );
  30580. return cached;
  30581. }
  30582. fetch( url ).then( function ( res ) {
  30583. return res.blob();
  30584. } ).then( function ( blob ) {
  30585. return createImageBitmap( blob, scope.options );
  30586. } ).then( function ( imageBitmap ) {
  30587. Cache.add( url, imageBitmap );
  30588. if ( onLoad ) { onLoad( imageBitmap ); }
  30589. scope.manager.itemEnd( url );
  30590. } ).catch( function ( e ) {
  30591. if ( onError ) { onError( e ); }
  30592. scope.manager.itemError( url );
  30593. scope.manager.itemEnd( url );
  30594. } );
  30595. scope.manager.itemStart( url );
  30596. }
  30597. } );
  30598. function ShapePath() {
  30599. this.type = 'ShapePath';
  30600. this.color = new Color();
  30601. this.subPaths = [];
  30602. this.currentPath = null;
  30603. }
  30604. Object.assign( ShapePath.prototype, {
  30605. moveTo: function ( x, y ) {
  30606. this.currentPath = new Path();
  30607. this.subPaths.push( this.currentPath );
  30608. this.currentPath.moveTo( x, y );
  30609. return this;
  30610. },
  30611. lineTo: function ( x, y ) {
  30612. this.currentPath.lineTo( x, y );
  30613. return this;
  30614. },
  30615. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  30616. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  30617. return this;
  30618. },
  30619. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  30620. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  30621. return this;
  30622. },
  30623. splineThru: function ( pts ) {
  30624. this.currentPath.splineThru( pts );
  30625. return this;
  30626. },
  30627. toShapes: function ( isCCW, noHoles ) {
  30628. function toShapesNoHoles( inSubpaths ) {
  30629. var shapes = [];
  30630. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  30631. var tmpPath = inSubpaths[ i ];
  30632. var tmpShape = new Shape();
  30633. tmpShape.curves = tmpPath.curves;
  30634. shapes.push( tmpShape );
  30635. }
  30636. return shapes;
  30637. }
  30638. function isPointInsidePolygon( inPt, inPolygon ) {
  30639. var polyLen = inPolygon.length;
  30640. // inPt on polygon contour => immediate success or
  30641. // toggling of inside/outside at every single! intersection point of an edge
  30642. // with the horizontal line through inPt, left of inPt
  30643. // not counting lowerY endpoints of edges and whole edges on that line
  30644. var inside = false;
  30645. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  30646. var edgeLowPt = inPolygon[ p ];
  30647. var edgeHighPt = inPolygon[ q ];
  30648. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  30649. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  30650. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  30651. // not parallel
  30652. if ( edgeDy < 0 ) {
  30653. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  30654. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  30655. }
  30656. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) { continue; }
  30657. if ( inPt.y === edgeLowPt.y ) {
  30658. if ( inPt.x === edgeLowPt.x ) { return true; } // inPt is on contour ?
  30659. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30660. } else {
  30661. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  30662. if ( perpEdge === 0 ) { return true; } // inPt is on contour ?
  30663. if ( perpEdge < 0 ) { continue; }
  30664. inside = ! inside; // true intersection left of inPt
  30665. }
  30666. } else {
  30667. // parallel or collinear
  30668. if ( inPt.y !== edgeLowPt.y ) { continue; } // parallel
  30669. // edge lies on the same horizontal line as inPt
  30670. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  30671. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) { return true; } // inPt: Point on contour !
  30672. // continue;
  30673. }
  30674. }
  30675. return inside;
  30676. }
  30677. var isClockWise = ShapeUtils.isClockWise;
  30678. var subPaths = this.subPaths;
  30679. if ( subPaths.length === 0 ) { return []; }
  30680. if ( noHoles === true ) { return toShapesNoHoles( subPaths ); }
  30681. var solid, tmpPath, tmpShape, shapes = [];
  30682. if ( subPaths.length === 1 ) {
  30683. tmpPath = subPaths[ 0 ];
  30684. tmpShape = new Shape();
  30685. tmpShape.curves = tmpPath.curves;
  30686. shapes.push( tmpShape );
  30687. return shapes;
  30688. }
  30689. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  30690. holesFirst = isCCW ? ! holesFirst : holesFirst;
  30691. // console.log("Holes first", holesFirst);
  30692. var betterShapeHoles = [];
  30693. var newShapes = [];
  30694. var newShapeHoles = [];
  30695. var mainIdx = 0;
  30696. var tmpPoints;
  30697. newShapes[ mainIdx ] = undefined;
  30698. newShapeHoles[ mainIdx ] = [];
  30699. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  30700. tmpPath = subPaths[ i ];
  30701. tmpPoints = tmpPath.getPoints();
  30702. solid = isClockWise( tmpPoints );
  30703. solid = isCCW ? ! solid : solid;
  30704. if ( solid ) {
  30705. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) { mainIdx ++; }
  30706. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  30707. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  30708. if ( holesFirst ) { mainIdx ++; }
  30709. newShapeHoles[ mainIdx ] = [];
  30710. //console.log('cw', i);
  30711. } else {
  30712. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  30713. //console.log('ccw', i);
  30714. }
  30715. }
  30716. // only Holes? -> probably all Shapes with wrong orientation
  30717. if ( ! newShapes[ 0 ] ) { return toShapesNoHoles( subPaths ); }
  30718. if ( newShapes.length > 1 ) {
  30719. var ambiguous = false;
  30720. var toChange = [];
  30721. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30722. betterShapeHoles[ sIdx ] = [];
  30723. }
  30724. for ( var sIdx$1 = 0, sLen$1 = newShapes.length; sIdx$1 < sLen$1; sIdx$1 ++ ) {
  30725. var sho = newShapeHoles[ sIdx$1 ];
  30726. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  30727. var ho = sho[ hIdx ];
  30728. var hole_unassigned = true;
  30729. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  30730. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  30731. if ( sIdx$1 !== s2Idx ) { toChange.push( { froms: sIdx$1, tos: s2Idx, hole: hIdx } ); }
  30732. if ( hole_unassigned ) {
  30733. hole_unassigned = false;
  30734. betterShapeHoles[ s2Idx ].push( ho );
  30735. } else {
  30736. ambiguous = true;
  30737. }
  30738. }
  30739. }
  30740. if ( hole_unassigned ) {
  30741. betterShapeHoles[ sIdx$1 ].push( ho );
  30742. }
  30743. }
  30744. }
  30745. // console.log("ambiguous: ", ambiguous);
  30746. if ( toChange.length > 0 ) {
  30747. // console.log("to change: ", toChange);
  30748. if ( ! ambiguous ) { newShapeHoles = betterShapeHoles; }
  30749. }
  30750. }
  30751. var tmpHoles;
  30752. for ( var i$1 = 0, il = newShapes.length; i$1 < il; i$1 ++ ) {
  30753. tmpShape = newShapes[ i$1 ].s;
  30754. shapes.push( tmpShape );
  30755. tmpHoles = newShapeHoles[ i$1 ];
  30756. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  30757. tmpShape.holes.push( tmpHoles[ j ].h );
  30758. }
  30759. }
  30760. //console.log("shape", shapes);
  30761. return shapes;
  30762. }
  30763. } );
  30764. function Font( data ) {
  30765. this.type = 'Font';
  30766. this.data = data;
  30767. }
  30768. Object.assign( Font.prototype, {
  30769. isFont: true,
  30770. generateShapes: function ( text, size ) {
  30771. if ( size === undefined ) { size = 100; }
  30772. var shapes = [];
  30773. var paths = createPaths( text, size, this.data );
  30774. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  30775. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  30776. }
  30777. return shapes;
  30778. }
  30779. } );
  30780. function createPaths( text, size, data ) {
  30781. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  30782. var scale = size / data.resolution;
  30783. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  30784. var paths = [];
  30785. var offsetX = 0, offsetY = 0;
  30786. for ( var i = 0; i < chars.length; i ++ ) {
  30787. var char = chars[ i ];
  30788. if ( char === '\n' ) {
  30789. offsetX = 0;
  30790. offsetY -= line_height;
  30791. } else {
  30792. var ret = createPath( char, scale, offsetX, offsetY, data );
  30793. offsetX += ret.offsetX;
  30794. paths.push( ret.path );
  30795. }
  30796. }
  30797. return paths;
  30798. }
  30799. function createPath( char, scale, offsetX, offsetY, data ) {
  30800. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  30801. if ( ! glyph ) {
  30802. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  30803. return;
  30804. }
  30805. var path = new ShapePath();
  30806. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  30807. if ( glyph.o ) {
  30808. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  30809. for ( var i = 0, l = outline.length; i < l; ) {
  30810. var action = outline[ i ++ ];
  30811. switch ( action ) {
  30812. case 'm': // moveTo
  30813. x = outline[ i ++ ] * scale + offsetX;
  30814. y = outline[ i ++ ] * scale + offsetY;
  30815. path.moveTo( x, y );
  30816. break;
  30817. case 'l': // lineTo
  30818. x = outline[ i ++ ] * scale + offsetX;
  30819. y = outline[ i ++ ] * scale + offsetY;
  30820. path.lineTo( x, y );
  30821. break;
  30822. case 'q': // quadraticCurveTo
  30823. cpx = outline[ i ++ ] * scale + offsetX;
  30824. cpy = outline[ i ++ ] * scale + offsetY;
  30825. cpx1 = outline[ i ++ ] * scale + offsetX;
  30826. cpy1 = outline[ i ++ ] * scale + offsetY;
  30827. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  30828. break;
  30829. case 'b': // bezierCurveTo
  30830. cpx = outline[ i ++ ] * scale + offsetX;
  30831. cpy = outline[ i ++ ] * scale + offsetY;
  30832. cpx1 = outline[ i ++ ] * scale + offsetX;
  30833. cpy1 = outline[ i ++ ] * scale + offsetY;
  30834. cpx2 = outline[ i ++ ] * scale + offsetX;
  30835. cpy2 = outline[ i ++ ] * scale + offsetY;
  30836. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  30837. break;
  30838. }
  30839. }
  30840. }
  30841. return { offsetX: glyph.ha * scale, path: path };
  30842. }
  30843. function FontLoader( manager ) {
  30844. Loader.call( this, manager );
  30845. }
  30846. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30847. constructor: FontLoader,
  30848. load: function ( url, onLoad, onProgress, onError ) {
  30849. var scope = this;
  30850. var loader = new FileLoader( this.manager );
  30851. loader.setPath( this.path );
  30852. loader.setRequestHeader( this.requestHeader );
  30853. loader.load( url, function ( text ) {
  30854. var json;
  30855. try {
  30856. json = JSON.parse( text );
  30857. } catch ( e ) {
  30858. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  30859. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  30860. }
  30861. var font = scope.parse( json );
  30862. if ( onLoad ) { onLoad( font ); }
  30863. }, onProgress, onError );
  30864. },
  30865. parse: function ( json ) {
  30866. return new Font( json );
  30867. }
  30868. } );
  30869. var _context;
  30870. var AudioContext = {
  30871. getContext: function () {
  30872. if ( _context === undefined ) {
  30873. _context = new ( window.AudioContext || window.webkitAudioContext )();
  30874. }
  30875. return _context;
  30876. },
  30877. setContext: function ( value ) {
  30878. _context = value;
  30879. }
  30880. };
  30881. function AudioLoader( manager ) {
  30882. Loader.call( this, manager );
  30883. }
  30884. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30885. constructor: AudioLoader,
  30886. load: function ( url, onLoad, onProgress, onError ) {
  30887. var scope = this;
  30888. var loader = new FileLoader( scope.manager );
  30889. loader.setResponseType( 'arraybuffer' );
  30890. loader.setPath( scope.path );
  30891. loader.setRequestHeader( scope.requestHeader );
  30892. loader.load( url, function ( buffer ) {
  30893. try {
  30894. // Create a copy of the buffer. The `decodeAudioData` method
  30895. // detaches the buffer when complete, preventing reuse.
  30896. var bufferCopy = buffer.slice( 0 );
  30897. var context = AudioContext.getContext();
  30898. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  30899. onLoad( audioBuffer );
  30900. } );
  30901. } catch ( e ) {
  30902. if ( onError ) {
  30903. onError( e );
  30904. } else {
  30905. console.error( e );
  30906. }
  30907. scope.manager.itemError( url );
  30908. }
  30909. }, onProgress, onError );
  30910. }
  30911. } );
  30912. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  30913. LightProbe.call( this, undefined, intensity );
  30914. var color1 = new Color().set( skyColor );
  30915. var color2 = new Color().set( groundColor );
  30916. var sky = new Vector3( color1.r, color1.g, color1.b );
  30917. var ground = new Vector3( color2.r, color2.g, color2.b );
  30918. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30919. var c0 = Math.sqrt( Math.PI );
  30920. var c1 = c0 * Math.sqrt( 0.75 );
  30921. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  30922. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  30923. }
  30924. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30925. constructor: HemisphereLightProbe,
  30926. isHemisphereLightProbe: true,
  30927. copy: function ( source ) { // modifying colors not currently supported
  30928. LightProbe.prototype.copy.call( this, source );
  30929. return this;
  30930. },
  30931. toJSON: function ( meta ) {
  30932. var data = LightProbe.prototype.toJSON.call( this, meta );
  30933. // data.sh = this.sh.toArray(); // todo
  30934. return data;
  30935. }
  30936. } );
  30937. function AmbientLightProbe( color, intensity ) {
  30938. LightProbe.call( this, undefined, intensity );
  30939. var color1 = new Color().set( color );
  30940. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30941. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  30942. }
  30943. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30944. constructor: AmbientLightProbe,
  30945. isAmbientLightProbe: true,
  30946. copy: function ( source ) { // modifying color not currently supported
  30947. LightProbe.prototype.copy.call( this, source );
  30948. return this;
  30949. },
  30950. toJSON: function ( meta ) {
  30951. var data = LightProbe.prototype.toJSON.call( this, meta );
  30952. // data.sh = this.sh.toArray(); // todo
  30953. return data;
  30954. }
  30955. } );
  30956. var _eyeRight = new Matrix4();
  30957. var _eyeLeft = new Matrix4();
  30958. function StereoCamera() {
  30959. this.type = 'StereoCamera';
  30960. this.aspect = 1;
  30961. this.eyeSep = 0.064;
  30962. this.cameraL = new PerspectiveCamera();
  30963. this.cameraL.layers.enable( 1 );
  30964. this.cameraL.matrixAutoUpdate = false;
  30965. this.cameraR = new PerspectiveCamera();
  30966. this.cameraR.layers.enable( 2 );
  30967. this.cameraR.matrixAutoUpdate = false;
  30968. this._cache = {
  30969. focus: null,
  30970. fov: null,
  30971. aspect: null,
  30972. near: null,
  30973. far: null,
  30974. zoom: null,
  30975. eyeSep: null
  30976. };
  30977. }
  30978. Object.assign( StereoCamera.prototype, {
  30979. update: function ( camera ) {
  30980. var cache = this._cache;
  30981. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  30982. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  30983. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  30984. if ( needsUpdate ) {
  30985. cache.focus = camera.focus;
  30986. cache.fov = camera.fov;
  30987. cache.aspect = camera.aspect * this.aspect;
  30988. cache.near = camera.near;
  30989. cache.far = camera.far;
  30990. cache.zoom = camera.zoom;
  30991. cache.eyeSep = this.eyeSep;
  30992. // Off-axis stereoscopic effect based on
  30993. // http://paulbourke.net/stereographics/stereorender/
  30994. var projectionMatrix = camera.projectionMatrix.clone();
  30995. var eyeSepHalf = cache.eyeSep / 2;
  30996. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  30997. var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  30998. var xmin, xmax;
  30999. // translate xOffset
  31000. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  31001. _eyeRight.elements[ 12 ] = eyeSepHalf;
  31002. // for left eye
  31003. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  31004. xmax = ymax * cache.aspect + eyeSepOnProjection;
  31005. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  31006. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  31007. this.cameraL.projectionMatrix.copy( projectionMatrix );
  31008. // for right eye
  31009. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  31010. xmax = ymax * cache.aspect - eyeSepOnProjection;
  31011. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  31012. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  31013. this.cameraR.projectionMatrix.copy( projectionMatrix );
  31014. }
  31015. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  31016. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  31017. }
  31018. } );
  31019. function Clock( autoStart ) {
  31020. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  31021. this.startTime = 0;
  31022. this.oldTime = 0;
  31023. this.elapsedTime = 0;
  31024. this.running = false;
  31025. }
  31026. Object.assign( Clock.prototype, {
  31027. start: function () {
  31028. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  31029. this.oldTime = this.startTime;
  31030. this.elapsedTime = 0;
  31031. this.running = true;
  31032. },
  31033. stop: function () {
  31034. this.getElapsedTime();
  31035. this.running = false;
  31036. this.autoStart = false;
  31037. },
  31038. getElapsedTime: function () {
  31039. this.getDelta();
  31040. return this.elapsedTime;
  31041. },
  31042. getDelta: function () {
  31043. var diff = 0;
  31044. if ( this.autoStart && ! this.running ) {
  31045. this.start();
  31046. return 0;
  31047. }
  31048. if ( this.running ) {
  31049. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  31050. diff = ( newTime - this.oldTime ) / 1000;
  31051. this.oldTime = newTime;
  31052. this.elapsedTime += diff;
  31053. }
  31054. return diff;
  31055. }
  31056. } );
  31057. var _position$2 = new Vector3();
  31058. var _quaternion$3 = new Quaternion();
  31059. var _scale$1 = new Vector3();
  31060. var _orientation = new Vector3();
  31061. function AudioListener() {
  31062. Object3D.call( this );
  31063. this.type = 'AudioListener';
  31064. this.context = AudioContext.getContext();
  31065. this.gain = this.context.createGain();
  31066. this.gain.connect( this.context.destination );
  31067. this.filter = null;
  31068. this.timeDelta = 0;
  31069. // private
  31070. this._clock = new Clock();
  31071. }
  31072. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  31073. constructor: AudioListener,
  31074. getInput: function () {
  31075. return this.gain;
  31076. },
  31077. removeFilter: function ( ) {
  31078. if ( this.filter !== null ) {
  31079. this.gain.disconnect( this.filter );
  31080. this.filter.disconnect( this.context.destination );
  31081. this.gain.connect( this.context.destination );
  31082. this.filter = null;
  31083. }
  31084. return this;
  31085. },
  31086. getFilter: function () {
  31087. return this.filter;
  31088. },
  31089. setFilter: function ( value ) {
  31090. if ( this.filter !== null ) {
  31091. this.gain.disconnect( this.filter );
  31092. this.filter.disconnect( this.context.destination );
  31093. } else {
  31094. this.gain.disconnect( this.context.destination );
  31095. }
  31096. this.filter = value;
  31097. this.gain.connect( this.filter );
  31098. this.filter.connect( this.context.destination );
  31099. return this;
  31100. },
  31101. getMasterVolume: function () {
  31102. return this.gain.gain.value;
  31103. },
  31104. setMasterVolume: function ( value ) {
  31105. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  31106. return this;
  31107. },
  31108. updateMatrixWorld: function ( force ) {
  31109. Object3D.prototype.updateMatrixWorld.call( this, force );
  31110. var listener = this.context.listener;
  31111. var up = this.up;
  31112. this.timeDelta = this._clock.getDelta();
  31113. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  31114. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  31115. if ( listener.positionX ) {
  31116. // code path for Chrome (see #14393)
  31117. var endTime = this.context.currentTime + this.timeDelta;
  31118. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  31119. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  31120. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  31121. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  31122. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  31123. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  31124. listener.upX.linearRampToValueAtTime( up.x, endTime );
  31125. listener.upY.linearRampToValueAtTime( up.y, endTime );
  31126. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  31127. } else {
  31128. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  31129. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  31130. }
  31131. }
  31132. } );
  31133. function Audio( listener ) {
  31134. Object3D.call( this );
  31135. this.type = 'Audio';
  31136. this.listener = listener;
  31137. this.context = listener.context;
  31138. this.gain = this.context.createGain();
  31139. this.gain.connect( listener.getInput() );
  31140. this.autoplay = false;
  31141. this.buffer = null;
  31142. this.detune = 0;
  31143. this.loop = false;
  31144. this.loopStart = 0;
  31145. this.loopEnd = 0;
  31146. this.offset = 0;
  31147. this.duration = undefined;
  31148. this.playbackRate = 1;
  31149. this.isPlaying = false;
  31150. this.hasPlaybackControl = true;
  31151. this.sourceType = 'empty';
  31152. this._startedAt = 0;
  31153. this._progress = 0;
  31154. this.filters = [];
  31155. }
  31156. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  31157. constructor: Audio,
  31158. getOutput: function () {
  31159. return this.gain;
  31160. },
  31161. setNodeSource: function ( audioNode ) {
  31162. this.hasPlaybackControl = false;
  31163. this.sourceType = 'audioNode';
  31164. this.source = audioNode;
  31165. this.connect();
  31166. return this;
  31167. },
  31168. setMediaElementSource: function ( mediaElement ) {
  31169. this.hasPlaybackControl = false;
  31170. this.sourceType = 'mediaNode';
  31171. this.source = this.context.createMediaElementSource( mediaElement );
  31172. this.connect();
  31173. return this;
  31174. },
  31175. setMediaStreamSource: function ( mediaStream ) {
  31176. this.hasPlaybackControl = false;
  31177. this.sourceType = 'mediaStreamNode';
  31178. this.source = this.context.createMediaStreamSource( mediaStream );
  31179. this.connect();
  31180. return this;
  31181. },
  31182. setBuffer: function ( audioBuffer ) {
  31183. this.buffer = audioBuffer;
  31184. this.sourceType = 'buffer';
  31185. if ( this.autoplay ) { this.play(); }
  31186. return this;
  31187. },
  31188. play: function ( delay ) {
  31189. if ( delay === undefined ) { delay = 0; }
  31190. if ( this.isPlaying === true ) {
  31191. console.warn( 'THREE.Audio: Audio is already playing.' );
  31192. return;
  31193. }
  31194. if ( this.hasPlaybackControl === false ) {
  31195. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31196. return;
  31197. }
  31198. this._startedAt = this.context.currentTime + delay;
  31199. var source = this.context.createBufferSource();
  31200. source.buffer = this.buffer;
  31201. source.loop = this.loop;
  31202. source.loopStart = this.loopStart;
  31203. source.loopEnd = this.loopEnd;
  31204. source.onended = this.onEnded.bind( this );
  31205. source.start( this._startedAt, this._progress + this.offset, this.duration );
  31206. this.isPlaying = true;
  31207. this.source = source;
  31208. this.setDetune( this.detune );
  31209. this.setPlaybackRate( this.playbackRate );
  31210. return this.connect();
  31211. },
  31212. pause: function () {
  31213. if ( this.hasPlaybackControl === false ) {
  31214. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31215. return;
  31216. }
  31217. if ( this.isPlaying === true ) {
  31218. // update current progress
  31219. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  31220. if ( this.loop === true ) {
  31221. // ensure _progress does not exceed duration with looped audios
  31222. this._progress = this._progress % ( this.duration || this.buffer.duration );
  31223. }
  31224. this.source.stop();
  31225. this.source.onended = null;
  31226. this.isPlaying = false;
  31227. }
  31228. return this;
  31229. },
  31230. stop: function () {
  31231. if ( this.hasPlaybackControl === false ) {
  31232. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31233. return;
  31234. }
  31235. this._progress = 0;
  31236. this.source.stop();
  31237. this.source.onended = null;
  31238. this.isPlaying = false;
  31239. return this;
  31240. },
  31241. connect: function () {
  31242. if ( this.filters.length > 0 ) {
  31243. this.source.connect( this.filters[ 0 ] );
  31244. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  31245. this.filters[ i - 1 ].connect( this.filters[ i ] );
  31246. }
  31247. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  31248. } else {
  31249. this.source.connect( this.getOutput() );
  31250. }
  31251. return this;
  31252. },
  31253. disconnect: function () {
  31254. if ( this.filters.length > 0 ) {
  31255. this.source.disconnect( this.filters[ 0 ] );
  31256. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  31257. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  31258. }
  31259. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  31260. } else {
  31261. this.source.disconnect( this.getOutput() );
  31262. }
  31263. return this;
  31264. },
  31265. getFilters: function () {
  31266. return this.filters;
  31267. },
  31268. setFilters: function ( value ) {
  31269. if ( ! value ) { value = []; }
  31270. if ( this.isPlaying === true ) {
  31271. this.disconnect();
  31272. this.filters = value;
  31273. this.connect();
  31274. } else {
  31275. this.filters = value;
  31276. }
  31277. return this;
  31278. },
  31279. setDetune: function ( value ) {
  31280. this.detune = value;
  31281. if ( this.source.detune === undefined ) { return; } // only set detune when available
  31282. if ( this.isPlaying === true ) {
  31283. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  31284. }
  31285. return this;
  31286. },
  31287. getDetune: function () {
  31288. return this.detune;
  31289. },
  31290. getFilter: function () {
  31291. return this.getFilters()[ 0 ];
  31292. },
  31293. setFilter: function ( filter ) {
  31294. return this.setFilters( filter ? [ filter ] : [] );
  31295. },
  31296. setPlaybackRate: function ( value ) {
  31297. if ( this.hasPlaybackControl === false ) {
  31298. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31299. return;
  31300. }
  31301. this.playbackRate = value;
  31302. if ( this.isPlaying === true ) {
  31303. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  31304. }
  31305. return this;
  31306. },
  31307. getPlaybackRate: function () {
  31308. return this.playbackRate;
  31309. },
  31310. onEnded: function () {
  31311. this.isPlaying = false;
  31312. },
  31313. getLoop: function () {
  31314. if ( this.hasPlaybackControl === false ) {
  31315. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31316. return false;
  31317. }
  31318. return this.loop;
  31319. },
  31320. setLoop: function ( value ) {
  31321. if ( this.hasPlaybackControl === false ) {
  31322. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31323. return;
  31324. }
  31325. this.loop = value;
  31326. if ( this.isPlaying === true ) {
  31327. this.source.loop = this.loop;
  31328. }
  31329. return this;
  31330. },
  31331. setLoopStart: function ( value ) {
  31332. this.loopStart = value;
  31333. return this;
  31334. },
  31335. setLoopEnd: function ( value ) {
  31336. this.loopEnd = value;
  31337. return this;
  31338. },
  31339. getVolume: function () {
  31340. return this.gain.gain.value;
  31341. },
  31342. setVolume: function ( value ) {
  31343. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  31344. return this;
  31345. }
  31346. } );
  31347. var _position$3 = new Vector3();
  31348. var _quaternion$4 = new Quaternion();
  31349. var _scale$2 = new Vector3();
  31350. var _orientation$1 = new Vector3();
  31351. function PositionalAudio( listener ) {
  31352. Audio.call( this, listener );
  31353. this.panner = this.context.createPanner();
  31354. this.panner.panningModel = 'HRTF';
  31355. this.panner.connect( this.gain );
  31356. }
  31357. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  31358. constructor: PositionalAudio,
  31359. getOutput: function () {
  31360. return this.panner;
  31361. },
  31362. getRefDistance: function () {
  31363. return this.panner.refDistance;
  31364. },
  31365. setRefDistance: function ( value ) {
  31366. this.panner.refDistance = value;
  31367. return this;
  31368. },
  31369. getRolloffFactor: function () {
  31370. return this.panner.rolloffFactor;
  31371. },
  31372. setRolloffFactor: function ( value ) {
  31373. this.panner.rolloffFactor = value;
  31374. return this;
  31375. },
  31376. getDistanceModel: function () {
  31377. return this.panner.distanceModel;
  31378. },
  31379. setDistanceModel: function ( value ) {
  31380. this.panner.distanceModel = value;
  31381. return this;
  31382. },
  31383. getMaxDistance: function () {
  31384. return this.panner.maxDistance;
  31385. },
  31386. setMaxDistance: function ( value ) {
  31387. this.panner.maxDistance = value;
  31388. return this;
  31389. },
  31390. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  31391. this.panner.coneInnerAngle = coneInnerAngle;
  31392. this.panner.coneOuterAngle = coneOuterAngle;
  31393. this.panner.coneOuterGain = coneOuterGain;
  31394. return this;
  31395. },
  31396. updateMatrixWorld: function ( force ) {
  31397. Object3D.prototype.updateMatrixWorld.call( this, force );
  31398. if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; }
  31399. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  31400. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  31401. var panner = this.panner;
  31402. if ( panner.positionX ) {
  31403. // code path for Chrome and Firefox (see #14393)
  31404. var endTime = this.context.currentTime + this.listener.timeDelta;
  31405. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  31406. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  31407. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  31408. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  31409. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  31410. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  31411. } else {
  31412. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  31413. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  31414. }
  31415. }
  31416. } );
  31417. function AudioAnalyser( audio, fftSize ) {
  31418. this.analyser = audio.context.createAnalyser();
  31419. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  31420. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  31421. audio.getOutput().connect( this.analyser );
  31422. }
  31423. Object.assign( AudioAnalyser.prototype, {
  31424. getFrequencyData: function () {
  31425. this.analyser.getByteFrequencyData( this.data );
  31426. return this.data;
  31427. },
  31428. getAverageFrequency: function () {
  31429. var value = 0;
  31430. var data = this.getFrequencyData();
  31431. for ( var i = 0; i < data.length; i ++ ) {
  31432. value += data[ i ];
  31433. }
  31434. return value / data.length;
  31435. }
  31436. } );
  31437. function PropertyMixer( binding, typeName, valueSize ) {
  31438. this.binding = binding;
  31439. this.valueSize = valueSize;
  31440. var mixFunction,
  31441. mixFunctionAdditive,
  31442. setIdentity;
  31443. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  31444. //
  31445. // interpolators can use .buffer as their .result
  31446. // the data then goes to 'incoming'
  31447. //
  31448. // 'accu0' and 'accu1' are used frame-interleaved for
  31449. // the cumulative result and are compared to detect
  31450. // changes
  31451. //
  31452. // 'orig' stores the original state of the property
  31453. //
  31454. // 'add' is used for additive cumulative results
  31455. //
  31456. // 'work' is optional and is only present for quaternion types. It is used
  31457. // to store intermediate quaternion multiplication results
  31458. switch ( typeName ) {
  31459. case 'quaternion':
  31460. mixFunction = this._slerp;
  31461. mixFunctionAdditive = this._slerpAdditive;
  31462. setIdentity = this._setAdditiveIdentityQuaternion;
  31463. this.buffer = new Float64Array( valueSize * 6 );
  31464. this._workIndex = 5;
  31465. break;
  31466. case 'string':
  31467. case 'bool':
  31468. mixFunction = this._select;
  31469. // Use the regular mix function and for additive on these types,
  31470. // additive is not relevant for non-numeric types
  31471. mixFunctionAdditive = this._select;
  31472. setIdentity = this._setAdditiveIdentityOther;
  31473. this.buffer = new Array( valueSize * 5 );
  31474. break;
  31475. default:
  31476. mixFunction = this._lerp;
  31477. mixFunctionAdditive = this._lerpAdditive;
  31478. setIdentity = this._setAdditiveIdentityNumeric;
  31479. this.buffer = new Float64Array( valueSize * 5 );
  31480. }
  31481. this._mixBufferRegion = mixFunction;
  31482. this._mixBufferRegionAdditive = mixFunctionAdditive;
  31483. this._setIdentity = setIdentity;
  31484. this._origIndex = 3;
  31485. this._addIndex = 4;
  31486. this.cumulativeWeight = 0;
  31487. this.cumulativeWeightAdditive = 0;
  31488. this.useCount = 0;
  31489. this.referenceCount = 0;
  31490. }
  31491. Object.assign( PropertyMixer.prototype, {
  31492. // accumulate data in the 'incoming' region into 'accu<i>'
  31493. accumulate: function ( accuIndex, weight ) {
  31494. // note: happily accumulating nothing when weight = 0, the caller knows
  31495. // the weight and shouldn't have made the call in the first place
  31496. var buffer = this.buffer,
  31497. stride = this.valueSize,
  31498. offset = accuIndex * stride + stride;
  31499. var currentWeight = this.cumulativeWeight;
  31500. if ( currentWeight === 0 ) {
  31501. // accuN := incoming * weight
  31502. for ( var i = 0; i !== stride; ++ i ) {
  31503. buffer[ offset + i ] = buffer[ i ];
  31504. }
  31505. currentWeight = weight;
  31506. } else {
  31507. // accuN := accuN + incoming * weight
  31508. currentWeight += weight;
  31509. var mix = weight / currentWeight;
  31510. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  31511. }
  31512. this.cumulativeWeight = currentWeight;
  31513. },
  31514. // accumulate data in the 'incoming' region into 'add'
  31515. accumulateAdditive: function ( weight ) {
  31516. var buffer = this.buffer,
  31517. stride = this.valueSize,
  31518. offset = stride * this._addIndex;
  31519. if ( this.cumulativeWeightAdditive === 0 ) {
  31520. // add = identity
  31521. this._setIdentity();
  31522. }
  31523. // add := add + incoming * weight
  31524. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  31525. this.cumulativeWeightAdditive += weight;
  31526. },
  31527. // apply the state of 'accu<i>' to the binding when accus differ
  31528. apply: function ( accuIndex ) {
  31529. var stride = this.valueSize,
  31530. buffer = this.buffer,
  31531. offset = accuIndex * stride + stride,
  31532. weight = this.cumulativeWeight,
  31533. weightAdditive = this.cumulativeWeightAdditive,
  31534. binding = this.binding;
  31535. this.cumulativeWeight = 0;
  31536. this.cumulativeWeightAdditive = 0;
  31537. if ( weight < 1 ) {
  31538. // accuN := accuN + original * ( 1 - cumulativeWeight )
  31539. var originalValueOffset = stride * this._origIndex;
  31540. this._mixBufferRegion(
  31541. buffer, offset, originalValueOffset, 1 - weight, stride );
  31542. }
  31543. if ( weightAdditive > 0 ) {
  31544. // accuN := accuN + additive accuN
  31545. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  31546. }
  31547. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  31548. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  31549. // value has changed -> update scene graph
  31550. binding.setValue( buffer, offset );
  31551. break;
  31552. }
  31553. }
  31554. },
  31555. // remember the state of the bound property and copy it to both accus
  31556. saveOriginalState: function () {
  31557. var binding = this.binding;
  31558. var buffer = this.buffer,
  31559. stride = this.valueSize,
  31560. originalValueOffset = stride * this._origIndex;
  31561. binding.getValue( buffer, originalValueOffset );
  31562. // accu[0..1] := orig -- initially detect changes against the original
  31563. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  31564. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  31565. }
  31566. // Add to identity for additive
  31567. this._setIdentity();
  31568. this.cumulativeWeight = 0;
  31569. this.cumulativeWeightAdditive = 0;
  31570. },
  31571. // apply the state previously taken via 'saveOriginalState' to the binding
  31572. restoreOriginalState: function () {
  31573. var originalValueOffset = this.valueSize * 3;
  31574. this.binding.setValue( this.buffer, originalValueOffset );
  31575. },
  31576. _setAdditiveIdentityNumeric: function () {
  31577. var startIndex = this._addIndex * this.valueSize;
  31578. var endIndex = startIndex + this.valueSize;
  31579. for ( var i = startIndex; i < endIndex; i ++ ) {
  31580. this.buffer[ i ] = 0;
  31581. }
  31582. },
  31583. _setAdditiveIdentityQuaternion: function () {
  31584. this._setAdditiveIdentityNumeric();
  31585. this.buffer[ this._addIndex * 4 + 3 ] = 1;
  31586. },
  31587. _setAdditiveIdentityOther: function () {
  31588. var startIndex = this._origIndex * this.valueSize;
  31589. var targetIndex = this._addIndex * this.valueSize;
  31590. for ( var i = 0; i < this.valueSize; i ++ ) {
  31591. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  31592. }
  31593. },
  31594. // mix functions
  31595. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31596. if ( t >= 0.5 ) {
  31597. for ( var i = 0; i !== stride; ++ i ) {
  31598. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  31599. }
  31600. }
  31601. },
  31602. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  31603. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  31604. },
  31605. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31606. var workOffset = this._workIndex * stride;
  31607. // Store result in intermediate buffer offset
  31608. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  31609. // Slerp to the intermediate result
  31610. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  31611. },
  31612. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31613. var s = 1 - t;
  31614. for ( var i = 0; i !== stride; ++ i ) {
  31615. var j = dstOffset + i;
  31616. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  31617. }
  31618. },
  31619. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31620. for ( var i = 0; i !== stride; ++ i ) {
  31621. var j = dstOffset + i;
  31622. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  31623. }
  31624. }
  31625. } );
  31626. // Characters [].:/ are reserved for track binding syntax.
  31627. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  31628. var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  31629. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  31630. // only latin characters, and the unicode \p{L} is not yet supported. So
  31631. // instead, we exclude reserved characters and match everything else.
  31632. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  31633. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  31634. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  31635. // be matched to parse the rest of the track name.
  31636. var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  31637. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  31638. var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  31639. // Object on target node, and accessor. May not contain reserved
  31640. // characters. Accessor may contain any character except closing bracket.
  31641. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  31642. // Property and accessor. May not contain reserved characters. Accessor may
  31643. // contain any non-bracket characters.
  31644. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  31645. var _trackRe = new RegExp( ''
  31646. + '^'
  31647. + _directoryRe
  31648. + _nodeRe
  31649. + _objectRe
  31650. + _propertyRe
  31651. + '$'
  31652. );
  31653. var _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  31654. function Composite( targetGroup, path, optionalParsedPath ) {
  31655. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  31656. this._targetGroup = targetGroup;
  31657. this._bindings = targetGroup.subscribe_( path, parsedPath );
  31658. }
  31659. Object.assign( Composite.prototype, {
  31660. getValue: function ( array, offset ) {
  31661. this.bind(); // bind all binding
  31662. var firstValidIndex = this._targetGroup.nCachedObjects_,
  31663. binding = this._bindings[ firstValidIndex ];
  31664. // and only call .getValue on the first
  31665. if ( binding !== undefined ) { binding.getValue( array, offset ); }
  31666. },
  31667. setValue: function ( array, offset ) {
  31668. var bindings = this._bindings;
  31669. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31670. bindings[ i ].setValue( array, offset );
  31671. }
  31672. },
  31673. bind: function () {
  31674. var bindings = this._bindings;
  31675. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31676. bindings[ i ].bind();
  31677. }
  31678. },
  31679. unbind: function () {
  31680. var bindings = this._bindings;
  31681. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31682. bindings[ i ].unbind();
  31683. }
  31684. }
  31685. } );
  31686. function PropertyBinding( rootNode, path, parsedPath ) {
  31687. this.path = path;
  31688. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  31689. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  31690. this.rootNode = rootNode;
  31691. }
  31692. Object.assign( PropertyBinding, {
  31693. Composite: Composite,
  31694. create: function ( root, path, parsedPath ) {
  31695. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  31696. return new PropertyBinding( root, path, parsedPath );
  31697. } else {
  31698. return new PropertyBinding.Composite( root, path, parsedPath );
  31699. }
  31700. },
  31701. /**
  31702. * Replaces spaces with underscores and removes unsupported characters from
  31703. * node names, to ensure compatibility with parseTrackName().
  31704. *
  31705. * @param {string} name Node name to be sanitized.
  31706. * @return {string}
  31707. */
  31708. sanitizeNodeName: function ( name ) {
  31709. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  31710. },
  31711. parseTrackName: function ( trackName ) {
  31712. var matches = _trackRe.exec( trackName );
  31713. if ( ! matches ) {
  31714. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  31715. }
  31716. var results = {
  31717. // directoryName: matches[ 1 ], // (tschw) currently unused
  31718. nodeName: matches[ 2 ],
  31719. objectName: matches[ 3 ],
  31720. objectIndex: matches[ 4 ],
  31721. propertyName: matches[ 5 ], // required
  31722. propertyIndex: matches[ 6 ]
  31723. };
  31724. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  31725. if ( lastDot !== undefined && lastDot !== - 1 ) {
  31726. var objectName = results.nodeName.substring( lastDot + 1 );
  31727. // Object names must be checked against an allowlist. Otherwise, there
  31728. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  31729. // 'bar' could be the objectName, or part of a nodeName (which can
  31730. // include '.' characters).
  31731. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  31732. results.nodeName = results.nodeName.substring( 0, lastDot );
  31733. results.objectName = objectName;
  31734. }
  31735. }
  31736. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  31737. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  31738. }
  31739. return results;
  31740. },
  31741. findNode: function ( root, nodeName ) {
  31742. if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  31743. return root;
  31744. }
  31745. // search into skeleton bones.
  31746. if ( root.skeleton ) {
  31747. var bone = root.skeleton.getBoneByName( nodeName );
  31748. if ( bone !== undefined ) {
  31749. return bone;
  31750. }
  31751. }
  31752. // search into node subtree.
  31753. if ( root.children ) {
  31754. var searchNodeSubtree = function ( children ) {
  31755. for ( var i = 0; i < children.length; i ++ ) {
  31756. var childNode = children[ i ];
  31757. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  31758. return childNode;
  31759. }
  31760. var result = searchNodeSubtree( childNode.children );
  31761. if ( result ) { return result; }
  31762. }
  31763. return null;
  31764. };
  31765. var subTreeNode = searchNodeSubtree( root.children );
  31766. if ( subTreeNode ) {
  31767. return subTreeNode;
  31768. }
  31769. }
  31770. return null;
  31771. }
  31772. } );
  31773. Object.assign( PropertyBinding.prototype, { // prototype, continued
  31774. // these are used to "bind" a nonexistent property
  31775. _getValue_unavailable: function () {},
  31776. _setValue_unavailable: function () {},
  31777. BindingType: {
  31778. Direct: 0,
  31779. EntireArray: 1,
  31780. ArrayElement: 2,
  31781. HasFromToArray: 3
  31782. },
  31783. Versioning: {
  31784. None: 0,
  31785. NeedsUpdate: 1,
  31786. MatrixWorldNeedsUpdate: 2
  31787. },
  31788. GetterByBindingType: [
  31789. function getValue_direct( buffer, offset ) {
  31790. buffer[ offset ] = this.node[ this.propertyName ];
  31791. },
  31792. function getValue_array( buffer, offset ) {
  31793. var source = this.resolvedProperty;
  31794. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  31795. buffer[ offset ++ ] = source[ i ];
  31796. }
  31797. },
  31798. function getValue_arrayElement( buffer, offset ) {
  31799. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  31800. },
  31801. function getValue_toArray( buffer, offset ) {
  31802. this.resolvedProperty.toArray( buffer, offset );
  31803. }
  31804. ],
  31805. SetterByBindingTypeAndVersioning: [
  31806. [
  31807. // Direct
  31808. function setValue_direct( buffer, offset ) {
  31809. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31810. },
  31811. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  31812. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31813. this.targetObject.needsUpdate = true;
  31814. },
  31815. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31816. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31817. this.targetObject.matrixWorldNeedsUpdate = true;
  31818. }
  31819. ], [
  31820. // EntireArray
  31821. function setValue_array( buffer, offset ) {
  31822. var dest = this.resolvedProperty;
  31823. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31824. dest[ i ] = buffer[ offset ++ ];
  31825. }
  31826. },
  31827. function setValue_array_setNeedsUpdate( buffer, offset ) {
  31828. var dest = this.resolvedProperty;
  31829. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31830. dest[ i ] = buffer[ offset ++ ];
  31831. }
  31832. this.targetObject.needsUpdate = true;
  31833. },
  31834. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31835. var dest = this.resolvedProperty;
  31836. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31837. dest[ i ] = buffer[ offset ++ ];
  31838. }
  31839. this.targetObject.matrixWorldNeedsUpdate = true;
  31840. }
  31841. ], [
  31842. // ArrayElement
  31843. function setValue_arrayElement( buffer, offset ) {
  31844. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31845. },
  31846. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  31847. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31848. this.targetObject.needsUpdate = true;
  31849. },
  31850. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31851. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31852. this.targetObject.matrixWorldNeedsUpdate = true;
  31853. }
  31854. ], [
  31855. // HasToFromArray
  31856. function setValue_fromArray( buffer, offset ) {
  31857. this.resolvedProperty.fromArray( buffer, offset );
  31858. },
  31859. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  31860. this.resolvedProperty.fromArray( buffer, offset );
  31861. this.targetObject.needsUpdate = true;
  31862. },
  31863. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31864. this.resolvedProperty.fromArray( buffer, offset );
  31865. this.targetObject.matrixWorldNeedsUpdate = true;
  31866. }
  31867. ]
  31868. ],
  31869. getValue: function getValue_unbound( targetArray, offset ) {
  31870. this.bind();
  31871. this.getValue( targetArray, offset );
  31872. // Note: This class uses a State pattern on a per-method basis:
  31873. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31874. // prototype version of these methods with one that represents
  31875. // the bound state. When the property is not found, the methods
  31876. // become no-ops.
  31877. },
  31878. setValue: function getValue_unbound( sourceArray, offset ) {
  31879. this.bind();
  31880. this.setValue( sourceArray, offset );
  31881. },
  31882. // create getter / setter pair for a property in the scene graph
  31883. bind: function () {
  31884. var targetObject = this.node,
  31885. parsedPath = this.parsedPath,
  31886. objectName = parsedPath.objectName,
  31887. propertyName = parsedPath.propertyName,
  31888. propertyIndex = parsedPath.propertyIndex;
  31889. if ( ! targetObject ) {
  31890. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  31891. this.node = targetObject;
  31892. }
  31893. // set fail state so we can just 'return' on error
  31894. this.getValue = this._getValue_unavailable;
  31895. this.setValue = this._setValue_unavailable;
  31896. // ensure there is a value node
  31897. if ( ! targetObject ) {
  31898. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  31899. return;
  31900. }
  31901. if ( objectName ) {
  31902. var objectIndex = parsedPath.objectIndex;
  31903. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31904. switch ( objectName ) {
  31905. case 'materials':
  31906. if ( ! targetObject.material ) {
  31907. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  31908. return;
  31909. }
  31910. if ( ! targetObject.material.materials ) {
  31911. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  31912. return;
  31913. }
  31914. targetObject = targetObject.material.materials;
  31915. break;
  31916. case 'bones':
  31917. if ( ! targetObject.skeleton ) {
  31918. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  31919. return;
  31920. }
  31921. // potential future optimization: skip this if propertyIndex is already an integer
  31922. // and convert the integer string to a true integer.
  31923. targetObject = targetObject.skeleton.bones;
  31924. // support resolving morphTarget names into indices.
  31925. for ( var i = 0; i < targetObject.length; i ++ ) {
  31926. if ( targetObject[ i ].name === objectIndex ) {
  31927. objectIndex = i;
  31928. break;
  31929. }
  31930. }
  31931. break;
  31932. default:
  31933. if ( targetObject[ objectName ] === undefined ) {
  31934. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  31935. return;
  31936. }
  31937. targetObject = targetObject[ objectName ];
  31938. }
  31939. if ( objectIndex !== undefined ) {
  31940. if ( targetObject[ objectIndex ] === undefined ) {
  31941. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  31942. return;
  31943. }
  31944. targetObject = targetObject[ objectIndex ];
  31945. }
  31946. }
  31947. // resolve property
  31948. var nodeProperty = targetObject[ propertyName ];
  31949. if ( nodeProperty === undefined ) {
  31950. var nodeName = parsedPath.nodeName;
  31951. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  31952. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  31953. return;
  31954. }
  31955. // determine versioning scheme
  31956. var versioning = this.Versioning.None;
  31957. this.targetObject = targetObject;
  31958. if ( targetObject.needsUpdate !== undefined ) { // material
  31959. versioning = this.Versioning.NeedsUpdate;
  31960. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  31961. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31962. }
  31963. // determine how the property gets bound
  31964. var bindingType = this.BindingType.Direct;
  31965. if ( propertyIndex !== undefined ) {
  31966. // access a sub element of the property array (only primitives are supported right now)
  31967. if ( propertyName === "morphTargetInfluences" ) {
  31968. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31969. // support resolving morphTarget names into indices.
  31970. if ( ! targetObject.geometry ) {
  31971. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  31972. return;
  31973. }
  31974. if ( targetObject.geometry.isBufferGeometry ) {
  31975. if ( ! targetObject.geometry.morphAttributes ) {
  31976. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  31977. return;
  31978. }
  31979. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  31980. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  31981. }
  31982. } else {
  31983. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  31984. return;
  31985. }
  31986. }
  31987. bindingType = this.BindingType.ArrayElement;
  31988. this.resolvedProperty = nodeProperty;
  31989. this.propertyIndex = propertyIndex;
  31990. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  31991. // must use copy for Object3D.Euler/Quaternion
  31992. bindingType = this.BindingType.HasFromToArray;
  31993. this.resolvedProperty = nodeProperty;
  31994. } else if ( Array.isArray( nodeProperty ) ) {
  31995. bindingType = this.BindingType.EntireArray;
  31996. this.resolvedProperty = nodeProperty;
  31997. } else {
  31998. this.propertyName = propertyName;
  31999. }
  32000. // select getter / setter
  32001. this.getValue = this.GetterByBindingType[ bindingType ];
  32002. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  32003. },
  32004. unbind: function () {
  32005. this.node = null;
  32006. // back to the prototype version of getValue / setValue
  32007. // note: avoiding to mutate the shape of 'this' via 'delete'
  32008. this.getValue = this._getValue_unbound;
  32009. this.setValue = this._setValue_unbound;
  32010. }
  32011. } );
  32012. // DECLARE ALIAS AFTER assign prototype
  32013. Object.assign( PropertyBinding.prototype, {
  32014. // initial state of these methods that calls 'bind'
  32015. _getValue_unbound: PropertyBinding.prototype.getValue,
  32016. _setValue_unbound: PropertyBinding.prototype.setValue,
  32017. } );
  32018. /**
  32019. *
  32020. * A group of objects that receives a shared animation state.
  32021. *
  32022. * Usage:
  32023. *
  32024. * - Add objects you would otherwise pass as 'root' to the
  32025. * constructor or the .clipAction method of AnimationMixer.
  32026. *
  32027. * - Instead pass this object as 'root'.
  32028. *
  32029. * - You can also add and remove objects later when the mixer
  32030. * is running.
  32031. *
  32032. * Note:
  32033. *
  32034. * Objects of this class appear as one object to the mixer,
  32035. * so cache control of the individual objects must be done
  32036. * on the group.
  32037. *
  32038. * Limitation:
  32039. *
  32040. * - The animated properties must be compatible among the
  32041. * all objects in the group.
  32042. *
  32043. * - A single property can either be controlled through a
  32044. * target group or directly, but not both.
  32045. */
  32046. function AnimationObjectGroup() {
  32047. this.uuid = MathUtils.generateUUID();
  32048. // cached objects followed by the active ones
  32049. this._objects = Array.prototype.slice.call( arguments );
  32050. this.nCachedObjects_ = 0; // threshold
  32051. // note: read by PropertyBinding.Composite
  32052. var indices = {};
  32053. this._indicesByUUID = indices; // for bookkeeping
  32054. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32055. indices[ arguments[ i ].uuid ] = i;
  32056. }
  32057. this._paths = []; // inside: string
  32058. this._parsedPaths = []; // inside: { we don't care, here }
  32059. this._bindings = []; // inside: Array< PropertyBinding >
  32060. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  32061. var scope = this;
  32062. this.stats = {
  32063. objects: {
  32064. get total() {
  32065. return scope._objects.length;
  32066. },
  32067. get inUse() {
  32068. return this.total - scope.nCachedObjects_;
  32069. }
  32070. },
  32071. get bindingsPerObject() {
  32072. return scope._bindings.length;
  32073. }
  32074. };
  32075. }
  32076. Object.assign( AnimationObjectGroup.prototype, {
  32077. isAnimationObjectGroup: true,
  32078. add: function () {
  32079. var objects = this._objects,
  32080. indicesByUUID = this._indicesByUUID,
  32081. paths = this._paths,
  32082. parsedPaths = this._parsedPaths,
  32083. bindings = this._bindings,
  32084. nBindings = bindings.length;
  32085. var knownObject = undefined,
  32086. nObjects = objects.length,
  32087. nCachedObjects = this.nCachedObjects_;
  32088. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32089. var object = arguments[ i ],
  32090. uuid = object.uuid;
  32091. var index = indicesByUUID[ uuid ];
  32092. if ( index === undefined ) {
  32093. // unknown object -> add it to the ACTIVE region
  32094. index = nObjects ++;
  32095. indicesByUUID[ uuid ] = index;
  32096. objects.push( object );
  32097. // accounting is done, now do the same for all bindings
  32098. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32099. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  32100. }
  32101. } else if ( index < nCachedObjects ) {
  32102. knownObject = objects[ index ];
  32103. // move existing object to the ACTIVE region
  32104. var firstActiveIndex = -- nCachedObjects,
  32105. lastCachedObject = objects[ firstActiveIndex ];
  32106. indicesByUUID[ lastCachedObject.uuid ] = index;
  32107. objects[ index ] = lastCachedObject;
  32108. indicesByUUID[ uuid ] = firstActiveIndex;
  32109. objects[ firstActiveIndex ] = object;
  32110. // accounting is done, now do the same for all bindings
  32111. for ( var j$1 = 0, m$1 = nBindings; j$1 !== m$1; ++ j$1 ) {
  32112. var bindingsForPath = bindings[ j$1 ],
  32113. lastCached = bindingsForPath[ firstActiveIndex ];
  32114. var binding = bindingsForPath[ index ];
  32115. bindingsForPath[ index ] = lastCached;
  32116. if ( binding === undefined ) {
  32117. // since we do not bother to create new bindings
  32118. // for objects that are cached, the binding may
  32119. // or may not exist
  32120. binding = new PropertyBinding( object, paths[ j$1 ], parsedPaths[ j$1 ] );
  32121. }
  32122. bindingsForPath[ firstActiveIndex ] = binding;
  32123. }
  32124. } else if ( objects[ index ] !== knownObject ) {
  32125. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  32126. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  32127. } // else the object is already where we want it to be
  32128. } // for arguments
  32129. this.nCachedObjects_ = nCachedObjects;
  32130. },
  32131. remove: function () {
  32132. var objects = this._objects,
  32133. indicesByUUID = this._indicesByUUID,
  32134. bindings = this._bindings,
  32135. nBindings = bindings.length;
  32136. var nCachedObjects = this.nCachedObjects_;
  32137. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32138. var object = arguments[ i ],
  32139. uuid = object.uuid,
  32140. index = indicesByUUID[ uuid ];
  32141. if ( index !== undefined && index >= nCachedObjects ) {
  32142. // move existing object into the CACHED region
  32143. var lastCachedIndex = nCachedObjects ++,
  32144. firstActiveObject = objects[ lastCachedIndex ];
  32145. indicesByUUID[ firstActiveObject.uuid ] = index;
  32146. objects[ index ] = firstActiveObject;
  32147. indicesByUUID[ uuid ] = lastCachedIndex;
  32148. objects[ lastCachedIndex ] = object;
  32149. // accounting is done, now do the same for all bindings
  32150. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32151. var bindingsForPath = bindings[ j ],
  32152. firstActive = bindingsForPath[ lastCachedIndex ],
  32153. binding = bindingsForPath[ index ];
  32154. bindingsForPath[ index ] = firstActive;
  32155. bindingsForPath[ lastCachedIndex ] = binding;
  32156. }
  32157. }
  32158. } // for arguments
  32159. this.nCachedObjects_ = nCachedObjects;
  32160. },
  32161. // remove & forget
  32162. uncache: function () {
  32163. var objects = this._objects,
  32164. indicesByUUID = this._indicesByUUID,
  32165. bindings = this._bindings,
  32166. nBindings = bindings.length;
  32167. var nCachedObjects = this.nCachedObjects_,
  32168. nObjects = objects.length;
  32169. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32170. var object = arguments[ i ],
  32171. uuid = object.uuid,
  32172. index = indicesByUUID[ uuid ];
  32173. if ( index !== undefined ) {
  32174. delete indicesByUUID[ uuid ];
  32175. if ( index < nCachedObjects ) {
  32176. // object is cached, shrink the CACHED region
  32177. var firstActiveIndex = -- nCachedObjects,
  32178. lastCachedObject = objects[ firstActiveIndex ],
  32179. lastIndex = -- nObjects,
  32180. lastObject = objects[ lastIndex ];
  32181. // last cached object takes this object's place
  32182. indicesByUUID[ lastCachedObject.uuid ] = index;
  32183. objects[ index ] = lastCachedObject;
  32184. // last object goes to the activated slot and pop
  32185. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  32186. objects[ firstActiveIndex ] = lastObject;
  32187. objects.pop();
  32188. // accounting is done, now do the same for all bindings
  32189. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32190. var bindingsForPath = bindings[ j ],
  32191. lastCached = bindingsForPath[ firstActiveIndex ],
  32192. last = bindingsForPath[ lastIndex ];
  32193. bindingsForPath[ index ] = lastCached;
  32194. bindingsForPath[ firstActiveIndex ] = last;
  32195. bindingsForPath.pop();
  32196. }
  32197. } else {
  32198. // object is active, just swap with the last and pop
  32199. var lastIndex$1 = -- nObjects,
  32200. lastObject$1 = objects[ lastIndex$1 ];
  32201. indicesByUUID[ lastObject$1.uuid ] = index;
  32202. objects[ index ] = lastObject$1;
  32203. objects.pop();
  32204. // accounting is done, now do the same for all bindings
  32205. for ( var j$1 = 0, m$1 = nBindings; j$1 !== m$1; ++ j$1 ) {
  32206. var bindingsForPath$1 = bindings[ j$1 ];
  32207. bindingsForPath$1[ index ] = bindingsForPath$1[ lastIndex$1 ];
  32208. bindingsForPath$1.pop();
  32209. }
  32210. } // cached or active
  32211. } // if object is known
  32212. } // for arguments
  32213. this.nCachedObjects_ = nCachedObjects;
  32214. },
  32215. // Internal interface used by befriended PropertyBinding.Composite:
  32216. subscribe_: function ( path, parsedPath ) {
  32217. // returns an array of bindings for the given path that is changed
  32218. // according to the contained objects in the group
  32219. var indicesByPath = this._bindingsIndicesByPath,
  32220. index = indicesByPath[ path ],
  32221. bindings = this._bindings;
  32222. if ( index !== undefined ) { return bindings[ index ]; }
  32223. var paths = this._paths,
  32224. parsedPaths = this._parsedPaths,
  32225. objects = this._objects,
  32226. nObjects = objects.length,
  32227. nCachedObjects = this.nCachedObjects_,
  32228. bindingsForPath = new Array( nObjects );
  32229. index = bindings.length;
  32230. indicesByPath[ path ] = index;
  32231. paths.push( path );
  32232. parsedPaths.push( parsedPath );
  32233. bindings.push( bindingsForPath );
  32234. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  32235. var object = objects[ i ];
  32236. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  32237. }
  32238. return bindingsForPath;
  32239. },
  32240. unsubscribe_: function ( path ) {
  32241. // tells the group to forget about a property path and no longer
  32242. // update the array previously obtained with 'subscribe_'
  32243. var indicesByPath = this._bindingsIndicesByPath,
  32244. index = indicesByPath[ path ];
  32245. if ( index !== undefined ) {
  32246. var paths = this._paths,
  32247. parsedPaths = this._parsedPaths,
  32248. bindings = this._bindings,
  32249. lastBindingsIndex = bindings.length - 1,
  32250. lastBindings = bindings[ lastBindingsIndex ],
  32251. lastBindingsPath = path[ lastBindingsIndex ];
  32252. indicesByPath[ lastBindingsPath ] = index;
  32253. bindings[ index ] = lastBindings;
  32254. bindings.pop();
  32255. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  32256. parsedPaths.pop();
  32257. paths[ index ] = paths[ lastBindingsIndex ];
  32258. paths.pop();
  32259. }
  32260. }
  32261. } );
  32262. function AnimationAction( mixer, clip, localRoot, blendMode ) {
  32263. this._mixer = mixer;
  32264. this._clip = clip;
  32265. this._localRoot = localRoot || null;
  32266. this.blendMode = blendMode || clip.blendMode;
  32267. var tracks = clip.tracks,
  32268. nTracks = tracks.length,
  32269. interpolants = new Array( nTracks );
  32270. var interpolantSettings = {
  32271. endingStart: ZeroCurvatureEnding,
  32272. endingEnd: ZeroCurvatureEnding
  32273. };
  32274. for ( var i = 0; i !== nTracks; ++ i ) {
  32275. var interpolant = tracks[ i ].createInterpolant( null );
  32276. interpolants[ i ] = interpolant;
  32277. interpolant.settings = interpolantSettings;
  32278. }
  32279. this._interpolantSettings = interpolantSettings;
  32280. this._interpolants = interpolants; // bound by the mixer
  32281. // inside: PropertyMixer (managed by the mixer)
  32282. this._propertyBindings = new Array( nTracks );
  32283. this._cacheIndex = null; // for the memory manager
  32284. this._byClipCacheIndex = null; // for the memory manager
  32285. this._timeScaleInterpolant = null;
  32286. this._weightInterpolant = null;
  32287. this.loop = LoopRepeat;
  32288. this._loopCount = - 1;
  32289. // global mixer time when the action is to be started
  32290. // it's set back to 'null' upon start of the action
  32291. this._startTime = null;
  32292. // scaled local time of the action
  32293. // gets clamped or wrapped to 0..clip.duration according to loop
  32294. this.time = 0;
  32295. this.timeScale = 1;
  32296. this._effectiveTimeScale = 1;
  32297. this.weight = 1;
  32298. this._effectiveWeight = 1;
  32299. this.repetitions = Infinity; // no. of repetitions when looping
  32300. this.paused = false; // true -> zero effective time scale
  32301. this.enabled = true; // false -> zero effective weight
  32302. this.clampWhenFinished = false;// keep feeding the last frame?
  32303. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  32304. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  32305. }
  32306. Object.assign( AnimationAction.prototype, {
  32307. // State & Scheduling
  32308. play: function () {
  32309. this._mixer._activateAction( this );
  32310. return this;
  32311. },
  32312. stop: function () {
  32313. this._mixer._deactivateAction( this );
  32314. return this.reset();
  32315. },
  32316. reset: function () {
  32317. this.paused = false;
  32318. this.enabled = true;
  32319. this.time = 0; // restart clip
  32320. this._loopCount = - 1;// forget previous loops
  32321. this._startTime = null;// forget scheduling
  32322. return this.stopFading().stopWarping();
  32323. },
  32324. isRunning: function () {
  32325. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  32326. this._startTime === null && this._mixer._isActiveAction( this );
  32327. },
  32328. // return true when play has been called
  32329. isScheduled: function () {
  32330. return this._mixer._isActiveAction( this );
  32331. },
  32332. startAt: function ( time ) {
  32333. this._startTime = time;
  32334. return this;
  32335. },
  32336. setLoop: function ( mode, repetitions ) {
  32337. this.loop = mode;
  32338. this.repetitions = repetitions;
  32339. return this;
  32340. },
  32341. // Weight
  32342. // set the weight stopping any scheduled fading
  32343. // although .enabled = false yields an effective weight of zero, this
  32344. // method does *not* change .enabled, because it would be confusing
  32345. setEffectiveWeight: function ( weight ) {
  32346. this.weight = weight;
  32347. // note: same logic as when updated at runtime
  32348. this._effectiveWeight = this.enabled ? weight : 0;
  32349. return this.stopFading();
  32350. },
  32351. // return the weight considering fading and .enabled
  32352. getEffectiveWeight: function () {
  32353. return this._effectiveWeight;
  32354. },
  32355. fadeIn: function ( duration ) {
  32356. return this._scheduleFading( duration, 0, 1 );
  32357. },
  32358. fadeOut: function ( duration ) {
  32359. return this._scheduleFading( duration, 1, 0 );
  32360. },
  32361. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  32362. fadeOutAction.fadeOut( duration );
  32363. this.fadeIn( duration );
  32364. if ( warp ) {
  32365. var fadeInDuration = this._clip.duration,
  32366. fadeOutDuration = fadeOutAction._clip.duration,
  32367. startEndRatio = fadeOutDuration / fadeInDuration,
  32368. endStartRatio = fadeInDuration / fadeOutDuration;
  32369. fadeOutAction.warp( 1.0, startEndRatio, duration );
  32370. this.warp( endStartRatio, 1.0, duration );
  32371. }
  32372. return this;
  32373. },
  32374. crossFadeTo: function ( fadeInAction, duration, warp ) {
  32375. return fadeInAction.crossFadeFrom( this, duration, warp );
  32376. },
  32377. stopFading: function () {
  32378. var weightInterpolant = this._weightInterpolant;
  32379. if ( weightInterpolant !== null ) {
  32380. this._weightInterpolant = null;
  32381. this._mixer._takeBackControlInterpolant( weightInterpolant );
  32382. }
  32383. return this;
  32384. },
  32385. // Time Scale Control
  32386. // set the time scale stopping any scheduled warping
  32387. // although .paused = true yields an effective time scale of zero, this
  32388. // method does *not* change .paused, because it would be confusing
  32389. setEffectiveTimeScale: function ( timeScale ) {
  32390. this.timeScale = timeScale;
  32391. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  32392. return this.stopWarping();
  32393. },
  32394. // return the time scale considering warping and .paused
  32395. getEffectiveTimeScale: function () {
  32396. return this._effectiveTimeScale;
  32397. },
  32398. setDuration: function ( duration ) {
  32399. this.timeScale = this._clip.duration / duration;
  32400. return this.stopWarping();
  32401. },
  32402. syncWith: function ( action ) {
  32403. this.time = action.time;
  32404. this.timeScale = action.timeScale;
  32405. return this.stopWarping();
  32406. },
  32407. halt: function ( duration ) {
  32408. return this.warp( this._effectiveTimeScale, 0, duration );
  32409. },
  32410. warp: function ( startTimeScale, endTimeScale, duration ) {
  32411. var mixer = this._mixer,
  32412. now = mixer.time,
  32413. timeScale = this.timeScale;
  32414. var interpolant = this._timeScaleInterpolant;
  32415. if ( interpolant === null ) {
  32416. interpolant = mixer._lendControlInterpolant();
  32417. this._timeScaleInterpolant = interpolant;
  32418. }
  32419. var times = interpolant.parameterPositions,
  32420. values = interpolant.sampleValues;
  32421. times[ 0 ] = now;
  32422. times[ 1 ] = now + duration;
  32423. values[ 0 ] = startTimeScale / timeScale;
  32424. values[ 1 ] = endTimeScale / timeScale;
  32425. return this;
  32426. },
  32427. stopWarping: function () {
  32428. var timeScaleInterpolant = this._timeScaleInterpolant;
  32429. if ( timeScaleInterpolant !== null ) {
  32430. this._timeScaleInterpolant = null;
  32431. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  32432. }
  32433. return this;
  32434. },
  32435. // Object Accessors
  32436. getMixer: function () {
  32437. return this._mixer;
  32438. },
  32439. getClip: function () {
  32440. return this._clip;
  32441. },
  32442. getRoot: function () {
  32443. return this._localRoot || this._mixer._root;
  32444. },
  32445. // Interna
  32446. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  32447. // called by the mixer
  32448. if ( ! this.enabled ) {
  32449. // call ._updateWeight() to update ._effectiveWeight
  32450. this._updateWeight( time );
  32451. return;
  32452. }
  32453. var startTime = this._startTime;
  32454. if ( startTime !== null ) {
  32455. // check for scheduled start of action
  32456. var timeRunning = ( time - startTime ) * timeDirection;
  32457. if ( timeRunning < 0 || timeDirection === 0 ) {
  32458. return; // yet to come / don't decide when delta = 0
  32459. }
  32460. // start
  32461. this._startTime = null; // unschedule
  32462. deltaTime = timeDirection * timeRunning;
  32463. }
  32464. // apply time scale and advance time
  32465. deltaTime *= this._updateTimeScale( time );
  32466. var clipTime = this._updateTime( deltaTime );
  32467. // note: _updateTime may disable the action resulting in
  32468. // an effective weight of 0
  32469. var weight = this._updateWeight( time );
  32470. if ( weight > 0 ) {
  32471. var interpolants = this._interpolants;
  32472. var propertyMixers = this._propertyBindings;
  32473. switch ( this.blendMode ) {
  32474. case AdditiveAnimationBlendMode:
  32475. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  32476. interpolants[ j ].evaluate( clipTime );
  32477. propertyMixers[ j ].accumulateAdditive( weight );
  32478. }
  32479. break;
  32480. case NormalAnimationBlendMode:
  32481. default:
  32482. for ( var j$1 = 0, m$1 = interpolants.length; j$1 !== m$1; ++ j$1 ) {
  32483. interpolants[ j$1 ].evaluate( clipTime );
  32484. propertyMixers[ j$1 ].accumulate( accuIndex, weight );
  32485. }
  32486. }
  32487. }
  32488. },
  32489. _updateWeight: function ( time ) {
  32490. var weight = 0;
  32491. if ( this.enabled ) {
  32492. weight = this.weight;
  32493. var interpolant = this._weightInterpolant;
  32494. if ( interpolant !== null ) {
  32495. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  32496. weight *= interpolantValue;
  32497. if ( time > interpolant.parameterPositions[ 1 ] ) {
  32498. this.stopFading();
  32499. if ( interpolantValue === 0 ) {
  32500. // faded out, disable
  32501. this.enabled = false;
  32502. }
  32503. }
  32504. }
  32505. }
  32506. this._effectiveWeight = weight;
  32507. return weight;
  32508. },
  32509. _updateTimeScale: function ( time ) {
  32510. var timeScale = 0;
  32511. if ( ! this.paused ) {
  32512. timeScale = this.timeScale;
  32513. var interpolant = this._timeScaleInterpolant;
  32514. if ( interpolant !== null ) {
  32515. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  32516. timeScale *= interpolantValue;
  32517. if ( time > interpolant.parameterPositions[ 1 ] ) {
  32518. this.stopWarping();
  32519. if ( timeScale === 0 ) {
  32520. // motion has halted, pause
  32521. this.paused = true;
  32522. } else {
  32523. // warp done - apply final time scale
  32524. this.timeScale = timeScale;
  32525. }
  32526. }
  32527. }
  32528. }
  32529. this._effectiveTimeScale = timeScale;
  32530. return timeScale;
  32531. },
  32532. _updateTime: function ( deltaTime ) {
  32533. var duration = this._clip.duration;
  32534. var loop = this.loop;
  32535. var time = this.time + deltaTime;
  32536. var loopCount = this._loopCount;
  32537. var pingPong = ( loop === LoopPingPong );
  32538. if ( deltaTime === 0 ) {
  32539. if ( loopCount === - 1 ) { return time; }
  32540. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  32541. }
  32542. if ( loop === LoopOnce ) {
  32543. if ( loopCount === - 1 ) {
  32544. // just started
  32545. this._loopCount = 0;
  32546. this._setEndings( true, true, false );
  32547. }
  32548. handle_stop: {
  32549. if ( time >= duration ) {
  32550. time = duration;
  32551. } else if ( time < 0 ) {
  32552. time = 0;
  32553. } else {
  32554. this.time = time;
  32555. break handle_stop;
  32556. }
  32557. if ( this.clampWhenFinished ) { this.paused = true; }
  32558. else { this.enabled = false; }
  32559. this.time = time;
  32560. this._mixer.dispatchEvent( {
  32561. type: 'finished', action: this,
  32562. direction: deltaTime < 0 ? - 1 : 1
  32563. } );
  32564. }
  32565. } else { // repetitive Repeat or PingPong
  32566. if ( loopCount === - 1 ) {
  32567. // just started
  32568. if ( deltaTime >= 0 ) {
  32569. loopCount = 0;
  32570. this._setEndings( true, this.repetitions === 0, pingPong );
  32571. } else {
  32572. // when looping in reverse direction, the initial
  32573. // transition through zero counts as a repetition,
  32574. // so leave loopCount at -1
  32575. this._setEndings( this.repetitions === 0, true, pingPong );
  32576. }
  32577. }
  32578. if ( time >= duration || time < 0 ) {
  32579. // wrap around
  32580. var loopDelta = Math.floor( time / duration ); // signed
  32581. time -= duration * loopDelta;
  32582. loopCount += Math.abs( loopDelta );
  32583. var pending = this.repetitions - loopCount;
  32584. if ( pending <= 0 ) {
  32585. // have to stop (switch state, clamp time, fire event)
  32586. if ( this.clampWhenFinished ) { this.paused = true; }
  32587. else { this.enabled = false; }
  32588. time = deltaTime > 0 ? duration : 0;
  32589. this.time = time;
  32590. this._mixer.dispatchEvent( {
  32591. type: 'finished', action: this,
  32592. direction: deltaTime > 0 ? 1 : - 1
  32593. } );
  32594. } else {
  32595. // keep running
  32596. if ( pending === 1 ) {
  32597. // entering the last round
  32598. var atStart = deltaTime < 0;
  32599. this._setEndings( atStart, ! atStart, pingPong );
  32600. } else {
  32601. this._setEndings( false, false, pingPong );
  32602. }
  32603. this._loopCount = loopCount;
  32604. this.time = time;
  32605. this._mixer.dispatchEvent( {
  32606. type: 'loop', action: this, loopDelta: loopDelta
  32607. } );
  32608. }
  32609. } else {
  32610. this.time = time;
  32611. }
  32612. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  32613. // invert time for the "pong round"
  32614. return duration - time;
  32615. }
  32616. }
  32617. return time;
  32618. },
  32619. _setEndings: function ( atStart, atEnd, pingPong ) {
  32620. var settings = this._interpolantSettings;
  32621. if ( pingPong ) {
  32622. settings.endingStart = ZeroSlopeEnding;
  32623. settings.endingEnd = ZeroSlopeEnding;
  32624. } else {
  32625. // assuming for LoopOnce atStart == atEnd == true
  32626. if ( atStart ) {
  32627. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32628. } else {
  32629. settings.endingStart = WrapAroundEnding;
  32630. }
  32631. if ( atEnd ) {
  32632. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32633. } else {
  32634. settings.endingEnd = WrapAroundEnding;
  32635. }
  32636. }
  32637. },
  32638. _scheduleFading: function ( duration, weightNow, weightThen ) {
  32639. var mixer = this._mixer, now = mixer.time;
  32640. var interpolant = this._weightInterpolant;
  32641. if ( interpolant === null ) {
  32642. interpolant = mixer._lendControlInterpolant();
  32643. this._weightInterpolant = interpolant;
  32644. }
  32645. var times = interpolant.parameterPositions,
  32646. values = interpolant.sampleValues;
  32647. times[ 0 ] = now;
  32648. values[ 0 ] = weightNow;
  32649. times[ 1 ] = now + duration;
  32650. values[ 1 ] = weightThen;
  32651. return this;
  32652. }
  32653. } );
  32654. function AnimationMixer( root ) {
  32655. this._root = root;
  32656. this._initMemoryManager();
  32657. this._accuIndex = 0;
  32658. this.time = 0;
  32659. this.timeScale = 1.0;
  32660. }
  32661. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  32662. constructor: AnimationMixer,
  32663. _bindAction: function ( action, prototypeAction ) {
  32664. var root = action._localRoot || this._root,
  32665. tracks = action._clip.tracks,
  32666. nTracks = tracks.length,
  32667. bindings = action._propertyBindings,
  32668. interpolants = action._interpolants,
  32669. rootUuid = root.uuid,
  32670. bindingsByRoot = this._bindingsByRootAndName;
  32671. var bindingsByName = bindingsByRoot[ rootUuid ];
  32672. if ( bindingsByName === undefined ) {
  32673. bindingsByName = {};
  32674. bindingsByRoot[ rootUuid ] = bindingsByName;
  32675. }
  32676. for ( var i = 0; i !== nTracks; ++ i ) {
  32677. var track = tracks[ i ],
  32678. trackName = track.name;
  32679. var binding = bindingsByName[ trackName ];
  32680. if ( binding !== undefined ) {
  32681. bindings[ i ] = binding;
  32682. } else {
  32683. binding = bindings[ i ];
  32684. if ( binding !== undefined ) {
  32685. // existing binding, make sure the cache knows
  32686. if ( binding._cacheIndex === null ) {
  32687. ++ binding.referenceCount;
  32688. this._addInactiveBinding( binding, rootUuid, trackName );
  32689. }
  32690. continue;
  32691. }
  32692. var path = prototypeAction && prototypeAction.
  32693. _propertyBindings[ i ].binding.parsedPath;
  32694. binding = new PropertyMixer(
  32695. PropertyBinding.create( root, trackName, path ),
  32696. track.ValueTypeName, track.getValueSize() );
  32697. ++ binding.referenceCount;
  32698. this._addInactiveBinding( binding, rootUuid, trackName );
  32699. bindings[ i ] = binding;
  32700. }
  32701. interpolants[ i ].resultBuffer = binding.buffer;
  32702. }
  32703. },
  32704. _activateAction: function ( action ) {
  32705. if ( ! this._isActiveAction( action ) ) {
  32706. if ( action._cacheIndex === null ) {
  32707. // this action has been forgotten by the cache, but the user
  32708. // appears to be still using it -> rebind
  32709. var rootUuid = ( action._localRoot || this._root ).uuid,
  32710. clipUuid = action._clip.uuid,
  32711. actionsForClip = this._actionsByClip[ clipUuid ];
  32712. this._bindAction( action,
  32713. actionsForClip && actionsForClip.knownActions[ 0 ] );
  32714. this._addInactiveAction( action, clipUuid, rootUuid );
  32715. }
  32716. var bindings = action._propertyBindings;
  32717. // increment reference counts / sort out state
  32718. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32719. var binding = bindings[ i ];
  32720. if ( binding.useCount ++ === 0 ) {
  32721. this._lendBinding( binding );
  32722. binding.saveOriginalState();
  32723. }
  32724. }
  32725. this._lendAction( action );
  32726. }
  32727. },
  32728. _deactivateAction: function ( action ) {
  32729. if ( this._isActiveAction( action ) ) {
  32730. var bindings = action._propertyBindings;
  32731. // decrement reference counts / sort out state
  32732. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32733. var binding = bindings[ i ];
  32734. if ( -- binding.useCount === 0 ) {
  32735. binding.restoreOriginalState();
  32736. this._takeBackBinding( binding );
  32737. }
  32738. }
  32739. this._takeBackAction( action );
  32740. }
  32741. },
  32742. // Memory manager
  32743. _initMemoryManager: function () {
  32744. this._actions = []; // 'nActiveActions' followed by inactive ones
  32745. this._nActiveActions = 0;
  32746. this._actionsByClip = {};
  32747. // inside:
  32748. // {
  32749. // knownActions: Array< AnimationAction > - used as prototypes
  32750. // actionByRoot: AnimationAction - lookup
  32751. // }
  32752. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  32753. this._nActiveBindings = 0;
  32754. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  32755. this._controlInterpolants = []; // same game as above
  32756. this._nActiveControlInterpolants = 0;
  32757. var scope = this;
  32758. this.stats = {
  32759. actions: {
  32760. get total() {
  32761. return scope._actions.length;
  32762. },
  32763. get inUse() {
  32764. return scope._nActiveActions;
  32765. }
  32766. },
  32767. bindings: {
  32768. get total() {
  32769. return scope._bindings.length;
  32770. },
  32771. get inUse() {
  32772. return scope._nActiveBindings;
  32773. }
  32774. },
  32775. controlInterpolants: {
  32776. get total() {
  32777. return scope._controlInterpolants.length;
  32778. },
  32779. get inUse() {
  32780. return scope._nActiveControlInterpolants;
  32781. }
  32782. }
  32783. };
  32784. },
  32785. // Memory management for AnimationAction objects
  32786. _isActiveAction: function ( action ) {
  32787. var index = action._cacheIndex;
  32788. return index !== null && index < this._nActiveActions;
  32789. },
  32790. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  32791. var actions = this._actions,
  32792. actionsByClip = this._actionsByClip;
  32793. var actionsForClip = actionsByClip[ clipUuid ];
  32794. if ( actionsForClip === undefined ) {
  32795. actionsForClip = {
  32796. knownActions: [ action ],
  32797. actionByRoot: {}
  32798. };
  32799. action._byClipCacheIndex = 0;
  32800. actionsByClip[ clipUuid ] = actionsForClip;
  32801. } else {
  32802. var knownActions = actionsForClip.knownActions;
  32803. action._byClipCacheIndex = knownActions.length;
  32804. knownActions.push( action );
  32805. }
  32806. action._cacheIndex = actions.length;
  32807. actions.push( action );
  32808. actionsForClip.actionByRoot[ rootUuid ] = action;
  32809. },
  32810. _removeInactiveAction: function ( action ) {
  32811. var actions = this._actions,
  32812. lastInactiveAction = actions[ actions.length - 1 ],
  32813. cacheIndex = action._cacheIndex;
  32814. lastInactiveAction._cacheIndex = cacheIndex;
  32815. actions[ cacheIndex ] = lastInactiveAction;
  32816. actions.pop();
  32817. action._cacheIndex = null;
  32818. var clipUuid = action._clip.uuid,
  32819. actionsByClip = this._actionsByClip,
  32820. actionsForClip = actionsByClip[ clipUuid ],
  32821. knownActionsForClip = actionsForClip.knownActions,
  32822. lastKnownAction =
  32823. knownActionsForClip[ knownActionsForClip.length - 1 ],
  32824. byClipCacheIndex = action._byClipCacheIndex;
  32825. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  32826. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  32827. knownActionsForClip.pop();
  32828. action._byClipCacheIndex = null;
  32829. var actionByRoot = actionsForClip.actionByRoot,
  32830. rootUuid = ( action._localRoot || this._root ).uuid;
  32831. delete actionByRoot[ rootUuid ];
  32832. if ( knownActionsForClip.length === 0 ) {
  32833. delete actionsByClip[ clipUuid ];
  32834. }
  32835. this._removeInactiveBindingsForAction( action );
  32836. },
  32837. _removeInactiveBindingsForAction: function ( action ) {
  32838. var bindings = action._propertyBindings;
  32839. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32840. var binding = bindings[ i ];
  32841. if ( -- binding.referenceCount === 0 ) {
  32842. this._removeInactiveBinding( binding );
  32843. }
  32844. }
  32845. },
  32846. _lendAction: function ( action ) {
  32847. // [ active actions | inactive actions ]
  32848. // [ active actions >| inactive actions ]
  32849. // s a
  32850. // <-swap->
  32851. // a s
  32852. var actions = this._actions,
  32853. prevIndex = action._cacheIndex,
  32854. lastActiveIndex = this._nActiveActions ++,
  32855. firstInactiveAction = actions[ lastActiveIndex ];
  32856. action._cacheIndex = lastActiveIndex;
  32857. actions[ lastActiveIndex ] = action;
  32858. firstInactiveAction._cacheIndex = prevIndex;
  32859. actions[ prevIndex ] = firstInactiveAction;
  32860. },
  32861. _takeBackAction: function ( action ) {
  32862. // [ active actions | inactive actions ]
  32863. // [ active actions |< inactive actions ]
  32864. // a s
  32865. // <-swap->
  32866. // s a
  32867. var actions = this._actions,
  32868. prevIndex = action._cacheIndex,
  32869. firstInactiveIndex = -- this._nActiveActions,
  32870. lastActiveAction = actions[ firstInactiveIndex ];
  32871. action._cacheIndex = firstInactiveIndex;
  32872. actions[ firstInactiveIndex ] = action;
  32873. lastActiveAction._cacheIndex = prevIndex;
  32874. actions[ prevIndex ] = lastActiveAction;
  32875. },
  32876. // Memory management for PropertyMixer objects
  32877. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  32878. var bindingsByRoot = this._bindingsByRootAndName,
  32879. bindings = this._bindings;
  32880. var bindingByName = bindingsByRoot[ rootUuid ];
  32881. if ( bindingByName === undefined ) {
  32882. bindingByName = {};
  32883. bindingsByRoot[ rootUuid ] = bindingByName;
  32884. }
  32885. bindingByName[ trackName ] = binding;
  32886. binding._cacheIndex = bindings.length;
  32887. bindings.push( binding );
  32888. },
  32889. _removeInactiveBinding: function ( binding ) {
  32890. var bindings = this._bindings,
  32891. propBinding = binding.binding,
  32892. rootUuid = propBinding.rootNode.uuid,
  32893. trackName = propBinding.path,
  32894. bindingsByRoot = this._bindingsByRootAndName,
  32895. bindingByName = bindingsByRoot[ rootUuid ],
  32896. lastInactiveBinding = bindings[ bindings.length - 1 ],
  32897. cacheIndex = binding._cacheIndex;
  32898. lastInactiveBinding._cacheIndex = cacheIndex;
  32899. bindings[ cacheIndex ] = lastInactiveBinding;
  32900. bindings.pop();
  32901. delete bindingByName[ trackName ];
  32902. if ( Object.keys( bindingByName ).length === 0 ) {
  32903. delete bindingsByRoot[ rootUuid ];
  32904. }
  32905. },
  32906. _lendBinding: function ( binding ) {
  32907. var bindings = this._bindings,
  32908. prevIndex = binding._cacheIndex,
  32909. lastActiveIndex = this._nActiveBindings ++,
  32910. firstInactiveBinding = bindings[ lastActiveIndex ];
  32911. binding._cacheIndex = lastActiveIndex;
  32912. bindings[ lastActiveIndex ] = binding;
  32913. firstInactiveBinding._cacheIndex = prevIndex;
  32914. bindings[ prevIndex ] = firstInactiveBinding;
  32915. },
  32916. _takeBackBinding: function ( binding ) {
  32917. var bindings = this._bindings,
  32918. prevIndex = binding._cacheIndex,
  32919. firstInactiveIndex = -- this._nActiveBindings,
  32920. lastActiveBinding = bindings[ firstInactiveIndex ];
  32921. binding._cacheIndex = firstInactiveIndex;
  32922. bindings[ firstInactiveIndex ] = binding;
  32923. lastActiveBinding._cacheIndex = prevIndex;
  32924. bindings[ prevIndex ] = lastActiveBinding;
  32925. },
  32926. // Memory management of Interpolants for weight and time scale
  32927. _lendControlInterpolant: function () {
  32928. var interpolants = this._controlInterpolants,
  32929. lastActiveIndex = this._nActiveControlInterpolants ++;
  32930. var interpolant = interpolants[ lastActiveIndex ];
  32931. if ( interpolant === undefined ) {
  32932. interpolant = new LinearInterpolant(
  32933. new Float32Array( 2 ), new Float32Array( 2 ),
  32934. 1, this._controlInterpolantsResultBuffer );
  32935. interpolant.__cacheIndex = lastActiveIndex;
  32936. interpolants[ lastActiveIndex ] = interpolant;
  32937. }
  32938. return interpolant;
  32939. },
  32940. _takeBackControlInterpolant: function ( interpolant ) {
  32941. var interpolants = this._controlInterpolants,
  32942. prevIndex = interpolant.__cacheIndex,
  32943. firstInactiveIndex = -- this._nActiveControlInterpolants,
  32944. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  32945. interpolant.__cacheIndex = firstInactiveIndex;
  32946. interpolants[ firstInactiveIndex ] = interpolant;
  32947. lastActiveInterpolant.__cacheIndex = prevIndex;
  32948. interpolants[ prevIndex ] = lastActiveInterpolant;
  32949. },
  32950. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  32951. // return an action for a clip optionally using a custom root target
  32952. // object (this method allocates a lot of dynamic memory in case a
  32953. // previously unknown clip/root combination is specified)
  32954. clipAction: function ( clip, optionalRoot, blendMode ) {
  32955. var root = optionalRoot || this._root,
  32956. rootUuid = root.uuid;
  32957. var clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  32958. var clipUuid = clipObject !== null ? clipObject.uuid : clip;
  32959. var actionsForClip = this._actionsByClip[ clipUuid ],
  32960. prototypeAction = null;
  32961. if ( blendMode === undefined ) {
  32962. if ( clipObject !== null ) {
  32963. blendMode = clipObject.blendMode;
  32964. } else {
  32965. blendMode = NormalAnimationBlendMode;
  32966. }
  32967. }
  32968. if ( actionsForClip !== undefined ) {
  32969. var existingAction = actionsForClip.actionByRoot[ rootUuid ];
  32970. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  32971. return existingAction;
  32972. }
  32973. // we know the clip, so we don't have to parse all
  32974. // the bindings again but can just copy
  32975. prototypeAction = actionsForClip.knownActions[ 0 ];
  32976. // also, take the clip from the prototype action
  32977. if ( clipObject === null )
  32978. { clipObject = prototypeAction._clip; }
  32979. }
  32980. // clip must be known when specified via string
  32981. if ( clipObject === null ) { return null; }
  32982. // allocate all resources required to run it
  32983. var newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  32984. this._bindAction( newAction, prototypeAction );
  32985. // and make the action known to the memory manager
  32986. this._addInactiveAction( newAction, clipUuid, rootUuid );
  32987. return newAction;
  32988. },
  32989. // get an existing action
  32990. existingAction: function ( clip, optionalRoot ) {
  32991. var root = optionalRoot || this._root,
  32992. rootUuid = root.uuid,
  32993. clipObject = typeof clip === 'string' ?
  32994. AnimationClip.findByName( root, clip ) : clip,
  32995. clipUuid = clipObject ? clipObject.uuid : clip,
  32996. actionsForClip = this._actionsByClip[ clipUuid ];
  32997. if ( actionsForClip !== undefined ) {
  32998. return actionsForClip.actionByRoot[ rootUuid ] || null;
  32999. }
  33000. return null;
  33001. },
  33002. // deactivates all previously scheduled actions
  33003. stopAllAction: function () {
  33004. var actions = this._actions,
  33005. nActions = this._nActiveActions;
  33006. for ( var i = nActions - 1; i >= 0; -- i ) {
  33007. actions[ i ].stop();
  33008. }
  33009. return this;
  33010. },
  33011. // advance the time and update apply the animation
  33012. update: function ( deltaTime ) {
  33013. deltaTime *= this.timeScale;
  33014. var actions = this._actions,
  33015. nActions = this._nActiveActions,
  33016. time = this.time += deltaTime,
  33017. timeDirection = Math.sign( deltaTime ),
  33018. accuIndex = this._accuIndex ^= 1;
  33019. // run active actions
  33020. for ( var i = 0; i !== nActions; ++ i ) {
  33021. var action = actions[ i ];
  33022. action._update( time, deltaTime, timeDirection, accuIndex );
  33023. }
  33024. // update scene graph
  33025. var bindings = this._bindings,
  33026. nBindings = this._nActiveBindings;
  33027. for ( var i$1 = 0; i$1 !== nBindings; ++ i$1 ) {
  33028. bindings[ i$1 ].apply( accuIndex );
  33029. }
  33030. return this;
  33031. },
  33032. // Allows you to seek to a specific time in an animation.
  33033. setTime: function ( timeInSeconds ) {
  33034. this.time = 0; // Zero out time attribute for AnimationMixer object;
  33035. for ( var i = 0; i < this._actions.length; i ++ ) {
  33036. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  33037. }
  33038. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  33039. },
  33040. // return this mixer's root target object
  33041. getRoot: function () {
  33042. return this._root;
  33043. },
  33044. // free all resources specific to a particular clip
  33045. uncacheClip: function ( clip ) {
  33046. var actions = this._actions,
  33047. clipUuid = clip.uuid,
  33048. actionsByClip = this._actionsByClip,
  33049. actionsForClip = actionsByClip[ clipUuid ];
  33050. if ( actionsForClip !== undefined ) {
  33051. // note: just calling _removeInactiveAction would mess up the
  33052. // iteration state and also require updating the state we can
  33053. // just throw away
  33054. var actionsToRemove = actionsForClip.knownActions;
  33055. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  33056. var action = actionsToRemove[ i ];
  33057. this._deactivateAction( action );
  33058. var cacheIndex = action._cacheIndex,
  33059. lastInactiveAction = actions[ actions.length - 1 ];
  33060. action._cacheIndex = null;
  33061. action._byClipCacheIndex = null;
  33062. lastInactiveAction._cacheIndex = cacheIndex;
  33063. actions[ cacheIndex ] = lastInactiveAction;
  33064. actions.pop();
  33065. this._removeInactiveBindingsForAction( action );
  33066. }
  33067. delete actionsByClip[ clipUuid ];
  33068. }
  33069. },
  33070. // free all resources specific to a particular root target object
  33071. uncacheRoot: function ( root ) {
  33072. var rootUuid = root.uuid,
  33073. actionsByClip = this._actionsByClip;
  33074. for ( var clipUuid in actionsByClip ) {
  33075. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  33076. action = actionByRoot[ rootUuid ];
  33077. if ( action !== undefined ) {
  33078. this._deactivateAction( action );
  33079. this._removeInactiveAction( action );
  33080. }
  33081. }
  33082. var bindingsByRoot = this._bindingsByRootAndName,
  33083. bindingByName = bindingsByRoot[ rootUuid ];
  33084. if ( bindingByName !== undefined ) {
  33085. for ( var trackName in bindingByName ) {
  33086. var binding = bindingByName[ trackName ];
  33087. binding.restoreOriginalState();
  33088. this._removeInactiveBinding( binding );
  33089. }
  33090. }
  33091. },
  33092. // remove a targeted clip from the cache
  33093. uncacheAction: function ( clip, optionalRoot ) {
  33094. var action = this.existingAction( clip, optionalRoot );
  33095. if ( action !== null ) {
  33096. this._deactivateAction( action );
  33097. this._removeInactiveAction( action );
  33098. }
  33099. }
  33100. } );
  33101. function Uniform( value ) {
  33102. if ( typeof value === 'string' ) {
  33103. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  33104. value = arguments[ 1 ];
  33105. }
  33106. this.value = value;
  33107. }
  33108. Uniform.prototype.clone = function () {
  33109. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  33110. };
  33111. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  33112. InterleavedBuffer.call( this, array, stride );
  33113. this.meshPerAttribute = meshPerAttribute || 1;
  33114. }
  33115. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  33116. constructor: InstancedInterleavedBuffer,
  33117. isInstancedInterleavedBuffer: true,
  33118. copy: function ( source ) {
  33119. InterleavedBuffer.prototype.copy.call( this, source );
  33120. this.meshPerAttribute = source.meshPerAttribute;
  33121. return this;
  33122. },
  33123. clone: function ( data ) {
  33124. var ib = InterleavedBuffer.prototype.clone.call( this, data );
  33125. ib.meshPerAttribute = this.meshPerAttribute;
  33126. return ib;
  33127. },
  33128. toJSON: function ( data ) {
  33129. var json = InterleavedBuffer.prototype.toJSON.call( this, data );
  33130. json.isInstancedInterleavedBuffer = true;
  33131. json.meshPerAttribute = this.meshPerAttribute;
  33132. return json;
  33133. }
  33134. } );
  33135. function Raycaster( origin, direction, near, far ) {
  33136. this.ray = new Ray( origin, direction );
  33137. // direction is assumed to be normalized (for accurate distance calculations)
  33138. this.near = near || 0;
  33139. this.far = far || Infinity;
  33140. this.camera = null;
  33141. this.layers = new Layers();
  33142. this.params = {
  33143. Mesh: {},
  33144. Line: { threshold: 1 },
  33145. LOD: {},
  33146. Points: { threshold: 1 },
  33147. Sprite: {}
  33148. };
  33149. Object.defineProperties( this.params, {
  33150. PointCloud: {
  33151. get: function () {
  33152. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  33153. return this.Points;
  33154. }
  33155. }
  33156. } );
  33157. }
  33158. function ascSort( a, b ) {
  33159. return a.distance - b.distance;
  33160. }
  33161. function intersectObject( object, raycaster, intersects, recursive ) {
  33162. if ( object.layers.test( raycaster.layers ) ) {
  33163. object.raycast( raycaster, intersects );
  33164. }
  33165. if ( recursive === true ) {
  33166. var children = object.children;
  33167. for ( var i = 0, l = children.length; i < l; i ++ ) {
  33168. intersectObject( children[ i ], raycaster, intersects, true );
  33169. }
  33170. }
  33171. }
  33172. Object.assign( Raycaster.prototype, {
  33173. set: function ( origin, direction ) {
  33174. // direction is assumed to be normalized (for accurate distance calculations)
  33175. this.ray.set( origin, direction );
  33176. },
  33177. setFromCamera: function ( coords, camera ) {
  33178. if ( ( camera && camera.isPerspectiveCamera ) ) {
  33179. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  33180. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  33181. this.camera = camera;
  33182. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  33183. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  33184. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  33185. this.camera = camera;
  33186. } else {
  33187. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  33188. }
  33189. },
  33190. intersectObject: function ( object, recursive, optionalTarget ) {
  33191. var intersects = optionalTarget || [];
  33192. intersectObject( object, this, intersects, recursive );
  33193. intersects.sort( ascSort );
  33194. return intersects;
  33195. },
  33196. intersectObjects: function ( objects, recursive, optionalTarget ) {
  33197. var intersects = optionalTarget || [];
  33198. if ( Array.isArray( objects ) === false ) {
  33199. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  33200. return intersects;
  33201. }
  33202. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  33203. intersectObject( objects[ i ], this, intersects, recursive );
  33204. }
  33205. intersects.sort( ascSort );
  33206. return intersects;
  33207. }
  33208. } );
  33209. /**
  33210. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  33211. *
  33212. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  33213. * The azimuthal angle (theta) is measured from the positive z-axis.
  33214. */
  33215. var Spherical = function Spherical( radius, phi, theta ) {
  33216. if ( radius === void 0 ) radius = 1;
  33217. if ( phi === void 0 ) phi = 0;
  33218. if ( theta === void 0 ) theta = 0;
  33219. this.radius = radius;
  33220. this.phi = phi; // polar angle
  33221. this.theta = theta; // azimuthal angle
  33222. return this;
  33223. };
  33224. Spherical.prototype.set = function set ( radius, phi, theta ) {
  33225. this.radius = radius;
  33226. this.phi = phi;
  33227. this.theta = theta;
  33228. return this;
  33229. };
  33230. Spherical.prototype.clone = function clone () {
  33231. return new this.constructor().copy( this );
  33232. };
  33233. Spherical.prototype.copy = function copy ( other ) {
  33234. this.radius = other.radius;
  33235. this.phi = other.phi;
  33236. this.theta = other.theta;
  33237. return this;
  33238. };
  33239. // restrict phi to be betwee EPS and PI-EPS
  33240. Spherical.prototype.makeSafe = function makeSafe () {
  33241. var EPS = 0.000001;
  33242. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  33243. return this;
  33244. };
  33245. Spherical.prototype.setFromVector3 = function setFromVector3 ( v ) {
  33246. return this.setFromCartesianCoords( v.x, v.y, v.z );
  33247. };
  33248. Spherical.prototype.setFromCartesianCoords = function setFromCartesianCoords ( x, y, z ) {
  33249. this.radius = Math.sqrt( x * x + y * y + z * z );
  33250. if ( this.radius === 0 ) {
  33251. this.theta = 0;
  33252. this.phi = 0;
  33253. } else {
  33254. this.theta = Math.atan2( x, z );
  33255. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  33256. }
  33257. return this;
  33258. };
  33259. /**
  33260. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  33261. */
  33262. function Cylindrical( radius, theta, y ) {
  33263. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  33264. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  33265. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  33266. return this;
  33267. }
  33268. Object.assign( Cylindrical.prototype, {
  33269. set: function ( radius, theta, y ) {
  33270. this.radius = radius;
  33271. this.theta = theta;
  33272. this.y = y;
  33273. return this;
  33274. },
  33275. clone: function () {
  33276. return new this.constructor().copy( this );
  33277. },
  33278. copy: function ( other ) {
  33279. this.radius = other.radius;
  33280. this.theta = other.theta;
  33281. this.y = other.y;
  33282. return this;
  33283. },
  33284. setFromVector3: function ( v ) {
  33285. return this.setFromCartesianCoords( v.x, v.y, v.z );
  33286. },
  33287. setFromCartesianCoords: function ( x, y, z ) {
  33288. this.radius = Math.sqrt( x * x + z * z );
  33289. this.theta = Math.atan2( x, z );
  33290. this.y = y;
  33291. return this;
  33292. }
  33293. } );
  33294. var _vector$7 = new Vector2();
  33295. function Box2( min, max ) {
  33296. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  33297. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  33298. }
  33299. Object.assign( Box2.prototype, {
  33300. set: function ( min, max ) {
  33301. this.min.copy( min );
  33302. this.max.copy( max );
  33303. return this;
  33304. },
  33305. setFromPoints: function ( points ) {
  33306. this.makeEmpty();
  33307. for ( var i = 0, il = points.length; i < il; i ++ ) {
  33308. this.expandByPoint( points[ i ] );
  33309. }
  33310. return this;
  33311. },
  33312. setFromCenterAndSize: function ( center, size ) {
  33313. var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
  33314. this.min.copy( center ).sub( halfSize );
  33315. this.max.copy( center ).add( halfSize );
  33316. return this;
  33317. },
  33318. clone: function () {
  33319. return new this.constructor().copy( this );
  33320. },
  33321. copy: function ( box ) {
  33322. this.min.copy( box.min );
  33323. this.max.copy( box.max );
  33324. return this;
  33325. },
  33326. makeEmpty: function () {
  33327. this.min.x = this.min.y = + Infinity;
  33328. this.max.x = this.max.y = - Infinity;
  33329. return this;
  33330. },
  33331. isEmpty: function () {
  33332. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  33333. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  33334. },
  33335. getCenter: function ( target ) {
  33336. if ( target === undefined ) {
  33337. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  33338. target = new Vector2();
  33339. }
  33340. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  33341. },
  33342. getSize: function ( target ) {
  33343. if ( target === undefined ) {
  33344. console.warn( 'THREE.Box2: .getSize() target is now required' );
  33345. target = new Vector2();
  33346. }
  33347. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  33348. },
  33349. expandByPoint: function ( point ) {
  33350. this.min.min( point );
  33351. this.max.max( point );
  33352. return this;
  33353. },
  33354. expandByVector: function ( vector ) {
  33355. this.min.sub( vector );
  33356. this.max.add( vector );
  33357. return this;
  33358. },
  33359. expandByScalar: function ( scalar ) {
  33360. this.min.addScalar( - scalar );
  33361. this.max.addScalar( scalar );
  33362. return this;
  33363. },
  33364. containsPoint: function ( point ) {
  33365. return point.x < this.min.x || point.x > this.max.x ||
  33366. point.y < this.min.y || point.y > this.max.y ? false : true;
  33367. },
  33368. containsBox: function ( box ) {
  33369. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  33370. this.min.y <= box.min.y && box.max.y <= this.max.y;
  33371. },
  33372. getParameter: function ( point, target ) {
  33373. // This can potentially have a divide by zero if the box
  33374. // has a size dimension of 0.
  33375. if ( target === undefined ) {
  33376. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  33377. target = new Vector2();
  33378. }
  33379. return target.set(
  33380. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  33381. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  33382. );
  33383. },
  33384. intersectsBox: function ( box ) {
  33385. // using 4 splitting planes to rule out intersections
  33386. return box.max.x < this.min.x || box.min.x > this.max.x ||
  33387. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  33388. },
  33389. clampPoint: function ( point, target ) {
  33390. if ( target === undefined ) {
  33391. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  33392. target = new Vector2();
  33393. }
  33394. return target.copy( point ).clamp( this.min, this.max );
  33395. },
  33396. distanceToPoint: function ( point ) {
  33397. var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
  33398. return clampedPoint.sub( point ).length();
  33399. },
  33400. intersect: function ( box ) {
  33401. this.min.max( box.min );
  33402. this.max.min( box.max );
  33403. return this;
  33404. },
  33405. union: function ( box ) {
  33406. this.min.min( box.min );
  33407. this.max.max( box.max );
  33408. return this;
  33409. },
  33410. translate: function ( offset ) {
  33411. this.min.add( offset );
  33412. this.max.add( offset );
  33413. return this;
  33414. },
  33415. equals: function ( box ) {
  33416. return box.min.equals( this.min ) && box.max.equals( this.max );
  33417. }
  33418. } );
  33419. var _startP = new Vector3();
  33420. var _startEnd = new Vector3();
  33421. function Line3( start, end ) {
  33422. this.start = ( start !== undefined ) ? start : new Vector3();
  33423. this.end = ( end !== undefined ) ? end : new Vector3();
  33424. }
  33425. Object.assign( Line3.prototype, {
  33426. set: function ( start, end ) {
  33427. this.start.copy( start );
  33428. this.end.copy( end );
  33429. return this;
  33430. },
  33431. clone: function () {
  33432. return new this.constructor().copy( this );
  33433. },
  33434. copy: function ( line ) {
  33435. this.start.copy( line.start );
  33436. this.end.copy( line.end );
  33437. return this;
  33438. },
  33439. getCenter: function ( target ) {
  33440. if ( target === undefined ) {
  33441. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  33442. target = new Vector3();
  33443. }
  33444. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  33445. },
  33446. delta: function ( target ) {
  33447. if ( target === undefined ) {
  33448. console.warn( 'THREE.Line3: .delta() target is now required' );
  33449. target = new Vector3();
  33450. }
  33451. return target.subVectors( this.end, this.start );
  33452. },
  33453. distanceSq: function () {
  33454. return this.start.distanceToSquared( this.end );
  33455. },
  33456. distance: function () {
  33457. return this.start.distanceTo( this.end );
  33458. },
  33459. at: function ( t, target ) {
  33460. if ( target === undefined ) {
  33461. console.warn( 'THREE.Line3: .at() target is now required' );
  33462. target = new Vector3();
  33463. }
  33464. return this.delta( target ).multiplyScalar( t ).add( this.start );
  33465. },
  33466. closestPointToPointParameter: function ( point, clampToLine ) {
  33467. _startP.subVectors( point, this.start );
  33468. _startEnd.subVectors( this.end, this.start );
  33469. var startEnd2 = _startEnd.dot( _startEnd );
  33470. var startEnd_startP = _startEnd.dot( _startP );
  33471. var t = startEnd_startP / startEnd2;
  33472. if ( clampToLine ) {
  33473. t = MathUtils.clamp( t, 0, 1 );
  33474. }
  33475. return t;
  33476. },
  33477. closestPointToPoint: function ( point, clampToLine, target ) {
  33478. var t = this.closestPointToPointParameter( point, clampToLine );
  33479. if ( target === undefined ) {
  33480. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  33481. target = new Vector3();
  33482. }
  33483. return this.delta( target ).multiplyScalar( t ).add( this.start );
  33484. },
  33485. applyMatrix4: function ( matrix ) {
  33486. this.start.applyMatrix4( matrix );
  33487. this.end.applyMatrix4( matrix );
  33488. return this;
  33489. },
  33490. equals: function ( line ) {
  33491. return line.start.equals( this.start ) && line.end.equals( this.end );
  33492. }
  33493. } );
  33494. function ImmediateRenderObject( material ) {
  33495. Object3D.call( this );
  33496. this.material = material;
  33497. this.render = function ( /* renderCallback */ ) {};
  33498. this.hasPositions = false;
  33499. this.hasNormals = false;
  33500. this.hasColors = false;
  33501. this.hasUvs = false;
  33502. this.positionArray = null;
  33503. this.normalArray = null;
  33504. this.colorArray = null;
  33505. this.uvArray = null;
  33506. this.count = 0;
  33507. }
  33508. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  33509. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  33510. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  33511. var _vector$8 = new Vector3();
  33512. function SpotLightHelper( light, color ) {
  33513. Object3D.call( this );
  33514. this.light = light;
  33515. this.light.updateMatrixWorld();
  33516. this.matrix = light.matrixWorld;
  33517. this.matrixAutoUpdate = false;
  33518. this.color = color;
  33519. var geometry = new BufferGeometry();
  33520. var positions = [
  33521. 0, 0, 0, 0, 0, 1,
  33522. 0, 0, 0, 1, 0, 1,
  33523. 0, 0, 0, - 1, 0, 1,
  33524. 0, 0, 0, 0, 1, 1,
  33525. 0, 0, 0, 0, - 1, 1
  33526. ];
  33527. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  33528. var p1 = ( i / l ) * Math.PI * 2;
  33529. var p2 = ( j / l ) * Math.PI * 2;
  33530. positions.push(
  33531. Math.cos( p1 ), Math.sin( p1 ), 1,
  33532. Math.cos( p2 ), Math.sin( p2 ), 1
  33533. );
  33534. }
  33535. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  33536. var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  33537. this.cone = new LineSegments( geometry, material );
  33538. this.add( this.cone );
  33539. this.update();
  33540. }
  33541. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  33542. SpotLightHelper.prototype.constructor = SpotLightHelper;
  33543. SpotLightHelper.prototype.dispose = function () {
  33544. this.cone.geometry.dispose();
  33545. this.cone.material.dispose();
  33546. };
  33547. SpotLightHelper.prototype.update = function () {
  33548. this.light.updateMatrixWorld();
  33549. var coneLength = this.light.distance ? this.light.distance : 1000;
  33550. var coneWidth = coneLength * Math.tan( this.light.angle );
  33551. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  33552. _vector$8.setFromMatrixPosition( this.light.target.matrixWorld );
  33553. this.cone.lookAt( _vector$8 );
  33554. if ( this.color !== undefined ) {
  33555. this.cone.material.color.set( this.color );
  33556. } else {
  33557. this.cone.material.color.copy( this.light.color );
  33558. }
  33559. };
  33560. var _vector$9 = new Vector3();
  33561. var _boneMatrix = new Matrix4();
  33562. var _matrixWorldInv = new Matrix4();
  33563. function getBoneList( object ) {
  33564. var boneList = [];
  33565. if ( object && object.isBone ) {
  33566. boneList.push( object );
  33567. }
  33568. for ( var i = 0; i < object.children.length; i ++ ) {
  33569. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  33570. }
  33571. return boneList;
  33572. }
  33573. function SkeletonHelper( object ) {
  33574. var bones = getBoneList( object );
  33575. var geometry = new BufferGeometry();
  33576. var vertices = [];
  33577. var colors = [];
  33578. var color1 = new Color( 0, 0, 1 );
  33579. var color2 = new Color( 0, 1, 0 );
  33580. for ( var i = 0; i < bones.length; i ++ ) {
  33581. var bone = bones[ i ];
  33582. if ( bone.parent && bone.parent.isBone ) {
  33583. vertices.push( 0, 0, 0 );
  33584. vertices.push( 0, 0, 0 );
  33585. colors.push( color1.r, color1.g, color1.b );
  33586. colors.push( color2.r, color2.g, color2.b );
  33587. }
  33588. }
  33589. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33590. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33591. var material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  33592. LineSegments.call( this, geometry, material );
  33593. this.type = 'SkeletonHelper';
  33594. this.root = object;
  33595. this.bones = bones;
  33596. this.matrix = object.matrixWorld;
  33597. this.matrixAutoUpdate = false;
  33598. }
  33599. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  33600. SkeletonHelper.prototype.constructor = SkeletonHelper;
  33601. SkeletonHelper.prototype.isSkeletonHelper = true;
  33602. SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {
  33603. var bones = this.bones;
  33604. var geometry = this.geometry;
  33605. var position = geometry.getAttribute( 'position' );
  33606. _matrixWorldInv.getInverse( this.root.matrixWorld );
  33607. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  33608. var bone = bones[ i ];
  33609. if ( bone.parent && bone.parent.isBone ) {
  33610. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  33611. _vector$9.setFromMatrixPosition( _boneMatrix );
  33612. position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );
  33613. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  33614. _vector$9.setFromMatrixPosition( _boneMatrix );
  33615. position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );
  33616. j += 2;
  33617. }
  33618. }
  33619. geometry.getAttribute( 'position' ).needsUpdate = true;
  33620. Object3D.prototype.updateMatrixWorld.call( this, force );
  33621. };
  33622. function PointLightHelper( light, sphereSize, color ) {
  33623. this.light = light;
  33624. this.light.updateMatrixWorld();
  33625. this.color = color;
  33626. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  33627. var material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  33628. Mesh.call( this, geometry, material );
  33629. this.type = 'PointLightHelper';
  33630. this.matrix = this.light.matrixWorld;
  33631. this.matrixAutoUpdate = false;
  33632. this.update();
  33633. /*
  33634. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  33635. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  33636. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  33637. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  33638. const d = light.distance;
  33639. if ( d === 0.0 ) {
  33640. this.lightDistance.visible = false;
  33641. } else {
  33642. this.lightDistance.scale.set( d, d, d );
  33643. }
  33644. this.add( this.lightDistance );
  33645. */
  33646. }
  33647. PointLightHelper.prototype = Object.create( Mesh.prototype );
  33648. PointLightHelper.prototype.constructor = PointLightHelper;
  33649. PointLightHelper.prototype.dispose = function () {
  33650. this.geometry.dispose();
  33651. this.material.dispose();
  33652. };
  33653. PointLightHelper.prototype.update = function () {
  33654. if ( this.color !== undefined ) {
  33655. this.material.color.set( this.color );
  33656. } else {
  33657. this.material.color.copy( this.light.color );
  33658. }
  33659. /*
  33660. const d = this.light.distance;
  33661. if ( d === 0.0 ) {
  33662. this.lightDistance.visible = false;
  33663. } else {
  33664. this.lightDistance.visible = true;
  33665. this.lightDistance.scale.set( d, d, d );
  33666. }
  33667. */
  33668. };
  33669. var _vector$a = new Vector3();
  33670. var _color1 = new Color();
  33671. var _color2 = new Color();
  33672. function HemisphereLightHelper( light, size, color ) {
  33673. Object3D.call( this );
  33674. this.light = light;
  33675. this.light.updateMatrixWorld();
  33676. this.matrix = light.matrixWorld;
  33677. this.matrixAutoUpdate = false;
  33678. this.color = color;
  33679. var geometry = new OctahedronBufferGeometry( size );
  33680. geometry.rotateY( Math.PI * 0.5 );
  33681. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  33682. if ( this.color === undefined ) { this.material.vertexColors = true; }
  33683. var position = geometry.getAttribute( 'position' );
  33684. var colors = new Float32Array( position.count * 3 );
  33685. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  33686. this.add( new Mesh( geometry, this.material ) );
  33687. this.update();
  33688. }
  33689. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  33690. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  33691. HemisphereLightHelper.prototype.dispose = function () {
  33692. this.children[ 0 ].geometry.dispose();
  33693. this.children[ 0 ].material.dispose();
  33694. };
  33695. HemisphereLightHelper.prototype.update = function () {
  33696. var mesh = this.children[ 0 ];
  33697. if ( this.color !== undefined ) {
  33698. this.material.color.set( this.color );
  33699. } else {
  33700. var colors = mesh.geometry.getAttribute( 'color' );
  33701. _color1.copy( this.light.color );
  33702. _color2.copy( this.light.groundColor );
  33703. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  33704. var color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  33705. colors.setXYZ( i, color.r, color.g, color.b );
  33706. }
  33707. colors.needsUpdate = true;
  33708. }
  33709. mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  33710. };
  33711. function GridHelper( size, divisions, color1, color2 ) {
  33712. size = size || 10;
  33713. divisions = divisions || 10;
  33714. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33715. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33716. var center = divisions / 2;
  33717. var step = size / divisions;
  33718. var halfSize = size / 2;
  33719. var vertices = [], colors = [];
  33720. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  33721. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  33722. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  33723. var color = i === center ? color1 : color2;
  33724. color.toArray( colors, j ); j += 3;
  33725. color.toArray( colors, j ); j += 3;
  33726. color.toArray( colors, j ); j += 3;
  33727. color.toArray( colors, j ); j += 3;
  33728. }
  33729. var geometry = new BufferGeometry();
  33730. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33731. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33732. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  33733. LineSegments.call( this, geometry, material );
  33734. this.type = 'GridHelper';
  33735. }
  33736. GridHelper.prototype = Object.create( LineSegments.prototype );
  33737. GridHelper.prototype.constructor = GridHelper;
  33738. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  33739. radius = radius || 10;
  33740. radials = radials || 16;
  33741. circles = circles || 8;
  33742. divisions = divisions || 64;
  33743. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33744. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33745. var vertices = [];
  33746. var colors = [];
  33747. // create the radials
  33748. for ( var i = 0; i <= radials; i ++ ) {
  33749. var v = ( i / radials ) * ( Math.PI * 2 );
  33750. var x = Math.sin( v ) * radius;
  33751. var z = Math.cos( v ) * radius;
  33752. vertices.push( 0, 0, 0 );
  33753. vertices.push( x, 0, z );
  33754. var color = ( i & 1 ) ? color1 : color2;
  33755. colors.push( color.r, color.g, color.b );
  33756. colors.push( color.r, color.g, color.b );
  33757. }
  33758. // create the circles
  33759. for ( var i$1 = 0; i$1 <= circles; i$1 ++ ) {
  33760. var color$1 = ( i$1 & 1 ) ? color1 : color2;
  33761. var r = radius - ( radius / circles * i$1 );
  33762. for ( var j = 0; j < divisions; j ++ ) {
  33763. // first vertex
  33764. var v$1 = ( j / divisions ) * ( Math.PI * 2 );
  33765. var x$1 = Math.sin( v$1 ) * r;
  33766. var z$1 = Math.cos( v$1 ) * r;
  33767. vertices.push( x$1, 0, z$1 );
  33768. colors.push( color$1.r, color$1.g, color$1.b );
  33769. // second vertex
  33770. v$1 = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  33771. x$1 = Math.sin( v$1 ) * r;
  33772. z$1 = Math.cos( v$1 ) * r;
  33773. vertices.push( x$1, 0, z$1 );
  33774. colors.push( color$1.r, color$1.g, color$1.b );
  33775. }
  33776. }
  33777. var geometry = new BufferGeometry();
  33778. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33779. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33780. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  33781. LineSegments.call( this, geometry, material );
  33782. this.type = 'PolarGridHelper';
  33783. }
  33784. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  33785. PolarGridHelper.prototype.constructor = PolarGridHelper;
  33786. var _v1$5 = new Vector3();
  33787. var _v2$3 = new Vector3();
  33788. var _v3$1 = new Vector3();
  33789. function DirectionalLightHelper( light, size, color ) {
  33790. Object3D.call( this );
  33791. this.light = light;
  33792. this.light.updateMatrixWorld();
  33793. this.matrix = light.matrixWorld;
  33794. this.matrixAutoUpdate = false;
  33795. this.color = color;
  33796. if ( size === undefined ) { size = 1; }
  33797. var geometry = new BufferGeometry();
  33798. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  33799. - size, size, 0,
  33800. size, size, 0,
  33801. size, - size, 0,
  33802. - size, - size, 0,
  33803. - size, size, 0
  33804. ], 3 ) );
  33805. var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  33806. this.lightPlane = new Line( geometry, material );
  33807. this.add( this.lightPlane );
  33808. geometry = new BufferGeometry();
  33809. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  33810. this.targetLine = new Line( geometry, material );
  33811. this.add( this.targetLine );
  33812. this.update();
  33813. }
  33814. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  33815. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  33816. DirectionalLightHelper.prototype.dispose = function () {
  33817. this.lightPlane.geometry.dispose();
  33818. this.lightPlane.material.dispose();
  33819. this.targetLine.geometry.dispose();
  33820. this.targetLine.material.dispose();
  33821. };
  33822. DirectionalLightHelper.prototype.update = function () {
  33823. _v1$5.setFromMatrixPosition( this.light.matrixWorld );
  33824. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  33825. _v3$1.subVectors( _v2$3, _v1$5 );
  33826. this.lightPlane.lookAt( _v2$3 );
  33827. if ( this.color !== undefined ) {
  33828. this.lightPlane.material.color.set( this.color );
  33829. this.targetLine.material.color.set( this.color );
  33830. } else {
  33831. this.lightPlane.material.color.copy( this.light.color );
  33832. this.targetLine.material.color.copy( this.light.color );
  33833. }
  33834. this.targetLine.lookAt( _v2$3 );
  33835. this.targetLine.scale.z = _v3$1.length();
  33836. };
  33837. var _vector$b = new Vector3();
  33838. var _camera = new Camera();
  33839. /**
  33840. * - shows frustum, line of sight and up of the camera
  33841. * - suitable for fast updates
  33842. * - based on frustum visualization in lightgl.js shadowmap example
  33843. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33844. */
  33845. function CameraHelper( camera ) {
  33846. var geometry = new BufferGeometry();
  33847. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  33848. var vertices = [];
  33849. var colors = [];
  33850. var pointMap = {};
  33851. // colors
  33852. var colorFrustum = new Color( 0xffaa00 );
  33853. var colorCone = new Color( 0xff0000 );
  33854. var colorUp = new Color( 0x00aaff );
  33855. var colorTarget = new Color( 0xffffff );
  33856. var colorCross = new Color( 0x333333 );
  33857. // near
  33858. addLine( 'n1', 'n2', colorFrustum );
  33859. addLine( 'n2', 'n4', colorFrustum );
  33860. addLine( 'n4', 'n3', colorFrustum );
  33861. addLine( 'n3', 'n1', colorFrustum );
  33862. // far
  33863. addLine( 'f1', 'f2', colorFrustum );
  33864. addLine( 'f2', 'f4', colorFrustum );
  33865. addLine( 'f4', 'f3', colorFrustum );
  33866. addLine( 'f3', 'f1', colorFrustum );
  33867. // sides
  33868. addLine( 'n1', 'f1', colorFrustum );
  33869. addLine( 'n2', 'f2', colorFrustum );
  33870. addLine( 'n3', 'f3', colorFrustum );
  33871. addLine( 'n4', 'f4', colorFrustum );
  33872. // cone
  33873. addLine( 'p', 'n1', colorCone );
  33874. addLine( 'p', 'n2', colorCone );
  33875. addLine( 'p', 'n3', colorCone );
  33876. addLine( 'p', 'n4', colorCone );
  33877. // up
  33878. addLine( 'u1', 'u2', colorUp );
  33879. addLine( 'u2', 'u3', colorUp );
  33880. addLine( 'u3', 'u1', colorUp );
  33881. // target
  33882. addLine( 'c', 't', colorTarget );
  33883. addLine( 'p', 'c', colorCross );
  33884. // cross
  33885. addLine( 'cn1', 'cn2', colorCross );
  33886. addLine( 'cn3', 'cn4', colorCross );
  33887. addLine( 'cf1', 'cf2', colorCross );
  33888. addLine( 'cf3', 'cf4', colorCross );
  33889. function addLine( a, b, color ) {
  33890. addPoint( a, color );
  33891. addPoint( b, color );
  33892. }
  33893. function addPoint( id, color ) {
  33894. vertices.push( 0, 0, 0 );
  33895. colors.push( color.r, color.g, color.b );
  33896. if ( pointMap[ id ] === undefined ) {
  33897. pointMap[ id ] = [];
  33898. }
  33899. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  33900. }
  33901. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33902. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33903. LineSegments.call( this, geometry, material );
  33904. this.type = 'CameraHelper';
  33905. this.camera = camera;
  33906. if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); }
  33907. this.matrix = camera.matrixWorld;
  33908. this.matrixAutoUpdate = false;
  33909. this.pointMap = pointMap;
  33910. this.update();
  33911. }
  33912. CameraHelper.prototype = Object.create( LineSegments.prototype );
  33913. CameraHelper.prototype.constructor = CameraHelper;
  33914. CameraHelper.prototype.update = function () {
  33915. var geometry = this.geometry;
  33916. var pointMap = this.pointMap;
  33917. var w = 1, h = 1;
  33918. // we need just camera projection matrix inverse
  33919. // world matrix must be identity
  33920. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  33921. // center / target
  33922. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  33923. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  33924. // near
  33925. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  33926. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  33927. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  33928. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  33929. // far
  33930. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  33931. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  33932. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  33933. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  33934. // up
  33935. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  33936. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  33937. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  33938. // cross
  33939. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  33940. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  33941. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  33942. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  33943. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  33944. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  33945. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  33946. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  33947. geometry.getAttribute( 'position' ).needsUpdate = true;
  33948. };
  33949. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  33950. _vector$b.set( x, y, z ).unproject( camera );
  33951. var points = pointMap[ point ];
  33952. if ( points !== undefined ) {
  33953. var position = geometry.getAttribute( 'position' );
  33954. for ( var i = 0, l = points.length; i < l; i ++ ) {
  33955. position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );
  33956. }
  33957. }
  33958. }
  33959. var _box$3 = new Box3();
  33960. function BoxHelper( object, color ) {
  33961. this.object = object;
  33962. if ( color === undefined ) { color = 0xffff00; }
  33963. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  33964. var positions = new Float32Array( 8 * 3 );
  33965. var geometry = new BufferGeometry();
  33966. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  33967. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  33968. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  33969. this.type = 'BoxHelper';
  33970. this.matrixAutoUpdate = false;
  33971. this.update();
  33972. }
  33973. BoxHelper.prototype = Object.create( LineSegments.prototype );
  33974. BoxHelper.prototype.constructor = BoxHelper;
  33975. BoxHelper.prototype.update = function ( object ) {
  33976. if ( object !== undefined ) {
  33977. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  33978. }
  33979. if ( this.object !== undefined ) {
  33980. _box$3.setFromObject( this.object );
  33981. }
  33982. if ( _box$3.isEmpty() ) { return; }
  33983. var min = _box$3.min;
  33984. var max = _box$3.max;
  33985. /*
  33986. 5____4
  33987. 1/___0/|
  33988. | 6__|_7
  33989. 2/___3/
  33990. 0: max.x, max.y, max.z
  33991. 1: min.x, max.y, max.z
  33992. 2: min.x, min.y, max.z
  33993. 3: max.x, min.y, max.z
  33994. 4: max.x, max.y, min.z
  33995. 5: min.x, max.y, min.z
  33996. 6: min.x, min.y, min.z
  33997. 7: max.x, min.y, min.z
  33998. */
  33999. var position = this.geometry.attributes.position;
  34000. var array = position.array;
  34001. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  34002. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  34003. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  34004. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  34005. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  34006. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  34007. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  34008. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  34009. position.needsUpdate = true;
  34010. this.geometry.computeBoundingSphere();
  34011. };
  34012. BoxHelper.prototype.setFromObject = function ( object ) {
  34013. this.object = object;
  34014. this.update();
  34015. return this;
  34016. };
  34017. BoxHelper.prototype.copy = function ( source ) {
  34018. LineSegments.prototype.copy.call( this, source );
  34019. this.object = source.object;
  34020. return this;
  34021. };
  34022. function Box3Helper( box, color ) {
  34023. this.type = 'Box3Helper';
  34024. this.box = box;
  34025. if ( color === undefined ) { color = 0xffff00; }
  34026. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  34027. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  34028. var geometry = new BufferGeometry();
  34029. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  34030. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  34031. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  34032. this.type = 'Box3Helper';
  34033. this.geometry.computeBoundingSphere();
  34034. }
  34035. Box3Helper.prototype = Object.create( LineSegments.prototype );
  34036. Box3Helper.prototype.constructor = Box3Helper;
  34037. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  34038. var box = this.box;
  34039. if ( box.isEmpty() ) { return; }
  34040. box.getCenter( this.position );
  34041. box.getSize( this.scale );
  34042. this.scale.multiplyScalar( 0.5 );
  34043. Object3D.prototype.updateMatrixWorld.call( this, force );
  34044. };
  34045. function PlaneHelper( plane, size, hex ) {
  34046. this.plane = plane;
  34047. this.size = ( size === undefined ) ? 1 : size;
  34048. var color = ( hex !== undefined ) ? hex : 0xffff00;
  34049. var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  34050. var geometry = new BufferGeometry();
  34051. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  34052. geometry.computeBoundingSphere();
  34053. Line.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  34054. this.type = 'PlaneHelper';
  34055. //
  34056. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  34057. var geometry2 = new BufferGeometry();
  34058. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  34059. geometry2.computeBoundingSphere();
  34060. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  34061. }
  34062. PlaneHelper.prototype = Object.create( Line.prototype );
  34063. PlaneHelper.prototype.constructor = PlaneHelper;
  34064. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  34065. var scale = - this.plane.constant;
  34066. if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter
  34067. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  34068. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  34069. this.lookAt( this.plane.normal );
  34070. Object3D.prototype.updateMatrixWorld.call( this, force );
  34071. };
  34072. var _axis = new Vector3();
  34073. var _lineGeometry, _coneGeometry;
  34074. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  34075. // dir is assumed to be normalized
  34076. Object3D.call( this );
  34077. this.type = 'ArrowHelper';
  34078. if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); }
  34079. if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); }
  34080. if ( length === undefined ) { length = 1; }
  34081. if ( color === undefined ) { color = 0xffff00; }
  34082. if ( headLength === undefined ) { headLength = 0.2 * length; }
  34083. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  34084. if ( _lineGeometry === undefined ) {
  34085. _lineGeometry = new BufferGeometry();
  34086. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  34087. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  34088. _coneGeometry.translate( 0, - 0.5, 0 );
  34089. }
  34090. this.position.copy( origin );
  34091. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  34092. this.line.matrixAutoUpdate = false;
  34093. this.add( this.line );
  34094. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  34095. this.cone.matrixAutoUpdate = false;
  34096. this.add( this.cone );
  34097. this.setDirection( dir );
  34098. this.setLength( length, headLength, headWidth );
  34099. }
  34100. ArrowHelper.prototype = Object.create( Object3D.prototype );
  34101. ArrowHelper.prototype.constructor = ArrowHelper;
  34102. ArrowHelper.prototype.setDirection = function ( dir ) {
  34103. // dir is assumed to be normalized
  34104. if ( dir.y > 0.99999 ) {
  34105. this.quaternion.set( 0, 0, 0, 1 );
  34106. } else if ( dir.y < - 0.99999 ) {
  34107. this.quaternion.set( 1, 0, 0, 0 );
  34108. } else {
  34109. _axis.set( dir.z, 0, - dir.x ).normalize();
  34110. var radians = Math.acos( dir.y );
  34111. this.quaternion.setFromAxisAngle( _axis, radians );
  34112. }
  34113. };
  34114. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  34115. if ( headLength === undefined ) { headLength = 0.2 * length; }
  34116. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  34117. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  34118. this.line.updateMatrix();
  34119. this.cone.scale.set( headWidth, headLength, headWidth );
  34120. this.cone.position.y = length;
  34121. this.cone.updateMatrix();
  34122. };
  34123. ArrowHelper.prototype.setColor = function ( color ) {
  34124. this.line.material.color.set( color );
  34125. this.cone.material.color.set( color );
  34126. };
  34127. ArrowHelper.prototype.copy = function ( source ) {
  34128. Object3D.prototype.copy.call( this, source, false );
  34129. this.line.copy( source.line );
  34130. this.cone.copy( source.cone );
  34131. return this;
  34132. };
  34133. function AxesHelper( size ) {
  34134. size = size || 1;
  34135. var vertices = [
  34136. 0, 0, 0, size, 0, 0,
  34137. 0, 0, 0, 0, size, 0,
  34138. 0, 0, 0, 0, 0, size
  34139. ];
  34140. var colors = [
  34141. 1, 0, 0, 1, 0.6, 0,
  34142. 0, 1, 0, 0.6, 1, 0,
  34143. 0, 0, 1, 0, 0.6, 1
  34144. ];
  34145. var geometry = new BufferGeometry();
  34146. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  34147. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  34148. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  34149. LineSegments.call( this, geometry, material );
  34150. this.type = 'AxesHelper';
  34151. }
  34152. AxesHelper.prototype = Object.create( LineSegments.prototype );
  34153. AxesHelper.prototype.constructor = AxesHelper;
  34154. var LOD_MIN = 4;
  34155. var LOD_MAX = 8;
  34156. var SIZE_MAX = Math.pow( 2, LOD_MAX );
  34157. // The standard deviations (radians) associated with the extra mips. These are
  34158. // chosen to approximate a Trowbridge-Reitz distribution function times the
  34159. // geometric shadowing function. These sigma values squared must match the
  34160. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  34161. var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  34162. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  34163. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  34164. // samples and exit early, but not recompile the shader.
  34165. var MAX_SAMPLES = 20;
  34166. var ENCODINGS = {};
  34167. ENCODINGS[ LinearEncoding ] = 0;
  34168. ENCODINGS[ sRGBEncoding ] = 1;
  34169. ENCODINGS[ RGBEEncoding ] = 2;
  34170. ENCODINGS[ RGBM7Encoding ] = 3;
  34171. ENCODINGS[ RGBM16Encoding ] = 4;
  34172. ENCODINGS[ RGBDEncoding ] = 5;
  34173. ENCODINGS[ GammaEncoding ] = 6;
  34174. var _flatCamera = new OrthographicCamera();
  34175. var ref = _createPlanes();
  34176. var _lodPlanes = ref._lodPlanes;
  34177. var _sizeLods = ref._sizeLods;
  34178. var _sigmas = ref._sigmas;
  34179. var _oldTarget = null;
  34180. // Golden Ratio
  34181. var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  34182. var INV_PHI = 1 / PHI;
  34183. // Vertices of a dodecahedron (except the opposites, which represent the
  34184. // same axis), used as axis directions evenly spread on a sphere.
  34185. var _axisDirections = [
  34186. new Vector3( 1, 1, 1 ),
  34187. new Vector3( - 1, 1, 1 ),
  34188. new Vector3( 1, 1, - 1 ),
  34189. new Vector3( - 1, 1, - 1 ),
  34190. new Vector3( 0, PHI, INV_PHI ),
  34191. new Vector3( 0, PHI, - INV_PHI ),
  34192. new Vector3( INV_PHI, 0, PHI ),
  34193. new Vector3( - INV_PHI, 0, PHI ),
  34194. new Vector3( PHI, INV_PHI, 0 ),
  34195. new Vector3( - PHI, INV_PHI, 0 ) ];
  34196. /**
  34197. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  34198. * (PMREM) from a cubeMap environment texture. This allows different levels of
  34199. * blur to be quickly accessed based on material roughness. It is packed into a
  34200. * special CubeUV format that allows us to perform custom interpolation so that
  34201. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  34202. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  34203. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  34204. * higher roughness levels. In this way we maintain resolution to smoothly
  34205. * interpolate diffuse lighting while limiting sampling computation.
  34206. */
  34207. function PMREMGenerator( renderer ) {
  34208. this._renderer = renderer;
  34209. this._pingPongRenderTarget = null;
  34210. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  34211. this._equirectShader = null;
  34212. this._cubemapShader = null;
  34213. this._compileMaterial( this._blurMaterial );
  34214. }
  34215. PMREMGenerator.prototype = {
  34216. constructor: PMREMGenerator,
  34217. /**
  34218. * Generates a PMREM from a supplied Scene, which can be faster than using an
  34219. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  34220. * in radians to be applied to the scene before PMREM generation. Optional near
  34221. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  34222. * is placed at the origin).
  34223. */
  34224. fromScene: function ( scene, sigma, near, far ) {
  34225. if ( sigma === void 0 ) sigma = 0;
  34226. if ( near === void 0 ) near = 0.1;
  34227. if ( far === void 0 ) far = 100;
  34228. _oldTarget = this._renderer.getRenderTarget();
  34229. var cubeUVRenderTarget = this._allocateTargets();
  34230. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  34231. if ( sigma > 0 ) {
  34232. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  34233. }
  34234. this._applyPMREM( cubeUVRenderTarget );
  34235. this._cleanup( cubeUVRenderTarget );
  34236. return cubeUVRenderTarget;
  34237. },
  34238. /**
  34239. * Generates a PMREM from an equirectangular texture, which can be either LDR
  34240. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  34241. * as this matches best with the 256 x 256 cubemap output.
  34242. */
  34243. fromEquirectangular: function ( equirectangular ) {
  34244. return this._fromTexture( equirectangular );
  34245. },
  34246. /**
  34247. * Generates a PMREM from an cubemap texture, which can be either LDR
  34248. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  34249. * as this matches best with the 256 x 256 cubemap output.
  34250. */
  34251. fromCubemap: function ( cubemap ) {
  34252. return this._fromTexture( cubemap );
  34253. },
  34254. /**
  34255. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  34256. * your texture's network fetch for increased concurrency.
  34257. */
  34258. compileCubemapShader: function () {
  34259. if ( this._cubemapShader === null ) {
  34260. this._cubemapShader = _getCubemapShader();
  34261. this._compileMaterial( this._cubemapShader );
  34262. }
  34263. },
  34264. /**
  34265. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  34266. * your texture's network fetch for increased concurrency.
  34267. */
  34268. compileEquirectangularShader: function () {
  34269. if ( this._equirectShader === null ) {
  34270. this._equirectShader = _getEquirectShader();
  34271. this._compileMaterial( this._equirectShader );
  34272. }
  34273. },
  34274. /**
  34275. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  34276. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  34277. * one of them will cause any others to also become unusable.
  34278. */
  34279. dispose: function () {
  34280. this._blurMaterial.dispose();
  34281. if ( this._cubemapShader !== null ) { this._cubemapShader.dispose(); }
  34282. if ( this._equirectShader !== null ) { this._equirectShader.dispose(); }
  34283. for ( var i = 0; i < _lodPlanes.length; i ++ ) {
  34284. _lodPlanes[ i ].dispose();
  34285. }
  34286. },
  34287. // private interface
  34288. _cleanup: function ( outputTarget ) {
  34289. this._pingPongRenderTarget.dispose();
  34290. this._renderer.setRenderTarget( _oldTarget );
  34291. outputTarget.scissorTest = false;
  34292. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  34293. },
  34294. _fromTexture: function ( texture ) {
  34295. _oldTarget = this._renderer.getRenderTarget();
  34296. var cubeUVRenderTarget = this._allocateTargets( texture );
  34297. this._textureToCubeUV( texture, cubeUVRenderTarget );
  34298. this._applyPMREM( cubeUVRenderTarget );
  34299. this._cleanup( cubeUVRenderTarget );
  34300. return cubeUVRenderTarget;
  34301. },
  34302. _allocateTargets: function ( texture ) { // warning: null texture is valid
  34303. var params = {
  34304. magFilter: NearestFilter,
  34305. minFilter: NearestFilter,
  34306. generateMipmaps: false,
  34307. type: UnsignedByteType,
  34308. format: RGBEFormat,
  34309. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  34310. depthBuffer: false,
  34311. stencilBuffer: false
  34312. };
  34313. var cubeUVRenderTarget = _createRenderTarget( params );
  34314. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  34315. this._pingPongRenderTarget = _createRenderTarget( params );
  34316. return cubeUVRenderTarget;
  34317. },
  34318. _compileMaterial: function ( material ) {
  34319. var tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  34320. this._renderer.compile( tmpMesh, _flatCamera );
  34321. },
  34322. _sceneToCubeUV: function ( scene, near, far, cubeUVRenderTarget ) {
  34323. var fov = 90;
  34324. var aspect = 1;
  34325. var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  34326. var upSign = [ 1, - 1, 1, 1, 1, 1 ];
  34327. var forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  34328. var renderer = this._renderer;
  34329. var outputEncoding = renderer.outputEncoding;
  34330. var toneMapping = renderer.toneMapping;
  34331. var clearColor = renderer.getClearColor();
  34332. var clearAlpha = renderer.getClearAlpha();
  34333. renderer.toneMapping = NoToneMapping;
  34334. renderer.outputEncoding = LinearEncoding;
  34335. var background = scene.background;
  34336. if ( background && background.isColor ) {
  34337. background.convertSRGBToLinear();
  34338. // Convert linear to RGBE
  34339. var maxComponent = Math.max( background.r, background.g, background.b );
  34340. var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  34341. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  34342. var alpha = ( fExp + 128.0 ) / 255.0;
  34343. renderer.setClearColor( background, alpha );
  34344. scene.background = null;
  34345. }
  34346. for ( var i = 0; i < 6; i ++ ) {
  34347. var col = i % 3;
  34348. if ( col == 0 ) {
  34349. cubeCamera.up.set( 0, upSign[ i ], 0 );
  34350. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  34351. } else if ( col == 1 ) {
  34352. cubeCamera.up.set( 0, 0, upSign[ i ] );
  34353. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  34354. } else {
  34355. cubeCamera.up.set( 0, upSign[ i ], 0 );
  34356. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  34357. }
  34358. _setViewport( cubeUVRenderTarget,
  34359. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  34360. renderer.setRenderTarget( cubeUVRenderTarget );
  34361. renderer.render( scene, cubeCamera );
  34362. }
  34363. renderer.toneMapping = toneMapping;
  34364. renderer.outputEncoding = outputEncoding;
  34365. renderer.setClearColor( clearColor, clearAlpha );
  34366. },
  34367. _textureToCubeUV: function ( texture, cubeUVRenderTarget ) {
  34368. var renderer = this._renderer;
  34369. if ( texture.isCubeTexture ) {
  34370. if ( this._cubemapShader == null ) {
  34371. this._cubemapShader = _getCubemapShader();
  34372. }
  34373. } else {
  34374. if ( this._equirectShader == null ) {
  34375. this._equirectShader = _getEquirectShader();
  34376. }
  34377. }
  34378. var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  34379. var mesh = new Mesh( _lodPlanes[ 0 ], material );
  34380. var uniforms = material.uniforms;
  34381. uniforms[ 'envMap' ].value = texture;
  34382. if ( ! texture.isCubeTexture ) {
  34383. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  34384. }
  34385. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  34386. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  34387. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  34388. renderer.setRenderTarget( cubeUVRenderTarget );
  34389. renderer.render( mesh, _flatCamera );
  34390. },
  34391. _applyPMREM: function ( cubeUVRenderTarget ) {
  34392. var renderer = this._renderer;
  34393. var autoClear = renderer.autoClear;
  34394. renderer.autoClear = false;
  34395. for ( var i = 1; i < TOTAL_LODS; i ++ ) {
  34396. var sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  34397. var poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  34398. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  34399. }
  34400. renderer.autoClear = autoClear;
  34401. },
  34402. /**
  34403. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  34404. * vertically and horizontally, but this breaks down on a cube. Here we apply
  34405. * the blur latitudinally (around the poles), and then longitudinally (towards
  34406. * the poles) to approximate the orthogonally-separable blur. It is least
  34407. * accurate at the poles, but still does a decent job.
  34408. */
  34409. _blur: function ( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  34410. var pingPongRenderTarget = this._pingPongRenderTarget;
  34411. this._halfBlur(
  34412. cubeUVRenderTarget,
  34413. pingPongRenderTarget,
  34414. lodIn,
  34415. lodOut,
  34416. sigma,
  34417. 'latitudinal',
  34418. poleAxis );
  34419. this._halfBlur(
  34420. pingPongRenderTarget,
  34421. cubeUVRenderTarget,
  34422. lodOut,
  34423. lodOut,
  34424. sigma,
  34425. 'longitudinal',
  34426. poleAxis );
  34427. },
  34428. _halfBlur: function ( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  34429. var renderer = this._renderer;
  34430. var blurMaterial = this._blurMaterial;
  34431. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  34432. console.error(
  34433. 'blur direction must be either latitudinal or longitudinal!' );
  34434. }
  34435. // Number of standard deviations at which to cut off the discrete approximation.
  34436. var STANDARD_DEVIATIONS = 3;
  34437. var blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  34438. var blurUniforms = blurMaterial.uniforms;
  34439. var pixels = _sizeLods[ lodIn ] - 1;
  34440. var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  34441. var sigmaPixels = sigmaRadians / radiansPerPixel;
  34442. var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  34443. if ( samples > MAX_SAMPLES ) {
  34444. console.warn( ("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES) );
  34445. }
  34446. var weights = [];
  34447. var sum = 0;
  34448. for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
  34449. var x$1 = i / sigmaPixels;
  34450. var weight = Math.exp( - x$1 * x$1 / 2 );
  34451. weights.push( weight );
  34452. if ( i == 0 ) {
  34453. sum += weight;
  34454. } else if ( i < samples ) {
  34455. sum += 2 * weight;
  34456. }
  34457. }
  34458. for ( var i$1 = 0; i$1 < weights.length; i$1 ++ ) {
  34459. weights[ i$1 ] = weights[ i$1 ] / sum;
  34460. }
  34461. blurUniforms[ 'envMap' ].value = targetIn.texture;
  34462. blurUniforms[ 'samples' ].value = samples;
  34463. blurUniforms[ 'weights' ].value = weights;
  34464. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  34465. if ( poleAxis ) {
  34466. blurUniforms[ 'poleAxis' ].value = poleAxis;
  34467. }
  34468. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  34469. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  34470. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  34471. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  34472. var outputSize = _sizeLods[ lodOut ];
  34473. var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  34474. var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  34475. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  34476. renderer.setRenderTarget( targetOut );
  34477. renderer.render( blurMesh, _flatCamera );
  34478. }
  34479. };
  34480. function _isLDR( texture ) {
  34481. if ( texture === undefined || texture.type !== UnsignedByteType ) { return false; }
  34482. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  34483. }
  34484. function _createPlanes() {
  34485. var _lodPlanes = [];
  34486. var _sizeLods = [];
  34487. var _sigmas = [];
  34488. var lod = LOD_MAX;
  34489. for ( var i = 0; i < TOTAL_LODS; i ++ ) {
  34490. var sizeLod = Math.pow( 2, lod );
  34491. _sizeLods.push( sizeLod );
  34492. var sigma = 1.0 / sizeLod;
  34493. if ( i > LOD_MAX - LOD_MIN ) {
  34494. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  34495. } else if ( i == 0 ) {
  34496. sigma = 0;
  34497. }
  34498. _sigmas.push( sigma );
  34499. var texelSize = 1.0 / ( sizeLod - 1 );
  34500. var min = - texelSize / 2;
  34501. var max = 1 + texelSize / 2;
  34502. var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  34503. var cubeFaces = 6;
  34504. var vertices = 6;
  34505. var positionSize = 3;
  34506. var uvSize = 2;
  34507. var faceIndexSize = 1;
  34508. var position = new Float32Array( positionSize * vertices * cubeFaces );
  34509. var uv = new Float32Array( uvSize * vertices * cubeFaces );
  34510. var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  34511. for ( var face = 0; face < cubeFaces; face ++ ) {
  34512. var x = ( face % 3 ) * 2 / 3 - 1;
  34513. var y = face > 2 ? 0 : - 1;
  34514. var coordinates = [
  34515. x, y, 0,
  34516. x + 2 / 3, y, 0,
  34517. x + 2 / 3, y + 1, 0,
  34518. x, y, 0,
  34519. x + 2 / 3, y + 1, 0,
  34520. x, y + 1, 0
  34521. ];
  34522. position.set( coordinates, positionSize * vertices * face );
  34523. uv.set( uv1, uvSize * vertices * face );
  34524. var fill = [ face, face, face, face, face, face ];
  34525. faceIndex.set( fill, faceIndexSize * vertices * face );
  34526. }
  34527. var planes = new BufferGeometry();
  34528. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  34529. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  34530. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  34531. _lodPlanes.push( planes );
  34532. if ( lod > LOD_MIN ) {
  34533. lod --;
  34534. }
  34535. }
  34536. return { _lodPlanes: _lodPlanes, _sizeLods: _sizeLods, _sigmas: _sigmas };
  34537. }
  34538. function _createRenderTarget( params ) {
  34539. var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  34540. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  34541. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  34542. cubeUVRenderTarget.scissorTest = true;
  34543. return cubeUVRenderTarget;
  34544. }
  34545. function _setViewport( target, x, y, width, height ) {
  34546. target.viewport.set( x, y, width, height );
  34547. target.scissor.set( x, y, width, height );
  34548. }
  34549. function _getBlurShader( maxSamples ) {
  34550. var weights = new Float32Array( maxSamples );
  34551. var poleAxis = new Vector3( 0, 1, 0 );
  34552. var shaderMaterial = new RawShaderMaterial( {
  34553. name: 'SphericalGaussianBlur',
  34554. defines: { 'n': maxSamples },
  34555. uniforms: {
  34556. 'envMap': { value: null },
  34557. 'samples': { value: 1 },
  34558. 'weights': { value: weights },
  34559. 'latitudinal': { value: false },
  34560. 'dTheta': { value: 0 },
  34561. 'mipInt': { value: 0 },
  34562. 'poleAxis': { value: poleAxis },
  34563. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34564. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34565. },
  34566. vertexShader: _getCommonVertexShader(),
  34567. fragmentShader: /* glsl */("\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t" + (_getEncodings()) + "\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),
  34568. blending: NoBlending,
  34569. depthTest: false,
  34570. depthWrite: false
  34571. } );
  34572. return shaderMaterial;
  34573. }
  34574. function _getEquirectShader() {
  34575. var texelSize = new Vector2( 1, 1 );
  34576. var shaderMaterial = new RawShaderMaterial( {
  34577. name: 'EquirectangularToCubeUV',
  34578. uniforms: {
  34579. 'envMap': { value: null },
  34580. 'texelSize': { value: texelSize },
  34581. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34582. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34583. },
  34584. vertexShader: _getCommonVertexShader(),
  34585. fragmentShader: /* glsl */("\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t" + (_getEncodings()) + "\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),
  34586. blending: NoBlending,
  34587. depthTest: false,
  34588. depthWrite: false
  34589. } );
  34590. return shaderMaterial;
  34591. }
  34592. function _getCubemapShader() {
  34593. var shaderMaterial = new RawShaderMaterial( {
  34594. name: 'CubemapToCubeUV',
  34595. uniforms: {
  34596. 'envMap': { value: null },
  34597. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34598. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34599. },
  34600. vertexShader: _getCommonVertexShader(),
  34601. fragmentShader: /* glsl */("\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t" + (_getEncodings()) + "\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),
  34602. blending: NoBlending,
  34603. depthTest: false,
  34604. depthWrite: false
  34605. } );
  34606. return shaderMaterial;
  34607. }
  34608. function _getCommonVertexShader() {
  34609. return /* glsl */"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t";
  34610. }
  34611. function _getEncodings() {
  34612. return /* glsl */"\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t";
  34613. }
  34614. function Face4( a, b, c, d, normal, color, materialIndex ) {
  34615. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  34616. return new Face3( a, b, c, normal, color, materialIndex );
  34617. }
  34618. var LineStrip = 0;
  34619. var LinePieces = 1;
  34620. var NoColors = 0;
  34621. var FaceColors = 1;
  34622. var VertexColors = 2;
  34623. function MeshFaceMaterial( materials ) {
  34624. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  34625. return materials;
  34626. }
  34627. function MultiMaterial( materials ) {
  34628. if ( materials === undefined ) { materials = []; }
  34629. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  34630. materials.isMultiMaterial = true;
  34631. materials.materials = materials;
  34632. materials.clone = function () {
  34633. return materials.slice();
  34634. };
  34635. return materials;
  34636. }
  34637. function PointCloud( geometry, material ) {
  34638. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  34639. return new Points( geometry, material );
  34640. }
  34641. function Particle( material ) {
  34642. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  34643. return new Sprite( material );
  34644. }
  34645. function ParticleSystem( geometry, material ) {
  34646. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  34647. return new Points( geometry, material );
  34648. }
  34649. function PointCloudMaterial( parameters ) {
  34650. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  34651. return new PointsMaterial( parameters );
  34652. }
  34653. function ParticleBasicMaterial( parameters ) {
  34654. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  34655. return new PointsMaterial( parameters );
  34656. }
  34657. function ParticleSystemMaterial( parameters ) {
  34658. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  34659. return new PointsMaterial( parameters );
  34660. }
  34661. function Vertex( x, y, z ) {
  34662. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  34663. return new Vector3( x, y, z );
  34664. }
  34665. //
  34666. function DynamicBufferAttribute( array, itemSize ) {
  34667. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  34668. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  34669. }
  34670. function Int8Attribute( array, itemSize ) {
  34671. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  34672. return new Int8BufferAttribute( array, itemSize );
  34673. }
  34674. function Uint8Attribute( array, itemSize ) {
  34675. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  34676. return new Uint8BufferAttribute( array, itemSize );
  34677. }
  34678. function Uint8ClampedAttribute( array, itemSize ) {
  34679. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  34680. return new Uint8ClampedBufferAttribute( array, itemSize );
  34681. }
  34682. function Int16Attribute( array, itemSize ) {
  34683. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  34684. return new Int16BufferAttribute( array, itemSize );
  34685. }
  34686. function Uint16Attribute( array, itemSize ) {
  34687. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  34688. return new Uint16BufferAttribute( array, itemSize );
  34689. }
  34690. function Int32Attribute( array, itemSize ) {
  34691. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  34692. return new Int32BufferAttribute( array, itemSize );
  34693. }
  34694. function Uint32Attribute( array, itemSize ) {
  34695. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  34696. return new Uint32BufferAttribute( array, itemSize );
  34697. }
  34698. function Float32Attribute( array, itemSize ) {
  34699. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  34700. return new Float32BufferAttribute( array, itemSize );
  34701. }
  34702. function Float64Attribute( array, itemSize ) {
  34703. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  34704. return new Float64BufferAttribute( array, itemSize );
  34705. }
  34706. //
  34707. Curve.create = function ( construct, getPoint ) {
  34708. console.log( 'THREE.Curve.create() has been deprecated' );
  34709. construct.prototype = Object.create( Curve.prototype );
  34710. construct.prototype.constructor = construct;
  34711. construct.prototype.getPoint = getPoint;
  34712. return construct;
  34713. };
  34714. //
  34715. Object.assign( CurvePath.prototype, {
  34716. createPointsGeometry: function ( divisions ) {
  34717. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34718. // generate geometry from path points (for Line or Points objects)
  34719. var pts = this.getPoints( divisions );
  34720. return this.createGeometry( pts );
  34721. },
  34722. createSpacedPointsGeometry: function ( divisions ) {
  34723. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34724. // generate geometry from equidistant sampling along the path
  34725. var pts = this.getSpacedPoints( divisions );
  34726. return this.createGeometry( pts );
  34727. },
  34728. createGeometry: function ( points ) {
  34729. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34730. var geometry = new Geometry();
  34731. for ( var i = 0, l = points.length; i < l; i ++ ) {
  34732. var point = points[ i ];
  34733. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  34734. }
  34735. return geometry;
  34736. }
  34737. } );
  34738. //
  34739. Object.assign( Path.prototype, {
  34740. fromPoints: function ( points ) {
  34741. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  34742. return this.setFromPoints( points );
  34743. }
  34744. } );
  34745. //
  34746. function ClosedSplineCurve3( points ) {
  34747. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  34748. CatmullRomCurve3.call( this, points );
  34749. this.type = 'catmullrom';
  34750. this.closed = true;
  34751. }
  34752. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  34753. //
  34754. function SplineCurve3( points ) {
  34755. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  34756. CatmullRomCurve3.call( this, points );
  34757. this.type = 'catmullrom';
  34758. }
  34759. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  34760. //
  34761. function Spline( points ) {
  34762. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  34763. CatmullRomCurve3.call( this, points );
  34764. this.type = 'catmullrom';
  34765. }
  34766. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  34767. Object.assign( Spline.prototype, {
  34768. initFromArray: function ( /* a */ ) {
  34769. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  34770. },
  34771. getControlPointsArray: function ( /* optionalTarget */ ) {
  34772. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  34773. },
  34774. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  34775. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  34776. }
  34777. } );
  34778. //
  34779. function AxisHelper( size ) {
  34780. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  34781. return new AxesHelper( size );
  34782. }
  34783. function BoundingBoxHelper( object, color ) {
  34784. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  34785. return new BoxHelper( object, color );
  34786. }
  34787. function EdgesHelper( object, hex ) {
  34788. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  34789. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  34790. }
  34791. GridHelper.prototype.setColors = function () {
  34792. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  34793. };
  34794. SkeletonHelper.prototype.update = function () {
  34795. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  34796. };
  34797. function WireframeHelper( object, hex ) {
  34798. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  34799. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  34800. }
  34801. //
  34802. Object.assign( Loader.prototype, {
  34803. extractUrlBase: function ( url ) {
  34804. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  34805. return LoaderUtils.extractUrlBase( url );
  34806. }
  34807. } );
  34808. Loader.Handlers = {
  34809. add: function ( /* regex, loader */ ) {
  34810. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  34811. },
  34812. get: function ( /* file */ ) {
  34813. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  34814. }
  34815. };
  34816. function XHRLoader( manager ) {
  34817. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  34818. return new FileLoader( manager );
  34819. }
  34820. function BinaryTextureLoader( manager ) {
  34821. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  34822. return new DataTextureLoader( manager );
  34823. }
  34824. Object.assign( ObjectLoader.prototype, {
  34825. setTexturePath: function ( value ) {
  34826. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  34827. return this.setResourcePath( value );
  34828. }
  34829. } );
  34830. //
  34831. Object.assign( Box2.prototype, {
  34832. center: function ( optionalTarget ) {
  34833. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  34834. return this.getCenter( optionalTarget );
  34835. },
  34836. empty: function () {
  34837. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  34838. return this.isEmpty();
  34839. },
  34840. isIntersectionBox: function ( box ) {
  34841. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34842. return this.intersectsBox( box );
  34843. },
  34844. size: function ( optionalTarget ) {
  34845. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  34846. return this.getSize( optionalTarget );
  34847. }
  34848. } );
  34849. Object.assign( Box3.prototype, {
  34850. center: function ( optionalTarget ) {
  34851. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  34852. return this.getCenter( optionalTarget );
  34853. },
  34854. empty: function () {
  34855. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  34856. return this.isEmpty();
  34857. },
  34858. isIntersectionBox: function ( box ) {
  34859. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34860. return this.intersectsBox( box );
  34861. },
  34862. isIntersectionSphere: function ( sphere ) {
  34863. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  34864. return this.intersectsSphere( sphere );
  34865. },
  34866. size: function ( optionalTarget ) {
  34867. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  34868. return this.getSize( optionalTarget );
  34869. }
  34870. } );
  34871. Object.assign( Sphere.prototype, {
  34872. empty: function () {
  34873. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  34874. return this.isEmpty();
  34875. },
  34876. } );
  34877. Frustum.prototype.setFromMatrix = function ( m ) {
  34878. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  34879. return this.setFromProjectionMatrix( m );
  34880. };
  34881. Line3.prototype.center = function ( optionalTarget ) {
  34882. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  34883. return this.getCenter( optionalTarget );
  34884. };
  34885. Object.assign( MathUtils, {
  34886. random16: function () {
  34887. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  34888. return Math.random();
  34889. },
  34890. nearestPowerOfTwo: function ( value ) {
  34891. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  34892. return MathUtils.floorPowerOfTwo( value );
  34893. },
  34894. nextPowerOfTwo: function ( value ) {
  34895. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  34896. return MathUtils.ceilPowerOfTwo( value );
  34897. }
  34898. } );
  34899. Object.assign( Matrix3.prototype, {
  34900. flattenToArrayOffset: function ( array, offset ) {
  34901. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  34902. return this.toArray( array, offset );
  34903. },
  34904. multiplyVector3: function ( vector ) {
  34905. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  34906. return vector.applyMatrix3( this );
  34907. },
  34908. multiplyVector3Array: function ( /* a */ ) {
  34909. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  34910. },
  34911. applyToBufferAttribute: function ( attribute ) {
  34912. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  34913. return attribute.applyMatrix3( this );
  34914. },
  34915. applyToVector3Array: function ( /* array, offset, length */ ) {
  34916. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  34917. }
  34918. } );
  34919. Object.assign( Matrix4.prototype, {
  34920. extractPosition: function ( m ) {
  34921. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  34922. return this.copyPosition( m );
  34923. },
  34924. flattenToArrayOffset: function ( array, offset ) {
  34925. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  34926. return this.toArray( array, offset );
  34927. },
  34928. getPosition: function () {
  34929. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  34930. return new Vector3().setFromMatrixColumn( this, 3 );
  34931. },
  34932. setRotationFromQuaternion: function ( q ) {
  34933. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  34934. return this.makeRotationFromQuaternion( q );
  34935. },
  34936. multiplyToArray: function () {
  34937. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  34938. },
  34939. multiplyVector3: function ( vector ) {
  34940. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34941. return vector.applyMatrix4( this );
  34942. },
  34943. multiplyVector4: function ( vector ) {
  34944. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34945. return vector.applyMatrix4( this );
  34946. },
  34947. multiplyVector3Array: function ( /* a */ ) {
  34948. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  34949. },
  34950. rotateAxis: function ( v ) {
  34951. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  34952. v.transformDirection( this );
  34953. },
  34954. crossVector: function ( vector ) {
  34955. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34956. return vector.applyMatrix4( this );
  34957. },
  34958. translate: function () {
  34959. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  34960. },
  34961. rotateX: function () {
  34962. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  34963. },
  34964. rotateY: function () {
  34965. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  34966. },
  34967. rotateZ: function () {
  34968. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  34969. },
  34970. rotateByAxis: function () {
  34971. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  34972. },
  34973. applyToBufferAttribute: function ( attribute ) {
  34974. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  34975. return attribute.applyMatrix4( this );
  34976. },
  34977. applyToVector3Array: function ( /* array, offset, length */ ) {
  34978. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  34979. },
  34980. makeFrustum: function ( left, right, bottom, top, near, far ) {
  34981. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  34982. return this.makePerspective( left, right, top, bottom, near, far );
  34983. }
  34984. } );
  34985. Plane.prototype.isIntersectionLine = function ( line ) {
  34986. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  34987. return this.intersectsLine( line );
  34988. };
  34989. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  34990. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  34991. return vector.applyQuaternion( this );
  34992. };
  34993. Object.assign( Ray.prototype, {
  34994. isIntersectionBox: function ( box ) {
  34995. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34996. return this.intersectsBox( box );
  34997. },
  34998. isIntersectionPlane: function ( plane ) {
  34999. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  35000. return this.intersectsPlane( plane );
  35001. },
  35002. isIntersectionSphere: function ( sphere ) {
  35003. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  35004. return this.intersectsSphere( sphere );
  35005. }
  35006. } );
  35007. Object.assign( Triangle.prototype, {
  35008. area: function () {
  35009. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  35010. return this.getArea();
  35011. },
  35012. barycoordFromPoint: function ( point, target ) {
  35013. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  35014. return this.getBarycoord( point, target );
  35015. },
  35016. midpoint: function ( target ) {
  35017. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  35018. return this.getMidpoint( target );
  35019. },
  35020. normal: function ( target ) {
  35021. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  35022. return this.getNormal( target );
  35023. },
  35024. plane: function ( target ) {
  35025. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  35026. return this.getPlane( target );
  35027. }
  35028. } );
  35029. Object.assign( Triangle, {
  35030. barycoordFromPoint: function ( point, a, b, c, target ) {
  35031. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  35032. return Triangle.getBarycoord( point, a, b, c, target );
  35033. },
  35034. normal: function ( a, b, c, target ) {
  35035. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  35036. return Triangle.getNormal( a, b, c, target );
  35037. }
  35038. } );
  35039. Object.assign( Shape.prototype, {
  35040. extractAllPoints: function ( divisions ) {
  35041. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  35042. return this.extractPoints( divisions );
  35043. },
  35044. extrude: function ( options ) {
  35045. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  35046. return new ExtrudeGeometry( this, options );
  35047. },
  35048. makeGeometry: function ( options ) {
  35049. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  35050. return new ShapeGeometry( this, options );
  35051. }
  35052. } );
  35053. Object.assign( Vector2.prototype, {
  35054. fromAttribute: function ( attribute, index, offset ) {
  35055. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35056. return this.fromBufferAttribute( attribute, index, offset );
  35057. },
  35058. distanceToManhattan: function ( v ) {
  35059. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  35060. return this.manhattanDistanceTo( v );
  35061. },
  35062. lengthManhattan: function () {
  35063. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  35064. return this.manhattanLength();
  35065. }
  35066. } );
  35067. Object.assign( Vector3.prototype, {
  35068. setEulerFromRotationMatrix: function () {
  35069. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  35070. },
  35071. setEulerFromQuaternion: function () {
  35072. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  35073. },
  35074. getPositionFromMatrix: function ( m ) {
  35075. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  35076. return this.setFromMatrixPosition( m );
  35077. },
  35078. getScaleFromMatrix: function ( m ) {
  35079. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  35080. return this.setFromMatrixScale( m );
  35081. },
  35082. getColumnFromMatrix: function ( index, matrix ) {
  35083. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  35084. return this.setFromMatrixColumn( matrix, index );
  35085. },
  35086. applyProjection: function ( m ) {
  35087. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  35088. return this.applyMatrix4( m );
  35089. },
  35090. fromAttribute: function ( attribute, index, offset ) {
  35091. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35092. return this.fromBufferAttribute( attribute, index, offset );
  35093. },
  35094. distanceToManhattan: function ( v ) {
  35095. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  35096. return this.manhattanDistanceTo( v );
  35097. },
  35098. lengthManhattan: function () {
  35099. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  35100. return this.manhattanLength();
  35101. }
  35102. } );
  35103. Object.assign( Vector4.prototype, {
  35104. fromAttribute: function ( attribute, index, offset ) {
  35105. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35106. return this.fromBufferAttribute( attribute, index, offset );
  35107. },
  35108. lengthManhattan: function () {
  35109. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  35110. return this.manhattanLength();
  35111. }
  35112. } );
  35113. //
  35114. Object.assign( Geometry.prototype, {
  35115. computeTangents: function () {
  35116. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  35117. },
  35118. computeLineDistances: function () {
  35119. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  35120. },
  35121. applyMatrix: function ( matrix ) {
  35122. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  35123. return this.applyMatrix4( matrix );
  35124. }
  35125. } );
  35126. Object.assign( Object3D.prototype, {
  35127. getChildByName: function ( name ) {
  35128. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  35129. return this.getObjectByName( name );
  35130. },
  35131. renderDepth: function () {
  35132. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  35133. },
  35134. translate: function ( distance, axis ) {
  35135. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  35136. return this.translateOnAxis( axis, distance );
  35137. },
  35138. getWorldRotation: function () {
  35139. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  35140. },
  35141. applyMatrix: function ( matrix ) {
  35142. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  35143. return this.applyMatrix4( matrix );
  35144. }
  35145. } );
  35146. Object.defineProperties( Object3D.prototype, {
  35147. eulerOrder: {
  35148. get: function () {
  35149. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  35150. return this.rotation.order;
  35151. },
  35152. set: function ( value ) {
  35153. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  35154. this.rotation.order = value;
  35155. }
  35156. },
  35157. useQuaternion: {
  35158. get: function () {
  35159. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  35160. },
  35161. set: function () {
  35162. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  35163. }
  35164. }
  35165. } );
  35166. Object.assign( Mesh.prototype, {
  35167. setDrawMode: function () {
  35168. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  35169. },
  35170. } );
  35171. Object.defineProperties( Mesh.prototype, {
  35172. drawMode: {
  35173. get: function () {
  35174. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  35175. return TrianglesDrawMode;
  35176. },
  35177. set: function () {
  35178. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  35179. }
  35180. }
  35181. } );
  35182. Object.defineProperties( LOD.prototype, {
  35183. objects: {
  35184. get: function () {
  35185. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  35186. return this.levels;
  35187. }
  35188. }
  35189. } );
  35190. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  35191. get: function () {
  35192. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  35193. },
  35194. set: function () {
  35195. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  35196. }
  35197. } );
  35198. SkinnedMesh.prototype.initBones = function () {
  35199. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  35200. };
  35201. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  35202. get: function () {
  35203. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  35204. return this.arcLengthDivisions;
  35205. },
  35206. set: function ( value ) {
  35207. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  35208. this.arcLengthDivisions = value;
  35209. }
  35210. } );
  35211. //
  35212. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  35213. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  35214. "Use .setFocalLength and .filmGauge for a photographic setup." );
  35215. if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; }
  35216. this.setFocalLength( focalLength );
  35217. };
  35218. //
  35219. Object.defineProperties( Light.prototype, {
  35220. onlyShadow: {
  35221. set: function () {
  35222. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  35223. }
  35224. },
  35225. shadowCameraFov: {
  35226. set: function ( value ) {
  35227. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  35228. this.shadow.camera.fov = value;
  35229. }
  35230. },
  35231. shadowCameraLeft: {
  35232. set: function ( value ) {
  35233. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  35234. this.shadow.camera.left = value;
  35235. }
  35236. },
  35237. shadowCameraRight: {
  35238. set: function ( value ) {
  35239. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  35240. this.shadow.camera.right = value;
  35241. }
  35242. },
  35243. shadowCameraTop: {
  35244. set: function ( value ) {
  35245. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  35246. this.shadow.camera.top = value;
  35247. }
  35248. },
  35249. shadowCameraBottom: {
  35250. set: function ( value ) {
  35251. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  35252. this.shadow.camera.bottom = value;
  35253. }
  35254. },
  35255. shadowCameraNear: {
  35256. set: function ( value ) {
  35257. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  35258. this.shadow.camera.near = value;
  35259. }
  35260. },
  35261. shadowCameraFar: {
  35262. set: function ( value ) {
  35263. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  35264. this.shadow.camera.far = value;
  35265. }
  35266. },
  35267. shadowCameraVisible: {
  35268. set: function () {
  35269. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  35270. }
  35271. },
  35272. shadowBias: {
  35273. set: function ( value ) {
  35274. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  35275. this.shadow.bias = value;
  35276. }
  35277. },
  35278. shadowDarkness: {
  35279. set: function () {
  35280. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  35281. }
  35282. },
  35283. shadowMapWidth: {
  35284. set: function ( value ) {
  35285. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  35286. this.shadow.mapSize.width = value;
  35287. }
  35288. },
  35289. shadowMapHeight: {
  35290. set: function ( value ) {
  35291. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  35292. this.shadow.mapSize.height = value;
  35293. }
  35294. }
  35295. } );
  35296. //
  35297. Object.defineProperties( BufferAttribute.prototype, {
  35298. length: {
  35299. get: function () {
  35300. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  35301. return this.array.length;
  35302. }
  35303. },
  35304. dynamic: {
  35305. get: function () {
  35306. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  35307. return this.usage === DynamicDrawUsage;
  35308. },
  35309. set: function ( /* value */ ) {
  35310. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  35311. this.setUsage( DynamicDrawUsage );
  35312. }
  35313. }
  35314. } );
  35315. Object.assign( BufferAttribute.prototype, {
  35316. setDynamic: function ( value ) {
  35317. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  35318. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  35319. return this;
  35320. },
  35321. copyIndicesArray: function ( /* indices */ ) {
  35322. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  35323. },
  35324. setArray: function ( /* array */ ) {
  35325. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  35326. }
  35327. } );
  35328. Object.assign( BufferGeometry.prototype, {
  35329. addIndex: function ( index ) {
  35330. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  35331. this.setIndex( index );
  35332. },
  35333. addAttribute: function ( name, attribute ) {
  35334. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  35335. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  35336. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  35337. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  35338. }
  35339. if ( name === 'index' ) {
  35340. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  35341. this.setIndex( attribute );
  35342. return this;
  35343. }
  35344. return this.setAttribute( name, attribute );
  35345. },
  35346. addDrawCall: function ( start, count, indexOffset ) {
  35347. if ( indexOffset !== undefined ) {
  35348. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  35349. }
  35350. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  35351. this.addGroup( start, count );
  35352. },
  35353. clearDrawCalls: function () {
  35354. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  35355. this.clearGroups();
  35356. },
  35357. computeTangents: function () {
  35358. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  35359. },
  35360. computeOffsets: function () {
  35361. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  35362. },
  35363. removeAttribute: function ( name ) {
  35364. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  35365. return this.deleteAttribute( name );
  35366. },
  35367. applyMatrix: function ( matrix ) {
  35368. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  35369. return this.applyMatrix4( matrix );
  35370. }
  35371. } );
  35372. Object.defineProperties( BufferGeometry.prototype, {
  35373. drawcalls: {
  35374. get: function () {
  35375. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  35376. return this.groups;
  35377. }
  35378. },
  35379. offsets: {
  35380. get: function () {
  35381. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  35382. return this.groups;
  35383. }
  35384. }
  35385. } );
  35386. Object.defineProperties( InstancedBufferGeometry.prototype, {
  35387. maxInstancedCount: {
  35388. get: function () {
  35389. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  35390. return this.instanceCount;
  35391. },
  35392. set: function ( value ) {
  35393. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  35394. this.instanceCount = value;
  35395. }
  35396. }
  35397. } );
  35398. Object.defineProperties( Raycaster.prototype, {
  35399. linePrecision: {
  35400. get: function () {
  35401. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  35402. return this.params.Line.threshold;
  35403. },
  35404. set: function ( value ) {
  35405. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  35406. this.params.Line.threshold = value;
  35407. }
  35408. }
  35409. } );
  35410. Object.defineProperties( InterleavedBuffer.prototype, {
  35411. dynamic: {
  35412. get: function () {
  35413. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  35414. return this.usage === DynamicDrawUsage;
  35415. },
  35416. set: function ( value ) {
  35417. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  35418. this.setUsage( value );
  35419. }
  35420. }
  35421. } );
  35422. Object.assign( InterleavedBuffer.prototype, {
  35423. setDynamic: function ( value ) {
  35424. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  35425. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  35426. return this;
  35427. },
  35428. setArray: function ( /* array */ ) {
  35429. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  35430. }
  35431. } );
  35432. //
  35433. Object.assign( ExtrudeBufferGeometry.prototype, {
  35434. getArrays: function () {
  35435. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  35436. },
  35437. addShapeList: function () {
  35438. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  35439. },
  35440. addShape: function () {
  35441. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  35442. }
  35443. } );
  35444. //
  35445. Object.defineProperties( Uniform.prototype, {
  35446. dynamic: {
  35447. set: function () {
  35448. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  35449. }
  35450. },
  35451. onUpdate: {
  35452. value: function () {
  35453. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  35454. return this;
  35455. }
  35456. }
  35457. } );
  35458. //
  35459. Object.defineProperties( Material.prototype, {
  35460. wrapAround: {
  35461. get: function () {
  35462. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  35463. },
  35464. set: function () {
  35465. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  35466. }
  35467. },
  35468. overdraw: {
  35469. get: function () {
  35470. console.warn( 'THREE.Material: .overdraw has been removed.' );
  35471. },
  35472. set: function () {
  35473. console.warn( 'THREE.Material: .overdraw has been removed.' );
  35474. }
  35475. },
  35476. wrapRGB: {
  35477. get: function () {
  35478. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  35479. return new Color();
  35480. }
  35481. },
  35482. shading: {
  35483. get: function () {
  35484. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  35485. },
  35486. set: function ( value ) {
  35487. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  35488. this.flatShading = ( value === FlatShading );
  35489. }
  35490. },
  35491. stencilMask: {
  35492. get: function () {
  35493. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  35494. return this.stencilFuncMask;
  35495. },
  35496. set: function ( value ) {
  35497. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  35498. this.stencilFuncMask = value;
  35499. }
  35500. }
  35501. } );
  35502. Object.defineProperties( MeshPhongMaterial.prototype, {
  35503. metal: {
  35504. get: function () {
  35505. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  35506. return false;
  35507. },
  35508. set: function () {
  35509. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  35510. }
  35511. }
  35512. } );
  35513. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  35514. transparency: {
  35515. get: function () {
  35516. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  35517. return this.transmission;
  35518. },
  35519. set: function ( value ) {
  35520. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  35521. this.transmission = value;
  35522. }
  35523. }
  35524. } );
  35525. Object.defineProperties( ShaderMaterial.prototype, {
  35526. derivatives: {
  35527. get: function () {
  35528. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  35529. return this.extensions.derivatives;
  35530. },
  35531. set: function ( value ) {
  35532. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  35533. this.extensions.derivatives = value;
  35534. }
  35535. }
  35536. } );
  35537. //
  35538. Object.assign( WebGLRenderer.prototype, {
  35539. clearTarget: function ( renderTarget, color, depth, stencil ) {
  35540. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  35541. this.setRenderTarget( renderTarget );
  35542. this.clear( color, depth, stencil );
  35543. },
  35544. animate: function ( callback ) {
  35545. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  35546. this.setAnimationLoop( callback );
  35547. },
  35548. getCurrentRenderTarget: function () {
  35549. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  35550. return this.getRenderTarget();
  35551. },
  35552. getMaxAnisotropy: function () {
  35553. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  35554. return this.capabilities.getMaxAnisotropy();
  35555. },
  35556. getPrecision: function () {
  35557. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  35558. return this.capabilities.precision;
  35559. },
  35560. resetGLState: function () {
  35561. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  35562. return this.state.reset();
  35563. },
  35564. supportsFloatTextures: function () {
  35565. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  35566. return this.extensions.get( 'OES_texture_float' );
  35567. },
  35568. supportsHalfFloatTextures: function () {
  35569. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  35570. return this.extensions.get( 'OES_texture_half_float' );
  35571. },
  35572. supportsStandardDerivatives: function () {
  35573. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  35574. return this.extensions.get( 'OES_standard_derivatives' );
  35575. },
  35576. supportsCompressedTextureS3TC: function () {
  35577. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  35578. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  35579. },
  35580. supportsCompressedTexturePVRTC: function () {
  35581. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  35582. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  35583. },
  35584. supportsBlendMinMax: function () {
  35585. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  35586. return this.extensions.get( 'EXT_blend_minmax' );
  35587. },
  35588. supportsVertexTextures: function () {
  35589. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  35590. return this.capabilities.vertexTextures;
  35591. },
  35592. supportsInstancedArrays: function () {
  35593. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  35594. return this.extensions.get( 'ANGLE_instanced_arrays' );
  35595. },
  35596. enableScissorTest: function ( boolean ) {
  35597. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  35598. this.setScissorTest( boolean );
  35599. },
  35600. initMaterial: function () {
  35601. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  35602. },
  35603. addPrePlugin: function () {
  35604. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  35605. },
  35606. addPostPlugin: function () {
  35607. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  35608. },
  35609. updateShadowMap: function () {
  35610. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  35611. },
  35612. setFaceCulling: function () {
  35613. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  35614. },
  35615. allocTextureUnit: function () {
  35616. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  35617. },
  35618. setTexture: function () {
  35619. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  35620. },
  35621. setTextureCube: function () {
  35622. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  35623. },
  35624. getActiveMipMapLevel: function () {
  35625. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  35626. return this.getActiveMipmapLevel();
  35627. }
  35628. } );
  35629. Object.defineProperties( WebGLRenderer.prototype, {
  35630. shadowMapEnabled: {
  35631. get: function () {
  35632. return this.shadowMap.enabled;
  35633. },
  35634. set: function ( value ) {
  35635. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  35636. this.shadowMap.enabled = value;
  35637. }
  35638. },
  35639. shadowMapType: {
  35640. get: function () {
  35641. return this.shadowMap.type;
  35642. },
  35643. set: function ( value ) {
  35644. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  35645. this.shadowMap.type = value;
  35646. }
  35647. },
  35648. shadowMapCullFace: {
  35649. get: function () {
  35650. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  35651. return undefined;
  35652. },
  35653. set: function ( /* value */ ) {
  35654. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  35655. }
  35656. },
  35657. context: {
  35658. get: function () {
  35659. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  35660. return this.getContext();
  35661. }
  35662. },
  35663. vr: {
  35664. get: function () {
  35665. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  35666. return this.xr;
  35667. }
  35668. },
  35669. gammaInput: {
  35670. get: function () {
  35671. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  35672. return false;
  35673. },
  35674. set: function () {
  35675. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  35676. }
  35677. },
  35678. gammaOutput: {
  35679. get: function () {
  35680. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  35681. return false;
  35682. },
  35683. set: function ( value ) {
  35684. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  35685. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  35686. }
  35687. },
  35688. toneMappingWhitePoint: {
  35689. get: function () {
  35690. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  35691. return 1.0;
  35692. },
  35693. set: function () {
  35694. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  35695. }
  35696. },
  35697. } );
  35698. Object.defineProperties( WebGLShadowMap.prototype, {
  35699. cullFace: {
  35700. get: function () {
  35701. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  35702. return undefined;
  35703. },
  35704. set: function ( /* cullFace */ ) {
  35705. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  35706. }
  35707. },
  35708. renderReverseSided: {
  35709. get: function () {
  35710. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  35711. return undefined;
  35712. },
  35713. set: function () {
  35714. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  35715. }
  35716. },
  35717. renderSingleSided: {
  35718. get: function () {
  35719. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  35720. return undefined;
  35721. },
  35722. set: function () {
  35723. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  35724. }
  35725. }
  35726. } );
  35727. function WebGLRenderTargetCube( width, height, options ) {
  35728. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  35729. return new WebGLCubeRenderTarget( width, options );
  35730. }
  35731. //
  35732. Object.defineProperties( WebGLRenderTarget.prototype, {
  35733. wrapS: {
  35734. get: function () {
  35735. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  35736. return this.texture.wrapS;
  35737. },
  35738. set: function ( value ) {
  35739. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  35740. this.texture.wrapS = value;
  35741. }
  35742. },
  35743. wrapT: {
  35744. get: function () {
  35745. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  35746. return this.texture.wrapT;
  35747. },
  35748. set: function ( value ) {
  35749. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  35750. this.texture.wrapT = value;
  35751. }
  35752. },
  35753. magFilter: {
  35754. get: function () {
  35755. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  35756. return this.texture.magFilter;
  35757. },
  35758. set: function ( value ) {
  35759. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  35760. this.texture.magFilter = value;
  35761. }
  35762. },
  35763. minFilter: {
  35764. get: function () {
  35765. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  35766. return this.texture.minFilter;
  35767. },
  35768. set: function ( value ) {
  35769. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  35770. this.texture.minFilter = value;
  35771. }
  35772. },
  35773. anisotropy: {
  35774. get: function () {
  35775. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  35776. return this.texture.anisotropy;
  35777. },
  35778. set: function ( value ) {
  35779. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  35780. this.texture.anisotropy = value;
  35781. }
  35782. },
  35783. offset: {
  35784. get: function () {
  35785. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  35786. return this.texture.offset;
  35787. },
  35788. set: function ( value ) {
  35789. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  35790. this.texture.offset = value;
  35791. }
  35792. },
  35793. repeat: {
  35794. get: function () {
  35795. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  35796. return this.texture.repeat;
  35797. },
  35798. set: function ( value ) {
  35799. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  35800. this.texture.repeat = value;
  35801. }
  35802. },
  35803. format: {
  35804. get: function () {
  35805. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  35806. return this.texture.format;
  35807. },
  35808. set: function ( value ) {
  35809. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  35810. this.texture.format = value;
  35811. }
  35812. },
  35813. type: {
  35814. get: function () {
  35815. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  35816. return this.texture.type;
  35817. },
  35818. set: function ( value ) {
  35819. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  35820. this.texture.type = value;
  35821. }
  35822. },
  35823. generateMipmaps: {
  35824. get: function () {
  35825. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  35826. return this.texture.generateMipmaps;
  35827. },
  35828. set: function ( value ) {
  35829. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  35830. this.texture.generateMipmaps = value;
  35831. }
  35832. }
  35833. } );
  35834. //
  35835. Object.defineProperties( Audio.prototype, {
  35836. load: {
  35837. value: function ( file ) {
  35838. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  35839. var scope = this;
  35840. var audioLoader = new AudioLoader();
  35841. audioLoader.load( file, function ( buffer ) {
  35842. scope.setBuffer( buffer );
  35843. } );
  35844. return this;
  35845. }
  35846. },
  35847. startTime: {
  35848. set: function () {
  35849. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  35850. }
  35851. }
  35852. } );
  35853. AudioAnalyser.prototype.getData = function () {
  35854. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  35855. return this.getFrequencyData();
  35856. };
  35857. //
  35858. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  35859. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  35860. return this.update( renderer, scene );
  35861. };
  35862. //
  35863. var GeometryUtils = {
  35864. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  35865. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  35866. var matrix;
  35867. if ( geometry2.isMesh ) {
  35868. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  35869. matrix = geometry2.matrix;
  35870. geometry2 = geometry2.geometry;
  35871. }
  35872. geometry1.merge( geometry2, matrix, materialIndexOffset );
  35873. },
  35874. center: function ( geometry ) {
  35875. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  35876. return geometry.center();
  35877. }
  35878. };
  35879. ImageUtils.crossOrigin = undefined;
  35880. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  35881. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  35882. var loader = new TextureLoader();
  35883. loader.setCrossOrigin( this.crossOrigin );
  35884. var texture = loader.load( url, onLoad, undefined, onError );
  35885. if ( mapping ) { texture.mapping = mapping; }
  35886. return texture;
  35887. };
  35888. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  35889. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  35890. var loader = new CubeTextureLoader();
  35891. loader.setCrossOrigin( this.crossOrigin );
  35892. var texture = loader.load( urls, onLoad, undefined, onError );
  35893. if ( mapping ) { texture.mapping = mapping; }
  35894. return texture;
  35895. };
  35896. ImageUtils.loadCompressedTexture = function () {
  35897. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  35898. };
  35899. ImageUtils.loadCompressedTextureCube = function () {
  35900. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  35901. };
  35902. //
  35903. function CanvasRenderer() {
  35904. console.error( 'THREE.CanvasRenderer has been removed' );
  35905. }
  35906. //
  35907. function JSONLoader() {
  35908. console.error( 'THREE.JSONLoader has been removed.' );
  35909. }
  35910. //
  35911. var SceneUtils = {
  35912. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  35913. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35914. },
  35915. detach: function ( /* child, parent, scene */ ) {
  35916. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35917. },
  35918. attach: function ( /* child, scene, parent */ ) {
  35919. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35920. }
  35921. };
  35922. //
  35923. function LensFlare() {
  35924. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  35925. }
  35926. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  35927. /* eslint-disable no-undef */
  35928. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  35929. revision: REVISION,
  35930. } } ) );
  35931. /* eslint-enable no-undef */
  35932. }
  35933. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  35934. exports.AddEquation = AddEquation;
  35935. exports.AddOperation = AddOperation;
  35936. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  35937. exports.AdditiveBlending = AdditiveBlending;
  35938. exports.AlphaFormat = AlphaFormat;
  35939. exports.AlwaysDepth = AlwaysDepth;
  35940. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  35941. exports.AmbientLight = AmbientLight;
  35942. exports.AmbientLightProbe = AmbientLightProbe;
  35943. exports.AnimationClip = AnimationClip;
  35944. exports.AnimationLoader = AnimationLoader;
  35945. exports.AnimationMixer = AnimationMixer;
  35946. exports.AnimationObjectGroup = AnimationObjectGroup;
  35947. exports.AnimationUtils = AnimationUtils;
  35948. exports.ArcCurve = ArcCurve;
  35949. exports.ArrayCamera = ArrayCamera;
  35950. exports.ArrowHelper = ArrowHelper;
  35951. exports.Audio = Audio;
  35952. exports.AudioAnalyser = AudioAnalyser;
  35953. exports.AudioContext = AudioContext;
  35954. exports.AudioListener = AudioListener;
  35955. exports.AudioLoader = AudioLoader;
  35956. exports.AxesHelper = AxesHelper;
  35957. exports.AxisHelper = AxisHelper;
  35958. exports.BackSide = BackSide;
  35959. exports.BasicDepthPacking = BasicDepthPacking;
  35960. exports.BasicShadowMap = BasicShadowMap;
  35961. exports.BinaryTextureLoader = BinaryTextureLoader;
  35962. exports.Bone = Bone;
  35963. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  35964. exports.BoundingBoxHelper = BoundingBoxHelper;
  35965. exports.Box2 = Box2;
  35966. exports.Box3 = Box3;
  35967. exports.Box3Helper = Box3Helper;
  35968. exports.BoxBufferGeometry = BoxBufferGeometry;
  35969. exports.BoxGeometry = BoxGeometry;
  35970. exports.BoxHelper = BoxHelper;
  35971. exports.BufferAttribute = BufferAttribute;
  35972. exports.BufferGeometry = BufferGeometry;
  35973. exports.BufferGeometryLoader = BufferGeometryLoader;
  35974. exports.ByteType = ByteType;
  35975. exports.Cache = Cache;
  35976. exports.Camera = Camera;
  35977. exports.CameraHelper = CameraHelper;
  35978. exports.CanvasRenderer = CanvasRenderer;
  35979. exports.CanvasTexture = CanvasTexture;
  35980. exports.CatmullRomCurve3 = CatmullRomCurve3;
  35981. exports.CineonToneMapping = CineonToneMapping;
  35982. exports.CircleBufferGeometry = CircleBufferGeometry;
  35983. exports.CircleGeometry = CircleGeometry;
  35984. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  35985. exports.Clock = Clock;
  35986. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  35987. exports.Color = Color;
  35988. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  35989. exports.CompressedTexture = CompressedTexture;
  35990. exports.CompressedTextureLoader = CompressedTextureLoader;
  35991. exports.ConeBufferGeometry = ConeBufferGeometry;
  35992. exports.ConeGeometry = ConeGeometry;
  35993. exports.CubeCamera = CubeCamera;
  35994. exports.CubeGeometry = BoxGeometry;
  35995. exports.CubeReflectionMapping = CubeReflectionMapping;
  35996. exports.CubeRefractionMapping = CubeRefractionMapping;
  35997. exports.CubeTexture = CubeTexture;
  35998. exports.CubeTextureLoader = CubeTextureLoader;
  35999. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  36000. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  36001. exports.CubicBezierCurve = CubicBezierCurve;
  36002. exports.CubicBezierCurve3 = CubicBezierCurve3;
  36003. exports.CubicInterpolant = CubicInterpolant;
  36004. exports.CullFaceBack = CullFaceBack;
  36005. exports.CullFaceFront = CullFaceFront;
  36006. exports.CullFaceFrontBack = CullFaceFrontBack;
  36007. exports.CullFaceNone = CullFaceNone;
  36008. exports.Curve = Curve;
  36009. exports.CurvePath = CurvePath;
  36010. exports.CustomBlending = CustomBlending;
  36011. exports.CustomToneMapping = CustomToneMapping;
  36012. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  36013. exports.CylinderGeometry = CylinderGeometry;
  36014. exports.Cylindrical = Cylindrical;
  36015. exports.DataTexture = DataTexture;
  36016. exports.DataTexture2DArray = DataTexture2DArray;
  36017. exports.DataTexture3D = DataTexture3D;
  36018. exports.DataTextureLoader = DataTextureLoader;
  36019. exports.DecrementStencilOp = DecrementStencilOp;
  36020. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  36021. exports.DefaultLoadingManager = DefaultLoadingManager;
  36022. exports.DepthFormat = DepthFormat;
  36023. exports.DepthStencilFormat = DepthStencilFormat;
  36024. exports.DepthTexture = DepthTexture;
  36025. exports.DirectionalLight = DirectionalLight;
  36026. exports.DirectionalLightHelper = DirectionalLightHelper;
  36027. exports.DirectionalLightShadow = DirectionalLightShadow;
  36028. exports.DiscreteInterpolant = DiscreteInterpolant;
  36029. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  36030. exports.DodecahedronGeometry = DodecahedronGeometry;
  36031. exports.DoubleSide = DoubleSide;
  36032. exports.DstAlphaFactor = DstAlphaFactor;
  36033. exports.DstColorFactor = DstColorFactor;
  36034. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  36035. exports.DynamicCopyUsage = DynamicCopyUsage;
  36036. exports.DynamicDrawUsage = DynamicDrawUsage;
  36037. exports.DynamicReadUsage = DynamicReadUsage;
  36038. exports.EdgesGeometry = EdgesGeometry;
  36039. exports.EdgesHelper = EdgesHelper;
  36040. exports.EllipseCurve = EllipseCurve;
  36041. exports.EqualDepth = EqualDepth;
  36042. exports.EqualStencilFunc = EqualStencilFunc;
  36043. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  36044. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  36045. exports.Euler = Euler;
  36046. exports.EventDispatcher = EventDispatcher;
  36047. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  36048. exports.ExtrudeGeometry = ExtrudeGeometry;
  36049. exports.Face3 = Face3;
  36050. exports.Face4 = Face4;
  36051. exports.FaceColors = FaceColors;
  36052. exports.FileLoader = FileLoader;
  36053. exports.FlatShading = FlatShading;
  36054. exports.Float32Attribute = Float32Attribute;
  36055. exports.Float32BufferAttribute = Float32BufferAttribute;
  36056. exports.Float64Attribute = Float64Attribute;
  36057. exports.Float64BufferAttribute = Float64BufferAttribute;
  36058. exports.FloatType = FloatType;
  36059. exports.Fog = Fog;
  36060. exports.FogExp2 = FogExp2;
  36061. exports.Font = Font;
  36062. exports.FontLoader = FontLoader;
  36063. exports.FrontSide = FrontSide;
  36064. exports.Frustum = Frustum;
  36065. exports.GammaEncoding = GammaEncoding;
  36066. exports.Geometry = Geometry;
  36067. exports.GeometryUtils = GeometryUtils;
  36068. exports.GreaterDepth = GreaterDepth;
  36069. exports.GreaterEqualDepth = GreaterEqualDepth;
  36070. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  36071. exports.GreaterStencilFunc = GreaterStencilFunc;
  36072. exports.GridHelper = GridHelper;
  36073. exports.Group = Group;
  36074. exports.HalfFloatType = HalfFloatType;
  36075. exports.HemisphereLight = HemisphereLight;
  36076. exports.HemisphereLightHelper = HemisphereLightHelper;
  36077. exports.HemisphereLightProbe = HemisphereLightProbe;
  36078. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  36079. exports.IcosahedronGeometry = IcosahedronGeometry;
  36080. exports.ImageBitmapLoader = ImageBitmapLoader;
  36081. exports.ImageLoader = ImageLoader;
  36082. exports.ImageUtils = ImageUtils;
  36083. exports.ImmediateRenderObject = ImmediateRenderObject;
  36084. exports.IncrementStencilOp = IncrementStencilOp;
  36085. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  36086. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  36087. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  36088. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  36089. exports.InstancedMesh = InstancedMesh;
  36090. exports.Int16Attribute = Int16Attribute;
  36091. exports.Int16BufferAttribute = Int16BufferAttribute;
  36092. exports.Int32Attribute = Int32Attribute;
  36093. exports.Int32BufferAttribute = Int32BufferAttribute;
  36094. exports.Int8Attribute = Int8Attribute;
  36095. exports.Int8BufferAttribute = Int8BufferAttribute;
  36096. exports.IntType = IntType;
  36097. exports.InterleavedBuffer = InterleavedBuffer;
  36098. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  36099. exports.Interpolant = Interpolant;
  36100. exports.InterpolateDiscrete = InterpolateDiscrete;
  36101. exports.InterpolateLinear = InterpolateLinear;
  36102. exports.InterpolateSmooth = InterpolateSmooth;
  36103. exports.InvertStencilOp = InvertStencilOp;
  36104. exports.JSONLoader = JSONLoader;
  36105. exports.KeepStencilOp = KeepStencilOp;
  36106. exports.KeyframeTrack = KeyframeTrack;
  36107. exports.LOD = LOD;
  36108. exports.LatheBufferGeometry = LatheBufferGeometry;
  36109. exports.LatheGeometry = LatheGeometry;
  36110. exports.Layers = Layers;
  36111. exports.LensFlare = LensFlare;
  36112. exports.LessDepth = LessDepth;
  36113. exports.LessEqualDepth = LessEqualDepth;
  36114. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  36115. exports.LessStencilFunc = LessStencilFunc;
  36116. exports.Light = Light;
  36117. exports.LightProbe = LightProbe;
  36118. exports.LightShadow = LightShadow;
  36119. exports.Line = Line;
  36120. exports.Line3 = Line3;
  36121. exports.LineBasicMaterial = LineBasicMaterial;
  36122. exports.LineCurve = LineCurve;
  36123. exports.LineCurve3 = LineCurve3;
  36124. exports.LineDashedMaterial = LineDashedMaterial;
  36125. exports.LineLoop = LineLoop;
  36126. exports.LinePieces = LinePieces;
  36127. exports.LineSegments = LineSegments;
  36128. exports.LineStrip = LineStrip;
  36129. exports.LinearEncoding = LinearEncoding;
  36130. exports.LinearFilter = LinearFilter;
  36131. exports.LinearInterpolant = LinearInterpolant;
  36132. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  36133. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  36134. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  36135. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  36136. exports.LinearToneMapping = LinearToneMapping;
  36137. exports.Loader = Loader;
  36138. exports.LoaderUtils = LoaderUtils;
  36139. exports.LoadingManager = LoadingManager;
  36140. exports.LogLuvEncoding = LogLuvEncoding;
  36141. exports.LoopOnce = LoopOnce;
  36142. exports.LoopPingPong = LoopPingPong;
  36143. exports.LoopRepeat = LoopRepeat;
  36144. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  36145. exports.LuminanceFormat = LuminanceFormat;
  36146. exports.MOUSE = MOUSE;
  36147. exports.Material = Material;
  36148. exports.MaterialLoader = MaterialLoader;
  36149. exports.Math = MathUtils;
  36150. exports.MathUtils = MathUtils;
  36151. exports.Matrix3 = Matrix3;
  36152. exports.Matrix4 = Matrix4;
  36153. exports.MaxEquation = MaxEquation;
  36154. exports.Mesh = Mesh;
  36155. exports.MeshBasicMaterial = MeshBasicMaterial;
  36156. exports.MeshDepthMaterial = MeshDepthMaterial;
  36157. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  36158. exports.MeshFaceMaterial = MeshFaceMaterial;
  36159. exports.MeshLambertMaterial = MeshLambertMaterial;
  36160. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  36161. exports.MeshNormalMaterial = MeshNormalMaterial;
  36162. exports.MeshPhongMaterial = MeshPhongMaterial;
  36163. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  36164. exports.MeshStandardMaterial = MeshStandardMaterial;
  36165. exports.MeshToonMaterial = MeshToonMaterial;
  36166. exports.MinEquation = MinEquation;
  36167. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  36168. exports.MixOperation = MixOperation;
  36169. exports.MultiMaterial = MultiMaterial;
  36170. exports.MultiplyBlending = MultiplyBlending;
  36171. exports.MultiplyOperation = MultiplyOperation;
  36172. exports.NearestFilter = NearestFilter;
  36173. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  36174. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  36175. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  36176. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  36177. exports.NeverDepth = NeverDepth;
  36178. exports.NeverStencilFunc = NeverStencilFunc;
  36179. exports.NoBlending = NoBlending;
  36180. exports.NoColors = NoColors;
  36181. exports.NoToneMapping = NoToneMapping;
  36182. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  36183. exports.NormalBlending = NormalBlending;
  36184. exports.NotEqualDepth = NotEqualDepth;
  36185. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  36186. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  36187. exports.Object3D = Object3D;
  36188. exports.ObjectLoader = ObjectLoader;
  36189. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  36190. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  36191. exports.OctahedronGeometry = OctahedronGeometry;
  36192. exports.OneFactor = OneFactor;
  36193. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  36194. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  36195. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  36196. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  36197. exports.OrthographicCamera = OrthographicCamera;
  36198. exports.PCFShadowMap = PCFShadowMap;
  36199. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  36200. exports.PMREMGenerator = PMREMGenerator;
  36201. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  36202. exports.ParametricGeometry = ParametricGeometry;
  36203. exports.Particle = Particle;
  36204. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  36205. exports.ParticleSystem = ParticleSystem;
  36206. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  36207. exports.Path = Path;
  36208. exports.PerspectiveCamera = PerspectiveCamera;
  36209. exports.Plane = Plane;
  36210. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  36211. exports.PlaneGeometry = PlaneGeometry;
  36212. exports.PlaneHelper = PlaneHelper;
  36213. exports.PointCloud = PointCloud;
  36214. exports.PointCloudMaterial = PointCloudMaterial;
  36215. exports.PointLight = PointLight;
  36216. exports.PointLightHelper = PointLightHelper;
  36217. exports.Points = Points;
  36218. exports.PointsMaterial = PointsMaterial;
  36219. exports.PolarGridHelper = PolarGridHelper;
  36220. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  36221. exports.PolyhedronGeometry = PolyhedronGeometry;
  36222. exports.PositionalAudio = PositionalAudio;
  36223. exports.PropertyBinding = PropertyBinding;
  36224. exports.PropertyMixer = PropertyMixer;
  36225. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  36226. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  36227. exports.Quaternion = Quaternion;
  36228. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  36229. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  36230. exports.REVISION = REVISION;
  36231. exports.RGBADepthPacking = RGBADepthPacking;
  36232. exports.RGBAFormat = RGBAFormat;
  36233. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  36234. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  36235. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  36236. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  36237. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  36238. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  36239. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  36240. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  36241. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  36242. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  36243. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  36244. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  36245. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  36246. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  36247. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  36248. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  36249. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  36250. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  36251. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  36252. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  36253. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  36254. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  36255. exports.RGBDEncoding = RGBDEncoding;
  36256. exports.RGBEEncoding = RGBEEncoding;
  36257. exports.RGBEFormat = RGBEFormat;
  36258. exports.RGBFormat = RGBFormat;
  36259. exports.RGBIntegerFormat = RGBIntegerFormat;
  36260. exports.RGBM16Encoding = RGBM16Encoding;
  36261. exports.RGBM7Encoding = RGBM7Encoding;
  36262. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  36263. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  36264. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  36265. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  36266. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  36267. exports.RGFormat = RGFormat;
  36268. exports.RGIntegerFormat = RGIntegerFormat;
  36269. exports.RawShaderMaterial = RawShaderMaterial;
  36270. exports.Ray = Ray;
  36271. exports.Raycaster = Raycaster;
  36272. exports.RectAreaLight = RectAreaLight;
  36273. exports.RedFormat = RedFormat;
  36274. exports.RedIntegerFormat = RedIntegerFormat;
  36275. exports.ReinhardToneMapping = ReinhardToneMapping;
  36276. exports.RepeatWrapping = RepeatWrapping;
  36277. exports.ReplaceStencilOp = ReplaceStencilOp;
  36278. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  36279. exports.RingBufferGeometry = RingBufferGeometry;
  36280. exports.RingGeometry = RingGeometry;
  36281. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  36282. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  36283. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  36284. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  36285. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  36286. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  36287. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  36288. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  36289. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  36290. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  36291. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  36292. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  36293. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  36294. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  36295. exports.Scene = Scene;
  36296. exports.SceneUtils = SceneUtils;
  36297. exports.ShaderChunk = ShaderChunk;
  36298. exports.ShaderLib = ShaderLib;
  36299. exports.ShaderMaterial = ShaderMaterial;
  36300. exports.ShadowMaterial = ShadowMaterial;
  36301. exports.Shape = Shape;
  36302. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  36303. exports.ShapeGeometry = ShapeGeometry;
  36304. exports.ShapePath = ShapePath;
  36305. exports.ShapeUtils = ShapeUtils;
  36306. exports.ShortType = ShortType;
  36307. exports.Skeleton = Skeleton;
  36308. exports.SkeletonHelper = SkeletonHelper;
  36309. exports.SkinnedMesh = SkinnedMesh;
  36310. exports.SmoothShading = SmoothShading;
  36311. exports.Sphere = Sphere;
  36312. exports.SphereBufferGeometry = SphereBufferGeometry;
  36313. exports.SphereGeometry = SphereGeometry;
  36314. exports.Spherical = Spherical;
  36315. exports.SphericalHarmonics3 = SphericalHarmonics3;
  36316. exports.Spline = Spline;
  36317. exports.SplineCurve = SplineCurve;
  36318. exports.SplineCurve3 = SplineCurve3;
  36319. exports.SpotLight = SpotLight;
  36320. exports.SpotLightHelper = SpotLightHelper;
  36321. exports.SpotLightShadow = SpotLightShadow;
  36322. exports.Sprite = Sprite;
  36323. exports.SpriteMaterial = SpriteMaterial;
  36324. exports.SrcAlphaFactor = SrcAlphaFactor;
  36325. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  36326. exports.SrcColorFactor = SrcColorFactor;
  36327. exports.StaticCopyUsage = StaticCopyUsage;
  36328. exports.StaticDrawUsage = StaticDrawUsage;
  36329. exports.StaticReadUsage = StaticReadUsage;
  36330. exports.StereoCamera = StereoCamera;
  36331. exports.StreamCopyUsage = StreamCopyUsage;
  36332. exports.StreamDrawUsage = StreamDrawUsage;
  36333. exports.StreamReadUsage = StreamReadUsage;
  36334. exports.StringKeyframeTrack = StringKeyframeTrack;
  36335. exports.SubtractEquation = SubtractEquation;
  36336. exports.SubtractiveBlending = SubtractiveBlending;
  36337. exports.TOUCH = TOUCH;
  36338. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  36339. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  36340. exports.TetrahedronGeometry = TetrahedronGeometry;
  36341. exports.TextBufferGeometry = TextBufferGeometry;
  36342. exports.TextGeometry = TextGeometry;
  36343. exports.Texture = Texture;
  36344. exports.TextureLoader = TextureLoader;
  36345. exports.TorusBufferGeometry = TorusBufferGeometry;
  36346. exports.TorusGeometry = TorusGeometry;
  36347. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  36348. exports.TorusKnotGeometry = TorusKnotGeometry;
  36349. exports.Triangle = Triangle;
  36350. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  36351. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  36352. exports.TrianglesDrawMode = TrianglesDrawMode;
  36353. exports.TubeBufferGeometry = TubeBufferGeometry;
  36354. exports.TubeGeometry = TubeGeometry;
  36355. exports.UVMapping = UVMapping;
  36356. exports.Uint16Attribute = Uint16Attribute;
  36357. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  36358. exports.Uint32Attribute = Uint32Attribute;
  36359. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  36360. exports.Uint8Attribute = Uint8Attribute;
  36361. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  36362. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  36363. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  36364. exports.Uniform = Uniform;
  36365. exports.UniformsLib = UniformsLib;
  36366. exports.UniformsUtils = UniformsUtils;
  36367. exports.UnsignedByteType = UnsignedByteType;
  36368. exports.UnsignedInt248Type = UnsignedInt248Type;
  36369. exports.UnsignedIntType = UnsignedIntType;
  36370. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  36371. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  36372. exports.UnsignedShort565Type = UnsignedShort565Type;
  36373. exports.UnsignedShortType = UnsignedShortType;
  36374. exports.VSMShadowMap = VSMShadowMap;
  36375. exports.Vector2 = Vector2;
  36376. exports.Vector3 = Vector3;
  36377. exports.Vector4 = Vector4;
  36378. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  36379. exports.Vertex = Vertex;
  36380. exports.VertexColors = VertexColors;
  36381. exports.VideoTexture = VideoTexture;
  36382. exports.WebGL1Renderer = WebGL1Renderer;
  36383. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  36384. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  36385. exports.WebGLRenderTarget = WebGLRenderTarget;
  36386. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  36387. exports.WebGLRenderer = WebGLRenderer;
  36388. exports.WebGLUtils = WebGLUtils;
  36389. exports.WireframeGeometry = WireframeGeometry;
  36390. exports.WireframeHelper = WireframeHelper;
  36391. exports.WrapAroundEnding = WrapAroundEnding;
  36392. exports.XHRLoader = XHRLoader;
  36393. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  36394. exports.ZeroFactor = ZeroFactor;
  36395. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  36396. exports.ZeroStencilOp = ZeroStencilOp;
  36397. exports.sRGBEncoding = sRGBEncoding;
  36398. Object.defineProperty(exports, '__esModule', { value: true });
  36399. })));
  36400. },{}],58:[function(_dereq_,module,exports){
  36401. console.warn( "THREE.DRACOLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  36402. THREE.DRACOLoader = function ( manager ) {
  36403. THREE.Loader.call( this, manager );
  36404. this.decoderPath = '';
  36405. this.decoderConfig = {};
  36406. this.decoderBinary = null;
  36407. this.decoderPending = null;
  36408. this.workerLimit = 4;
  36409. this.workerPool = [];
  36410. this.workerNextTaskID = 1;
  36411. this.workerSourceURL = '';
  36412. this.defaultAttributeIDs = {
  36413. position: 'POSITION',
  36414. normal: 'NORMAL',
  36415. color: 'COLOR',
  36416. uv: 'TEX_COORD'
  36417. };
  36418. this.defaultAttributeTypes = {
  36419. position: 'Float32Array',
  36420. normal: 'Float32Array',
  36421. color: 'Float32Array',
  36422. uv: 'Float32Array'
  36423. };
  36424. };
  36425. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36426. constructor: THREE.DRACOLoader,
  36427. setDecoderPath: function ( path ) {
  36428. this.decoderPath = path;
  36429. return this;
  36430. },
  36431. setDecoderConfig: function ( config ) {
  36432. this.decoderConfig = config;
  36433. return this;
  36434. },
  36435. setWorkerLimit: function ( workerLimit ) {
  36436. this.workerLimit = workerLimit;
  36437. return this;
  36438. },
  36439. /** @deprecated */
  36440. setVerbosity: function () {
  36441. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  36442. },
  36443. /** @deprecated */
  36444. setDrawMode: function () {
  36445. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  36446. },
  36447. /** @deprecated */
  36448. setSkipDequantization: function () {
  36449. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  36450. },
  36451. load: function ( url, onLoad, onProgress, onError ) {
  36452. var loader = new THREE.FileLoader( this.manager );
  36453. loader.setPath( this.path );
  36454. loader.setResponseType( 'arraybuffer' );
  36455. loader.setRequestHeader( this.requestHeader );
  36456. if ( this.crossOrigin === 'use-credentials' ) {
  36457. loader.setWithCredentials( true );
  36458. }
  36459. loader.load( url, ( buffer ) => {
  36460. var taskConfig = {
  36461. attributeIDs: this.defaultAttributeIDs,
  36462. attributeTypes: this.defaultAttributeTypes,
  36463. useUniqueIDs: false
  36464. };
  36465. this.decodeGeometry( buffer, taskConfig )
  36466. .then( onLoad )
  36467. .catch( onError );
  36468. }, onProgress, onError );
  36469. },
  36470. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  36471. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  36472. var taskConfig = {
  36473. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  36474. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  36475. useUniqueIDs: !! attributeIDs
  36476. };
  36477. this.decodeGeometry( buffer, taskConfig ).then( callback );
  36478. },
  36479. decodeGeometry: function ( buffer, taskConfig ) {
  36480. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  36481. // references (rather than names) to typed array constructors. These must be
  36482. // serialized before sending them to the worker.
  36483. for ( var attribute in taskConfig.attributeTypes ) {
  36484. var type = taskConfig.attributeTypes[ attribute ];
  36485. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  36486. taskConfig.attributeTypes[ attribute ] = type.name;
  36487. }
  36488. }
  36489. //
  36490. var taskKey = JSON.stringify( taskConfig );
  36491. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  36492. // again from this thread.
  36493. if ( THREE.DRACOLoader.taskCache.has( buffer ) ) {
  36494. var cachedTask = THREE.DRACOLoader.taskCache.get( buffer );
  36495. if ( cachedTask.key === taskKey ) {
  36496. return cachedTask.promise;
  36497. } else if ( buffer.byteLength === 0 ) {
  36498. // Technically, it would be possible to wait for the previous task to complete,
  36499. // transfer the buffer back, and decode again with the second configuration. That
  36500. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  36501. // different ways, so this is left unimplemented.
  36502. throw new Error(
  36503. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  36504. 'settings. Buffer has already been transferred.'
  36505. );
  36506. }
  36507. }
  36508. //
  36509. var worker;
  36510. var taskID = this.workerNextTaskID ++;
  36511. var taskCost = buffer.byteLength;
  36512. // Obtain a worker and assign a task, and construct a geometry instance
  36513. // when the task completes.
  36514. var geometryPending = this._getWorker( taskID, taskCost )
  36515. .then( ( _worker ) => {
  36516. worker = _worker;
  36517. return new Promise( ( resolve, reject ) => {
  36518. worker._callbacks[ taskID ] = { resolve, reject };
  36519. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  36520. // this.debug();
  36521. } );
  36522. } )
  36523. .then( ( message ) => this._createGeometry( message.geometry ) );
  36524. // Remove task from the task list.
  36525. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  36526. geometryPending
  36527. .catch( () => true )
  36528. .then( () => {
  36529. if ( worker && taskID ) {
  36530. this._releaseTask( worker, taskID );
  36531. // this.debug();
  36532. }
  36533. } );
  36534. // Cache the task result.
  36535. THREE.DRACOLoader.taskCache.set( buffer, {
  36536. key: taskKey,
  36537. promise: geometryPending
  36538. } );
  36539. return geometryPending;
  36540. },
  36541. _createGeometry: function ( geometryData ) {
  36542. var geometry = new THREE.BufferGeometry();
  36543. if ( geometryData.index ) {
  36544. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  36545. }
  36546. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  36547. var attribute = geometryData.attributes[ i ];
  36548. var name = attribute.name;
  36549. var array = attribute.array;
  36550. var itemSize = attribute.itemSize;
  36551. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  36552. }
  36553. return geometry;
  36554. },
  36555. _loadLibrary: function ( url, responseType ) {
  36556. var loader = new THREE.FileLoader( this.manager );
  36557. loader.setPath( this.decoderPath );
  36558. loader.setResponseType( responseType );
  36559. return new Promise( ( resolve, reject ) => {
  36560. loader.load( url, resolve, undefined, reject );
  36561. } );
  36562. },
  36563. preload: function () {
  36564. this._initDecoder();
  36565. return this;
  36566. },
  36567. _initDecoder: function () {
  36568. if ( this.decoderPending ) return this.decoderPending;
  36569. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  36570. var librariesPending = [];
  36571. if ( useJS ) {
  36572. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  36573. } else {
  36574. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  36575. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  36576. }
  36577. this.decoderPending = Promise.all( librariesPending )
  36578. .then( ( libraries ) => {
  36579. var jsContent = libraries[ 0 ];
  36580. if ( ! useJS ) {
  36581. this.decoderConfig.wasmBinary = libraries[ 1 ];
  36582. }
  36583. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  36584. var body = [
  36585. '/* draco decoder */',
  36586. jsContent,
  36587. '',
  36588. '/* worker */',
  36589. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  36590. ].join( '\n' );
  36591. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  36592. } );
  36593. return this.decoderPending;
  36594. },
  36595. _getWorker: function ( taskID, taskCost ) {
  36596. return this._initDecoder().then( () => {
  36597. if ( this.workerPool.length < this.workerLimit ) {
  36598. var worker = new Worker( this.workerSourceURL );
  36599. worker._callbacks = {};
  36600. worker._taskCosts = {};
  36601. worker._taskLoad = 0;
  36602. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  36603. worker.onmessage = function ( e ) {
  36604. var message = e.data;
  36605. switch ( message.type ) {
  36606. case 'decode':
  36607. worker._callbacks[ message.id ].resolve( message );
  36608. break;
  36609. case 'error':
  36610. worker._callbacks[ message.id ].reject( message );
  36611. break;
  36612. default:
  36613. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  36614. }
  36615. };
  36616. this.workerPool.push( worker );
  36617. } else {
  36618. this.workerPool.sort( function ( a, b ) {
  36619. return a._taskLoad > b._taskLoad ? - 1 : 1;
  36620. } );
  36621. }
  36622. var worker = this.workerPool[ this.workerPool.length - 1 ];
  36623. worker._taskCosts[ taskID ] = taskCost;
  36624. worker._taskLoad += taskCost;
  36625. return worker;
  36626. } );
  36627. },
  36628. _releaseTask: function ( worker, taskID ) {
  36629. worker._taskLoad -= worker._taskCosts[ taskID ];
  36630. delete worker._callbacks[ taskID ];
  36631. delete worker._taskCosts[ taskID ];
  36632. },
  36633. debug: function () {
  36634. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  36635. },
  36636. dispose: function () {
  36637. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  36638. this.workerPool[ i ].terminate();
  36639. }
  36640. this.workerPool.length = 0;
  36641. return this;
  36642. }
  36643. } );
  36644. /* WEB WORKER */
  36645. THREE.DRACOLoader.DRACOWorker = function () {
  36646. var decoderConfig;
  36647. var decoderPending;
  36648. onmessage = function ( e ) {
  36649. var message = e.data;
  36650. switch ( message.type ) {
  36651. case 'init':
  36652. decoderConfig = message.decoderConfig;
  36653. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  36654. decoderConfig.onModuleLoaded = function ( draco ) {
  36655. // Module is Promise-like. Wrap before resolving to avoid loop.
  36656. resolve( { draco: draco } );
  36657. };
  36658. DracoDecoderModule( decoderConfig );
  36659. } );
  36660. break;
  36661. case 'decode':
  36662. var buffer = message.buffer;
  36663. var taskConfig = message.taskConfig;
  36664. decoderPending.then( ( module ) => {
  36665. var draco = module.draco;
  36666. var decoder = new draco.Decoder();
  36667. var decoderBuffer = new draco.DecoderBuffer();
  36668. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  36669. try {
  36670. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  36671. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  36672. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  36673. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  36674. } catch ( error ) {
  36675. console.error( error );
  36676. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  36677. } finally {
  36678. draco.destroy( decoderBuffer );
  36679. draco.destroy( decoder );
  36680. }
  36681. } );
  36682. break;
  36683. }
  36684. };
  36685. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  36686. var attributeIDs = taskConfig.attributeIDs;
  36687. var attributeTypes = taskConfig.attributeTypes;
  36688. var dracoGeometry;
  36689. var decodingStatus;
  36690. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  36691. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36692. dracoGeometry = new draco.Mesh();
  36693. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  36694. } else if ( geometryType === draco.POINT_CLOUD ) {
  36695. dracoGeometry = new draco.PointCloud();
  36696. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  36697. } else {
  36698. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  36699. }
  36700. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  36701. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  36702. }
  36703. var geometry = { index: null, attributes: [] };
  36704. // Gather all vertex attributes.
  36705. for ( var attributeName in attributeIDs ) {
  36706. var attributeType = self[ attributeTypes[ attributeName ] ];
  36707. var attribute;
  36708. var attributeID;
  36709. // A Draco file may be created with default vertex attributes, whose attribute IDs
  36710. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  36711. // a Draco file may contain a custom set of attributes, identified by known unique
  36712. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  36713. if ( taskConfig.useUniqueIDs ) {
  36714. attributeID = attributeIDs[ attributeName ];
  36715. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  36716. } else {
  36717. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  36718. if ( attributeID === - 1 ) continue;
  36719. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  36720. }
  36721. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  36722. }
  36723. // Add index.
  36724. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36725. // Generate mesh faces.
  36726. var numFaces = dracoGeometry.num_faces();
  36727. var numIndices = numFaces * 3;
  36728. var index = new Uint32Array( numIndices );
  36729. var indexArray = new draco.DracoInt32Array();
  36730. for ( var i = 0; i < numFaces; ++ i ) {
  36731. decoder.GetFaceFromMesh( dracoGeometry, i, indexArray );
  36732. for ( var j = 0; j < 3; ++ j ) {
  36733. index[ i * 3 + j ] = indexArray.GetValue( j );
  36734. }
  36735. }
  36736. geometry.index = { array: index, itemSize: 1 };
  36737. draco.destroy( indexArray );
  36738. }
  36739. draco.destroy( dracoGeometry );
  36740. return geometry;
  36741. }
  36742. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  36743. var numComponents = attribute.num_components();
  36744. var numPoints = dracoGeometry.num_points();
  36745. var numValues = numPoints * numComponents;
  36746. var dracoArray;
  36747. var array;
  36748. switch ( attributeType ) {
  36749. case Float32Array:
  36750. dracoArray = new draco.DracoFloat32Array();
  36751. decoder.GetAttributeFloatForAllPoints( dracoGeometry, attribute, dracoArray );
  36752. array = new Float32Array( numValues );
  36753. break;
  36754. case Int8Array:
  36755. dracoArray = new draco.DracoInt8Array();
  36756. decoder.GetAttributeInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  36757. array = new Int8Array( numValues );
  36758. break;
  36759. case Int16Array:
  36760. dracoArray = new draco.DracoInt16Array();
  36761. decoder.GetAttributeInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  36762. array = new Int16Array( numValues );
  36763. break;
  36764. case Int32Array:
  36765. dracoArray = new draco.DracoInt32Array();
  36766. decoder.GetAttributeInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  36767. array = new Int32Array( numValues );
  36768. break;
  36769. case Uint8Array:
  36770. dracoArray = new draco.DracoUInt8Array();
  36771. decoder.GetAttributeUInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  36772. array = new Uint8Array( numValues );
  36773. break;
  36774. case Uint16Array:
  36775. dracoArray = new draco.DracoUInt16Array();
  36776. decoder.GetAttributeUInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  36777. array = new Uint16Array( numValues );
  36778. break;
  36779. case Uint32Array:
  36780. dracoArray = new draco.DracoUInt32Array();
  36781. decoder.GetAttributeUInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  36782. array = new Uint32Array( numValues );
  36783. break;
  36784. default:
  36785. throw new Error( 'THREE.DRACOLoader: Unexpected attribute type.' );
  36786. }
  36787. for ( var i = 0; i < numValues; i ++ ) {
  36788. array[ i ] = dracoArray.GetValue( i );
  36789. }
  36790. draco.destroy( dracoArray );
  36791. return {
  36792. name: attributeName,
  36793. array: array,
  36794. itemSize: numComponents
  36795. };
  36796. }
  36797. };
  36798. THREE.DRACOLoader.taskCache = new WeakMap();
  36799. /** Deprecated static methods */
  36800. /** @deprecated */
  36801. THREE.DRACOLoader.setDecoderPath = function () {
  36802. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  36803. };
  36804. /** @deprecated */
  36805. THREE.DRACOLoader.setDecoderConfig = function () {
  36806. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  36807. };
  36808. /** @deprecated */
  36809. THREE.DRACOLoader.releaseDecoderModule = function () {
  36810. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  36811. };
  36812. /** @deprecated */
  36813. THREE.DRACOLoader.getDecoderModule = function () {
  36814. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  36815. };
  36816. },{}],59:[function(_dereq_,module,exports){
  36817. console.warn( "THREE.GLTFLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  36818. THREE.GLTFLoader = ( function () {
  36819. function GLTFLoader( manager ) {
  36820. THREE.Loader.call( this, manager );
  36821. this.dracoLoader = null;
  36822. this.ddsLoader = null;
  36823. this.ktx2Loader = null;
  36824. this.pluginCallbacks = [];
  36825. this.register( function ( parser ) {
  36826. return new GLTFMaterialsClearcoatExtension( parser );
  36827. } );
  36828. this.register( function ( parser ) {
  36829. return new GLTFTextureBasisUExtension( parser );
  36830. } );
  36831. this.register( function ( parser ) {
  36832. return new GLTFMaterialsTransmissionExtension( parser );
  36833. } );
  36834. }
  36835. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36836. constructor: GLTFLoader,
  36837. load: function ( url, onLoad, onProgress, onError ) {
  36838. var scope = this;
  36839. var resourcePath;
  36840. if ( this.resourcePath !== '' ) {
  36841. resourcePath = this.resourcePath;
  36842. } else if ( this.path !== '' ) {
  36843. resourcePath = this.path;
  36844. } else {
  36845. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  36846. }
  36847. // Tells the LoadingManager to track an extra item, which resolves after
  36848. // the model is fully loaded. This means the count of items loaded will
  36849. // be incorrect, but ensures manager.onLoad() does not fire early.
  36850. scope.manager.itemStart( url );
  36851. var _onError = function ( e ) {
  36852. if ( onError ) {
  36853. onError( e );
  36854. } else {
  36855. console.error( e );
  36856. }
  36857. scope.manager.itemError( url );
  36858. scope.manager.itemEnd( url );
  36859. };
  36860. var loader = new THREE.FileLoader( scope.manager );
  36861. loader.setPath( this.path );
  36862. loader.setResponseType( 'arraybuffer' );
  36863. loader.setRequestHeader( this.requestHeader );
  36864. if ( scope.crossOrigin === 'use-credentials' ) {
  36865. loader.setWithCredentials( true );
  36866. }
  36867. loader.load( url, function ( data ) {
  36868. try {
  36869. scope.parse( data, resourcePath, function ( gltf ) {
  36870. onLoad( gltf );
  36871. scope.manager.itemEnd( url );
  36872. }, _onError );
  36873. } catch ( e ) {
  36874. _onError( e );
  36875. }
  36876. }, onProgress, _onError );
  36877. },
  36878. setDRACOLoader: function ( dracoLoader ) {
  36879. this.dracoLoader = dracoLoader;
  36880. return this;
  36881. },
  36882. setDDSLoader: function ( ddsLoader ) {
  36883. this.ddsLoader = ddsLoader;
  36884. return this;
  36885. },
  36886. setKTX2Loader: function ( ktx2Loader ) {
  36887. this.ktx2Loader = ktx2Loader;
  36888. return this;
  36889. },
  36890. register: function ( callback ) {
  36891. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  36892. this.pluginCallbacks.push( callback );
  36893. }
  36894. return this;
  36895. },
  36896. unregister: function ( callback ) {
  36897. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  36898. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  36899. }
  36900. return this;
  36901. },
  36902. parse: function ( data, path, onLoad, onError ) {
  36903. var content;
  36904. var extensions = {};
  36905. var plugins = {};
  36906. if ( typeof data === 'string' ) {
  36907. content = data;
  36908. } else {
  36909. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  36910. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  36911. try {
  36912. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  36913. } catch ( error ) {
  36914. if ( onError ) onError( error );
  36915. return;
  36916. }
  36917. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36918. } else {
  36919. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  36920. }
  36921. }
  36922. var json = JSON.parse( content );
  36923. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  36924. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  36925. return;
  36926. }
  36927. var parser = new GLTFParser( json, {
  36928. path: path || this.resourcePath || '',
  36929. crossOrigin: this.crossOrigin,
  36930. manager: this.manager,
  36931. ktx2Loader: this.ktx2Loader
  36932. } );
  36933. parser.fileLoader.setRequestHeader( this.requestHeader );
  36934. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  36935. var plugin = this.pluginCallbacks[ i ]( parser );
  36936. plugins[ plugin.name ] = plugin;
  36937. // Workaround to avoid determining as unknown extension
  36938. // in addUnknownExtensionsToUserData().
  36939. // Remove this workaround if we move all the existing
  36940. // extension handlers to plugin system
  36941. extensions[ plugin.name ] = true;
  36942. }
  36943. if ( json.extensionsUsed ) {
  36944. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  36945. var extensionName = json.extensionsUsed[ i ];
  36946. var extensionsRequired = json.extensionsRequired || [];
  36947. switch ( extensionName ) {
  36948. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  36949. extensions[ extensionName ] = new GLTFLightsExtension( json );
  36950. break;
  36951. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  36952. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  36953. break;
  36954. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  36955. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  36956. break;
  36957. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  36958. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  36959. break;
  36960. case EXTENSIONS.MSFT_TEXTURE_DDS:
  36961. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  36962. break;
  36963. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  36964. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  36965. break;
  36966. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  36967. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  36968. break;
  36969. default:
  36970. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  36971. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  36972. }
  36973. }
  36974. }
  36975. }
  36976. parser.setExtensions( extensions );
  36977. parser.setPlugins( plugins );
  36978. parser.parse( onLoad, onError );
  36979. }
  36980. } );
  36981. /* GLTFREGISTRY */
  36982. function GLTFRegistry() {
  36983. var objects = {};
  36984. return {
  36985. get: function ( key ) {
  36986. return objects[ key ];
  36987. },
  36988. add: function ( key, object ) {
  36989. objects[ key ] = object;
  36990. },
  36991. remove: function ( key ) {
  36992. delete objects[ key ];
  36993. },
  36994. removeAll: function () {
  36995. objects = {};
  36996. }
  36997. };
  36998. }
  36999. /*********************************/
  37000. /********** EXTENSIONS ***********/
  37001. /*********************************/
  37002. var EXTENSIONS = {
  37003. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  37004. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  37005. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  37006. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  37007. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  37008. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  37009. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  37010. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  37011. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  37012. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  37013. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  37014. };
  37015. /**
  37016. * DDS Texture Extension
  37017. *
  37018. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  37019. *
  37020. */
  37021. function GLTFTextureDDSExtension( ddsLoader ) {
  37022. if ( ! ddsLoader ) {
  37023. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  37024. }
  37025. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  37026. this.ddsLoader = ddsLoader;
  37027. }
  37028. /**
  37029. * Punctual Lights Extension
  37030. *
  37031. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  37032. */
  37033. function GLTFLightsExtension( json ) {
  37034. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  37035. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  37036. this.lightDefs = extension.lights || [];
  37037. }
  37038. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  37039. var lightDef = this.lightDefs[ lightIndex ];
  37040. var lightNode;
  37041. var color = new THREE.Color( 0xffffff );
  37042. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  37043. var range = lightDef.range !== undefined ? lightDef.range : 0;
  37044. switch ( lightDef.type ) {
  37045. case 'directional':
  37046. lightNode = new THREE.DirectionalLight( color );
  37047. lightNode.target.position.set( 0, 0, - 1 );
  37048. lightNode.add( lightNode.target );
  37049. break;
  37050. case 'point':
  37051. lightNode = new THREE.PointLight( color );
  37052. lightNode.distance = range;
  37053. break;
  37054. case 'spot':
  37055. lightNode = new THREE.SpotLight( color );
  37056. lightNode.distance = range;
  37057. // Handle spotlight properties.
  37058. lightDef.spot = lightDef.spot || {};
  37059. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  37060. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  37061. lightNode.angle = lightDef.spot.outerConeAngle;
  37062. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  37063. lightNode.target.position.set( 0, 0, - 1 );
  37064. lightNode.add( lightNode.target );
  37065. break;
  37066. default:
  37067. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  37068. }
  37069. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  37070. // here, because node-level parsing will only override position if explicitly specified.
  37071. lightNode.position.set( 0, 0, 0 );
  37072. lightNode.decay = 2;
  37073. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  37074. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  37075. return Promise.resolve( lightNode );
  37076. };
  37077. /**
  37078. * Unlit Materials Extension
  37079. *
  37080. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  37081. */
  37082. function GLTFMaterialsUnlitExtension() {
  37083. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  37084. }
  37085. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  37086. return THREE.MeshBasicMaterial;
  37087. };
  37088. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  37089. var pending = [];
  37090. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37091. materialParams.opacity = 1.0;
  37092. var metallicRoughness = materialDef.pbrMetallicRoughness;
  37093. if ( metallicRoughness ) {
  37094. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37095. var array = metallicRoughness.baseColorFactor;
  37096. materialParams.color.fromArray( array );
  37097. materialParams.opacity = array[ 3 ];
  37098. }
  37099. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37100. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37101. }
  37102. }
  37103. return Promise.all( pending );
  37104. };
  37105. /**
  37106. * Clearcoat Materials Extension
  37107. *
  37108. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  37109. */
  37110. function GLTFMaterialsClearcoatExtension( parser ) {
  37111. this.parser = parser;
  37112. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  37113. }
  37114. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( /* materialIndex */ ) {
  37115. return THREE.MeshPhysicalMaterial;
  37116. };
  37117. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37118. var parser = this.parser;
  37119. var materialDef = parser.json.materials[ materialIndex ];
  37120. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37121. return Promise.resolve();
  37122. }
  37123. var pending = [];
  37124. var extension = materialDef.extensions[ this.name ];
  37125. if ( extension.clearcoatFactor !== undefined ) {
  37126. materialParams.clearcoat = extension.clearcoatFactor;
  37127. }
  37128. if ( extension.clearcoatTexture !== undefined ) {
  37129. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  37130. }
  37131. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  37132. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  37133. }
  37134. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  37135. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  37136. }
  37137. if ( extension.clearcoatNormalTexture !== undefined ) {
  37138. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  37139. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  37140. var scale = extension.clearcoatNormalTexture.scale;
  37141. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  37142. }
  37143. }
  37144. return Promise.all( pending );
  37145. };
  37146. /**
  37147. * Transmission Materials Extension
  37148. *
  37149. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  37150. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  37151. */
  37152. function GLTFMaterialsTransmissionExtension( parser ) {
  37153. this.parser = parser;
  37154. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  37155. }
  37156. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( /* materialIndex */ ) {
  37157. return THREE.MeshPhysicalMaterial;
  37158. };
  37159. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37160. var parser = this.parser;
  37161. var materialDef = parser.json.materials[ materialIndex ];
  37162. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37163. return Promise.resolve();
  37164. }
  37165. var pending = [];
  37166. var extension = materialDef.extensions[ this.name ];
  37167. if ( extension.transmissionFactor !== undefined ) {
  37168. materialParams.transmission = extension.transmissionFactor;
  37169. }
  37170. if ( extension.transmissionTexture !== undefined ) {
  37171. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  37172. }
  37173. return Promise.all( pending );
  37174. };
  37175. /**
  37176. * BasisU Texture Extension
  37177. *
  37178. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  37179. * (draft PR https://github.com/KhronosGroup/glTF/pull/1751)
  37180. */
  37181. function GLTFTextureBasisUExtension( parser ) {
  37182. this.parser = parser;
  37183. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  37184. }
  37185. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  37186. var parser = this.parser;
  37187. var json = parser.json;
  37188. var textureDef = json.textures[ textureIndex ];
  37189. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  37190. return null;
  37191. }
  37192. var extension = textureDef.extensions[ this.name ];
  37193. var source = json.images[ extension.source ];
  37194. var loader = parser.options.ktx2Loader;
  37195. if ( ! loader ) {
  37196. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  37197. }
  37198. return parser.loadTextureImage( textureIndex, source, loader );
  37199. };
  37200. /* BINARY EXTENSION */
  37201. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  37202. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  37203. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  37204. function GLTFBinaryExtension( data ) {
  37205. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  37206. this.content = null;
  37207. this.body = null;
  37208. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  37209. this.header = {
  37210. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  37211. version: headerView.getUint32( 4, true ),
  37212. length: headerView.getUint32( 8, true )
  37213. };
  37214. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  37215. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  37216. } else if ( this.header.version < 2.0 ) {
  37217. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  37218. }
  37219. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  37220. var chunkIndex = 0;
  37221. while ( chunkIndex < chunkView.byteLength ) {
  37222. var chunkLength = chunkView.getUint32( chunkIndex, true );
  37223. chunkIndex += 4;
  37224. var chunkType = chunkView.getUint32( chunkIndex, true );
  37225. chunkIndex += 4;
  37226. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  37227. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  37228. this.content = THREE.LoaderUtils.decodeText( contentArray );
  37229. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  37230. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  37231. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  37232. }
  37233. // Clients must ignore chunks with unknown types.
  37234. chunkIndex += chunkLength;
  37235. }
  37236. if ( this.content === null ) {
  37237. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  37238. }
  37239. }
  37240. /**
  37241. * DRACO Mesh Compression Extension
  37242. *
  37243. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  37244. */
  37245. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  37246. if ( ! dracoLoader ) {
  37247. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  37248. }
  37249. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  37250. this.json = json;
  37251. this.dracoLoader = dracoLoader;
  37252. this.dracoLoader.preload();
  37253. }
  37254. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  37255. var json = this.json;
  37256. var dracoLoader = this.dracoLoader;
  37257. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  37258. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  37259. var threeAttributeMap = {};
  37260. var attributeNormalizedMap = {};
  37261. var attributeTypeMap = {};
  37262. for ( var attributeName in gltfAttributeMap ) {
  37263. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37264. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  37265. }
  37266. for ( attributeName in primitive.attributes ) {
  37267. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37268. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  37269. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  37270. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  37271. attributeTypeMap[ threeAttributeName ] = componentType;
  37272. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  37273. }
  37274. }
  37275. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  37276. return new Promise( function ( resolve ) {
  37277. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  37278. for ( var attributeName in geometry.attributes ) {
  37279. var attribute = geometry.attributes[ attributeName ];
  37280. var normalized = attributeNormalizedMap[ attributeName ];
  37281. if ( normalized !== undefined ) attribute.normalized = normalized;
  37282. }
  37283. resolve( geometry );
  37284. }, threeAttributeMap, attributeTypeMap );
  37285. } );
  37286. } );
  37287. };
  37288. /**
  37289. * Texture Transform Extension
  37290. *
  37291. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  37292. */
  37293. function GLTFTextureTransformExtension() {
  37294. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  37295. }
  37296. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  37297. texture = texture.clone();
  37298. if ( transform.offset !== undefined ) {
  37299. texture.offset.fromArray( transform.offset );
  37300. }
  37301. if ( transform.rotation !== undefined ) {
  37302. texture.rotation = transform.rotation;
  37303. }
  37304. if ( transform.scale !== undefined ) {
  37305. texture.repeat.fromArray( transform.scale );
  37306. }
  37307. if ( transform.texCoord !== undefined ) {
  37308. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  37309. }
  37310. texture.needsUpdate = true;
  37311. return texture;
  37312. };
  37313. /**
  37314. * Specular-Glossiness Extension
  37315. *
  37316. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  37317. */
  37318. /**
  37319. * A sub class of THREE.StandardMaterial with some of the functionality
  37320. * changed via the `onBeforeCompile` callback
  37321. * @pailhead
  37322. */
  37323. function GLTFMeshStandardSGMaterial( params ) {
  37324. THREE.MeshStandardMaterial.call( this );
  37325. this.isGLTFSpecularGlossinessMaterial = true;
  37326. //various chunks that need replacing
  37327. var specularMapParsFragmentChunk = [
  37328. '#ifdef USE_SPECULARMAP',
  37329. ' uniform sampler2D specularMap;',
  37330. '#endif'
  37331. ].join( '\n' );
  37332. var glossinessMapParsFragmentChunk = [
  37333. '#ifdef USE_GLOSSINESSMAP',
  37334. ' uniform sampler2D glossinessMap;',
  37335. '#endif'
  37336. ].join( '\n' );
  37337. var specularMapFragmentChunk = [
  37338. 'vec3 specularFactor = specular;',
  37339. '#ifdef USE_SPECULARMAP',
  37340. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  37341. ' texelSpecular = sRGBToLinear( texelSpecular );',
  37342. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37343. ' specularFactor *= texelSpecular.rgb;',
  37344. '#endif'
  37345. ].join( '\n' );
  37346. var glossinessMapFragmentChunk = [
  37347. 'float glossinessFactor = glossiness;',
  37348. '#ifdef USE_GLOSSINESSMAP',
  37349. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  37350. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37351. ' glossinessFactor *= texelGlossiness.a;',
  37352. '#endif'
  37353. ].join( '\n' );
  37354. var lightPhysicalFragmentChunk = [
  37355. 'PhysicalMaterial material;',
  37356. 'material.diffuseColor = diffuseColor.rgb;',
  37357. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  37358. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  37359. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.',
  37360. 'material.specularRoughness += geometryRoughness;',
  37361. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  37362. 'material.specularColor = specularFactor.rgb;',
  37363. ].join( '\n' );
  37364. var uniforms = {
  37365. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  37366. glossiness: { value: 1 },
  37367. specularMap: { value: null },
  37368. glossinessMap: { value: null }
  37369. };
  37370. this._extraUniforms = uniforms;
  37371. // please see #14031 or #13198 for an alternate approach
  37372. this.onBeforeCompile = function ( shader ) {
  37373. for ( var uniformName in uniforms ) {
  37374. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  37375. }
  37376. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' );
  37377. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float metalness;', 'uniform float glossiness;' );
  37378. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk );
  37379. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk );
  37380. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk );
  37381. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk );
  37382. shader.fragmentShader = shader.fragmentShader.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  37383. };
  37384. /*eslint-disable*/
  37385. Object.defineProperties(
  37386. this,
  37387. {
  37388. specular: {
  37389. get: function () { return uniforms.specular.value; },
  37390. set: function ( v ) { uniforms.specular.value = v; }
  37391. },
  37392. specularMap: {
  37393. get: function () { return uniforms.specularMap.value; },
  37394. set: function ( v ) { uniforms.specularMap.value = v; }
  37395. },
  37396. glossiness: {
  37397. get: function () { return uniforms.glossiness.value; },
  37398. set: function ( v ) { uniforms.glossiness.value = v; }
  37399. },
  37400. glossinessMap: {
  37401. get: function () { return uniforms.glossinessMap.value; },
  37402. set: function ( v ) {
  37403. uniforms.glossinessMap.value = v;
  37404. //how about something like this - @pailhead
  37405. if ( v ) {
  37406. this.defines.USE_GLOSSINESSMAP = '';
  37407. // set USE_ROUGHNESSMAP to enable vUv
  37408. this.defines.USE_ROUGHNESSMAP = '';
  37409. } else {
  37410. delete this.defines.USE_ROUGHNESSMAP;
  37411. delete this.defines.USE_GLOSSINESSMAP;
  37412. }
  37413. }
  37414. }
  37415. }
  37416. );
  37417. /*eslint-enable*/
  37418. delete this.metalness;
  37419. delete this.roughness;
  37420. delete this.metalnessMap;
  37421. delete this.roughnessMap;
  37422. this.setValues( params );
  37423. }
  37424. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  37425. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  37426. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  37427. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  37428. this.specularMap = source.specularMap;
  37429. this.specular.copy( source.specular );
  37430. this.glossinessMap = source.glossinessMap;
  37431. this.glossiness = source.glossiness;
  37432. delete this.metalness;
  37433. delete this.roughness;
  37434. delete this.metalnessMap;
  37435. delete this.roughnessMap;
  37436. return this;
  37437. };
  37438. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  37439. return {
  37440. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  37441. specularGlossinessParams: [
  37442. 'color',
  37443. 'map',
  37444. 'lightMap',
  37445. 'lightMapIntensity',
  37446. 'aoMap',
  37447. 'aoMapIntensity',
  37448. 'emissive',
  37449. 'emissiveIntensity',
  37450. 'emissiveMap',
  37451. 'bumpMap',
  37452. 'bumpScale',
  37453. 'normalMap',
  37454. 'normalMapType',
  37455. 'displacementMap',
  37456. 'displacementScale',
  37457. 'displacementBias',
  37458. 'specularMap',
  37459. 'specular',
  37460. 'glossinessMap',
  37461. 'glossiness',
  37462. 'alphaMap',
  37463. 'envMap',
  37464. 'envMapIntensity',
  37465. 'refractionRatio',
  37466. ],
  37467. getMaterialType: function () {
  37468. return GLTFMeshStandardSGMaterial;
  37469. },
  37470. extendParams: function ( materialParams, materialDef, parser ) {
  37471. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  37472. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37473. materialParams.opacity = 1.0;
  37474. var pending = [];
  37475. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  37476. var array = pbrSpecularGlossiness.diffuseFactor;
  37477. materialParams.color.fromArray( array );
  37478. materialParams.opacity = array[ 3 ];
  37479. }
  37480. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  37481. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  37482. }
  37483. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  37484. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  37485. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  37486. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  37487. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  37488. }
  37489. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  37490. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  37491. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  37492. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  37493. }
  37494. return Promise.all( pending );
  37495. },
  37496. createMaterial: function ( materialParams ) {
  37497. var material = new GLTFMeshStandardSGMaterial( materialParams );
  37498. material.fog = true;
  37499. material.color = materialParams.color;
  37500. material.map = materialParams.map === undefined ? null : materialParams.map;
  37501. material.lightMap = null;
  37502. material.lightMapIntensity = 1.0;
  37503. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  37504. material.aoMapIntensity = 1.0;
  37505. material.emissive = materialParams.emissive;
  37506. material.emissiveIntensity = 1.0;
  37507. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  37508. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  37509. material.bumpScale = 1;
  37510. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  37511. material.normalMapType = THREE.TangentSpaceNormalMap;
  37512. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  37513. material.displacementMap = null;
  37514. material.displacementScale = 1;
  37515. material.displacementBias = 0;
  37516. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  37517. material.specular = materialParams.specular;
  37518. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  37519. material.glossiness = materialParams.glossiness;
  37520. material.alphaMap = null;
  37521. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  37522. material.envMapIntensity = 1.0;
  37523. material.refractionRatio = 0.98;
  37524. return material;
  37525. },
  37526. };
  37527. }
  37528. /**
  37529. * Mesh Quantization Extension
  37530. *
  37531. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  37532. */
  37533. function GLTFMeshQuantizationExtension() {
  37534. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  37535. }
  37536. /*********************************/
  37537. /********** INTERPOLATION ********/
  37538. /*********************************/
  37539. // Spline Interpolation
  37540. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  37541. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  37542. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  37543. }
  37544. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  37545. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  37546. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  37547. // Copies a sample value to the result buffer. See description of glTF
  37548. // CUBICSPLINE values layout in interpolate_() function below.
  37549. var result = this.resultBuffer,
  37550. values = this.sampleValues,
  37551. valueSize = this.valueSize,
  37552. offset = index * valueSize * 3 + valueSize;
  37553. for ( var i = 0; i !== valueSize; i ++ ) {
  37554. result[ i ] = values[ offset + i ];
  37555. }
  37556. return result;
  37557. };
  37558. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37559. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37560. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  37561. var result = this.resultBuffer;
  37562. var values = this.sampleValues;
  37563. var stride = this.valueSize;
  37564. var stride2 = stride * 2;
  37565. var stride3 = stride * 3;
  37566. var td = t1 - t0;
  37567. var p = ( t - t0 ) / td;
  37568. var pp = p * p;
  37569. var ppp = pp * p;
  37570. var offset1 = i1 * stride3;
  37571. var offset0 = offset1 - stride3;
  37572. var s2 = - 2 * ppp + 3 * pp;
  37573. var s3 = ppp - pp;
  37574. var s0 = 1 - s2;
  37575. var s1 = s3 - pp + p;
  37576. // Layout of keyframe output values for CUBICSPLINE animations:
  37577. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  37578. for ( var i = 0; i !== stride; i ++ ) {
  37579. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  37580. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  37581. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  37582. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  37583. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  37584. }
  37585. return result;
  37586. };
  37587. /*********************************/
  37588. /********** INTERNALS ************/
  37589. /*********************************/
  37590. /* CONSTANTS */
  37591. var WEBGL_CONSTANTS = {
  37592. FLOAT: 5126,
  37593. //FLOAT_MAT2: 35674,
  37594. FLOAT_MAT3: 35675,
  37595. FLOAT_MAT4: 35676,
  37596. FLOAT_VEC2: 35664,
  37597. FLOAT_VEC3: 35665,
  37598. FLOAT_VEC4: 35666,
  37599. LINEAR: 9729,
  37600. REPEAT: 10497,
  37601. SAMPLER_2D: 35678,
  37602. POINTS: 0,
  37603. LINES: 1,
  37604. LINE_LOOP: 2,
  37605. LINE_STRIP: 3,
  37606. TRIANGLES: 4,
  37607. TRIANGLE_STRIP: 5,
  37608. TRIANGLE_FAN: 6,
  37609. UNSIGNED_BYTE: 5121,
  37610. UNSIGNED_SHORT: 5123
  37611. };
  37612. var WEBGL_COMPONENT_TYPES = {
  37613. 5120: Int8Array,
  37614. 5121: Uint8Array,
  37615. 5122: Int16Array,
  37616. 5123: Uint16Array,
  37617. 5125: Uint32Array,
  37618. 5126: Float32Array
  37619. };
  37620. var WEBGL_FILTERS = {
  37621. 9728: THREE.NearestFilter,
  37622. 9729: THREE.LinearFilter,
  37623. 9984: THREE.NearestMipmapNearestFilter,
  37624. 9985: THREE.LinearMipmapNearestFilter,
  37625. 9986: THREE.NearestMipmapLinearFilter,
  37626. 9987: THREE.LinearMipmapLinearFilter
  37627. };
  37628. var WEBGL_WRAPPINGS = {
  37629. 33071: THREE.ClampToEdgeWrapping,
  37630. 33648: THREE.MirroredRepeatWrapping,
  37631. 10497: THREE.RepeatWrapping
  37632. };
  37633. var WEBGL_TYPE_SIZES = {
  37634. 'SCALAR': 1,
  37635. 'VEC2': 2,
  37636. 'VEC3': 3,
  37637. 'VEC4': 4,
  37638. 'MAT2': 4,
  37639. 'MAT3': 9,
  37640. 'MAT4': 16
  37641. };
  37642. var ATTRIBUTES = {
  37643. POSITION: 'position',
  37644. NORMAL: 'normal',
  37645. TANGENT: 'tangent',
  37646. TEXCOORD_0: 'uv',
  37647. TEXCOORD_1: 'uv2',
  37648. COLOR_0: 'color',
  37649. WEIGHTS_0: 'skinWeight',
  37650. JOINTS_0: 'skinIndex',
  37651. };
  37652. var PATH_PROPERTIES = {
  37653. scale: 'scale',
  37654. translation: 'position',
  37655. rotation: 'quaternion',
  37656. weights: 'morphTargetInfluences'
  37657. };
  37658. var INTERPOLATION = {
  37659. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  37660. // keyframe track will be initialized with a default interpolation type, then modified.
  37661. LINEAR: THREE.InterpolateLinear,
  37662. STEP: THREE.InterpolateDiscrete
  37663. };
  37664. var ALPHA_MODES = {
  37665. OPAQUE: 'OPAQUE',
  37666. MASK: 'MASK',
  37667. BLEND: 'BLEND'
  37668. };
  37669. var MIME_TYPE_FORMATS = {
  37670. 'image/png': THREE.RGBAFormat,
  37671. 'image/jpeg': THREE.RGBFormat
  37672. };
  37673. /* UTILITY FUNCTIONS */
  37674. function resolveURL( url, path ) {
  37675. // Invalid URL
  37676. if ( typeof url !== 'string' || url === '' ) return '';
  37677. // Host Relative URL
  37678. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  37679. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  37680. }
  37681. // Absolute URL http://,https://,//
  37682. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  37683. // Data URI
  37684. if ( /^data:.*,.*$/i.test( url ) ) return url;
  37685. // Blob URL
  37686. if ( /^blob:.*$/i.test( url ) ) return url;
  37687. // Relative URL
  37688. return path + url;
  37689. }
  37690. /**
  37691. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  37692. */
  37693. function createDefaultMaterial( cache ) {
  37694. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  37695. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  37696. color: 0xFFFFFF,
  37697. emissive: 0x000000,
  37698. metalness: 1,
  37699. roughness: 1,
  37700. transparent: false,
  37701. depthTest: true,
  37702. side: THREE.FrontSide
  37703. } );
  37704. }
  37705. return cache[ 'DefaultMaterial' ];
  37706. }
  37707. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  37708. // Add unknown glTF extensions to an object's userData.
  37709. for ( var name in objectDef.extensions ) {
  37710. if ( knownExtensions[ name ] === undefined ) {
  37711. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  37712. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  37713. }
  37714. }
  37715. }
  37716. /**
  37717. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  37718. * @param {GLTF.definition} gltfDef
  37719. */
  37720. function assignExtrasToUserData( object, gltfDef ) {
  37721. if ( gltfDef.extras !== undefined ) {
  37722. if ( typeof gltfDef.extras === 'object' ) {
  37723. Object.assign( object.userData, gltfDef.extras );
  37724. } else {
  37725. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  37726. }
  37727. }
  37728. }
  37729. /**
  37730. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  37731. *
  37732. * @param {THREE.BufferGeometry} geometry
  37733. * @param {Array<GLTF.Target>} targets
  37734. * @param {GLTFParser} parser
  37735. * @return {Promise<THREE.BufferGeometry>}
  37736. */
  37737. function addMorphTargets( geometry, targets, parser ) {
  37738. var hasMorphPosition = false;
  37739. var hasMorphNormal = false;
  37740. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  37741. var target = targets[ i ];
  37742. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  37743. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  37744. if ( hasMorphPosition && hasMorphNormal ) break;
  37745. }
  37746. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  37747. var pendingPositionAccessors = [];
  37748. var pendingNormalAccessors = [];
  37749. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  37750. var target = targets[ i ];
  37751. if ( hasMorphPosition ) {
  37752. var pendingAccessor = target.POSITION !== undefined
  37753. ? parser.getDependency( 'accessor', target.POSITION )
  37754. : geometry.attributes.position;
  37755. pendingPositionAccessors.push( pendingAccessor );
  37756. }
  37757. if ( hasMorphNormal ) {
  37758. var pendingAccessor = target.NORMAL !== undefined
  37759. ? parser.getDependency( 'accessor', target.NORMAL )
  37760. : geometry.attributes.normal;
  37761. pendingNormalAccessors.push( pendingAccessor );
  37762. }
  37763. }
  37764. return Promise.all( [
  37765. Promise.all( pendingPositionAccessors ),
  37766. Promise.all( pendingNormalAccessors )
  37767. ] ).then( function ( accessors ) {
  37768. var morphPositions = accessors[ 0 ];
  37769. var morphNormals = accessors[ 1 ];
  37770. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  37771. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  37772. geometry.morphTargetsRelative = true;
  37773. return geometry;
  37774. } );
  37775. }
  37776. /**
  37777. * @param {THREE.Mesh} mesh
  37778. * @param {GLTF.Mesh} meshDef
  37779. */
  37780. function updateMorphTargets( mesh, meshDef ) {
  37781. mesh.updateMorphTargets();
  37782. if ( meshDef.weights !== undefined ) {
  37783. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  37784. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  37785. }
  37786. }
  37787. // .extras has user-defined data, so check that .extras.targetNames is an array.
  37788. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  37789. var targetNames = meshDef.extras.targetNames;
  37790. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  37791. mesh.morphTargetDictionary = {};
  37792. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  37793. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  37794. }
  37795. } else {
  37796. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  37797. }
  37798. }
  37799. }
  37800. function createPrimitiveKey( primitiveDef ) {
  37801. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  37802. var geometryKey;
  37803. if ( dracoExtension ) {
  37804. geometryKey = 'draco:' + dracoExtension.bufferView
  37805. + ':' + dracoExtension.indices
  37806. + ':' + createAttributesKey( dracoExtension.attributes );
  37807. } else {
  37808. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  37809. }
  37810. return geometryKey;
  37811. }
  37812. function createAttributesKey( attributes ) {
  37813. var attributesKey = '';
  37814. var keys = Object.keys( attributes ).sort();
  37815. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  37816. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  37817. }
  37818. return attributesKey;
  37819. }
  37820. /* GLTF PARSER */
  37821. function GLTFParser( json, options ) {
  37822. this.json = json || {};
  37823. this.extensions = {};
  37824. this.plugins = {};
  37825. this.options = options || {};
  37826. // loader object cache
  37827. this.cache = new GLTFRegistry();
  37828. // associations between Three.js objects and glTF elements
  37829. this.associations = new Map();
  37830. // BufferGeometry caching
  37831. this.primitiveCache = {};
  37832. // Object3D instance caches
  37833. this.meshCache = { refs: {}, uses: {} };
  37834. this.cameraCache = { refs: {}, uses: {} };
  37835. this.lightCache = { refs: {}, uses: {} };
  37836. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  37837. // expensive work of uploading a texture to the GPU off the main thread.
  37838. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  37839. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  37840. } else {
  37841. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  37842. }
  37843. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  37844. this.fileLoader = new THREE.FileLoader( this.options.manager );
  37845. this.fileLoader.setResponseType( 'arraybuffer' );
  37846. if ( this.options.crossOrigin === 'use-credentials' ) {
  37847. this.fileLoader.setWithCredentials( true );
  37848. }
  37849. }
  37850. GLTFParser.prototype.setExtensions = function ( extensions ) {
  37851. this.extensions = extensions;
  37852. };
  37853. GLTFParser.prototype.setPlugins = function ( plugins ) {
  37854. this.plugins = plugins;
  37855. };
  37856. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  37857. var parser = this;
  37858. var json = this.json;
  37859. var extensions = this.extensions;
  37860. // Clear the loader cache
  37861. this.cache.removeAll();
  37862. // Mark the special nodes/meshes in json for efficient parse
  37863. this._markDefs();
  37864. Promise.all( [
  37865. this.getDependencies( 'scene' ),
  37866. this.getDependencies( 'animation' ),
  37867. this.getDependencies( 'camera' ),
  37868. ] ).then( function ( dependencies ) {
  37869. var result = {
  37870. scene: dependencies[ 0 ][ json.scene || 0 ],
  37871. scenes: dependencies[ 0 ],
  37872. animations: dependencies[ 1 ],
  37873. cameras: dependencies[ 2 ],
  37874. asset: json.asset,
  37875. parser: parser,
  37876. userData: {}
  37877. };
  37878. addUnknownExtensionsToUserData( extensions, result, json );
  37879. assignExtrasToUserData( result, json );
  37880. onLoad( result );
  37881. } ).catch( onError );
  37882. };
  37883. /**
  37884. * Marks the special nodes/meshes in json for efficient parse.
  37885. */
  37886. GLTFParser.prototype._markDefs = function () {
  37887. var nodeDefs = this.json.nodes || [];
  37888. var skinDefs = this.json.skins || [];
  37889. var meshDefs = this.json.meshes || [];
  37890. // Nothing in the node definition indicates whether it is a Bone or an
  37891. // Object3D. Use the skins' joint references to mark bones.
  37892. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  37893. var joints = skinDefs[ skinIndex ].joints;
  37894. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  37895. nodeDefs[ joints[ i ] ].isBone = true;
  37896. }
  37897. }
  37898. // Iterate over all nodes, marking references to shared resources,
  37899. // as well as skeleton joints.
  37900. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37901. var nodeDef = nodeDefs[ nodeIndex ];
  37902. if ( nodeDef.mesh !== undefined ) {
  37903. this._addNodeRef( this.meshCache, nodeDef.mesh );
  37904. // Nothing in the mesh definition indicates whether it is
  37905. // a SkinnedMesh or Mesh. Use the node's mesh reference
  37906. // to mark SkinnedMesh if node has skin.
  37907. if ( nodeDef.skin !== undefined ) {
  37908. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  37909. }
  37910. }
  37911. if ( nodeDef.camera !== undefined ) {
  37912. this._addNodeRef( this.cameraCache, nodeDef.camera );
  37913. }
  37914. if ( nodeDef.extensions
  37915. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  37916. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  37917. this._addNodeRef( this.lightCache, nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  37918. }
  37919. }
  37920. };
  37921. /**
  37922. * Counts references to shared node / Object3D resources. These resources
  37923. * can be reused, or "instantiated", at multiple nodes in the scene
  37924. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  37925. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  37926. * Textures) can be reused directly and are not marked here.
  37927. *
  37928. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  37929. */
  37930. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  37931. if ( index === undefined ) return;
  37932. if ( cache.refs[ index ] === undefined ) {
  37933. cache.refs[ index ] = cache.uses[ index ] = 0;
  37934. }
  37935. cache.refs[ index ] ++;
  37936. };
  37937. /** Returns a reference to a shared resource, cloning it if necessary. */
  37938. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  37939. if ( cache.refs[ index ] <= 1 ) return object;
  37940. var ref = object.clone();
  37941. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  37942. return ref;
  37943. };
  37944. GLTFParser.prototype._invokeOne = function ( func ) {
  37945. var extensions = Object.values( this.plugins );
  37946. extensions.push( this );
  37947. for ( var i = 0; i < extensions.length; i ++ ) {
  37948. var result = func( extensions[ i ] );
  37949. if ( result ) return result;
  37950. }
  37951. };
  37952. GLTFParser.prototype._invokeAll = function ( func ) {
  37953. var extensions = Object.values( this.plugins );
  37954. extensions.unshift( this );
  37955. var pending = [];
  37956. for ( var i = 0; i < extensions.length; i ++ ) {
  37957. pending.push( func( extensions[ i ] ) );
  37958. }
  37959. return Promise.all( pending );
  37960. };
  37961. /**
  37962. * Requests the specified dependency asynchronously, with caching.
  37963. * @param {string} type
  37964. * @param {number} index
  37965. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  37966. */
  37967. GLTFParser.prototype.getDependency = function ( type, index ) {
  37968. var cacheKey = type + ':' + index;
  37969. var dependency = this.cache.get( cacheKey );
  37970. if ( ! dependency ) {
  37971. switch ( type ) {
  37972. case 'scene':
  37973. dependency = this.loadScene( index );
  37974. break;
  37975. case 'node':
  37976. dependency = this.loadNode( index );
  37977. break;
  37978. case 'mesh':
  37979. dependency = this._invokeOne( function ( ext ) {
  37980. return ext.loadMesh && ext.loadMesh( index );
  37981. } );
  37982. break;
  37983. case 'accessor':
  37984. dependency = this.loadAccessor( index );
  37985. break;
  37986. case 'bufferView':
  37987. dependency = this._invokeOne( function ( ext ) {
  37988. return ext.loadBufferView && ext.loadBufferView( index );
  37989. } );
  37990. break;
  37991. case 'buffer':
  37992. dependency = this.loadBuffer( index );
  37993. break;
  37994. case 'material':
  37995. dependency = this._invokeOne( function ( ext ) {
  37996. return ext.loadMaterial && ext.loadMaterial( index );
  37997. } );
  37998. break;
  37999. case 'texture':
  38000. dependency = this._invokeOne( function ( ext ) {
  38001. return ext.loadTexture && ext.loadTexture( index );
  38002. } );
  38003. break;
  38004. case 'skin':
  38005. dependency = this.loadSkin( index );
  38006. break;
  38007. case 'animation':
  38008. dependency = this.loadAnimation( index );
  38009. break;
  38010. case 'camera':
  38011. dependency = this.loadCamera( index );
  38012. break;
  38013. case 'light':
  38014. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  38015. break;
  38016. default:
  38017. throw new Error( 'Unknown type: ' + type );
  38018. }
  38019. this.cache.add( cacheKey, dependency );
  38020. }
  38021. return dependency;
  38022. };
  38023. /**
  38024. * Requests all dependencies of the specified type asynchronously, with caching.
  38025. * @param {string} type
  38026. * @return {Promise<Array<Object>>}
  38027. */
  38028. GLTFParser.prototype.getDependencies = function ( type ) {
  38029. var dependencies = this.cache.get( type );
  38030. if ( ! dependencies ) {
  38031. var parser = this;
  38032. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  38033. dependencies = Promise.all( defs.map( function ( def, index ) {
  38034. return parser.getDependency( type, index );
  38035. } ) );
  38036. this.cache.add( type, dependencies );
  38037. }
  38038. return dependencies;
  38039. };
  38040. /**
  38041. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38042. * @param {number} bufferIndex
  38043. * @return {Promise<ArrayBuffer>}
  38044. */
  38045. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  38046. var bufferDef = this.json.buffers[ bufferIndex ];
  38047. var loader = this.fileLoader;
  38048. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  38049. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  38050. }
  38051. // If present, GLB container is required to be the first buffer.
  38052. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  38053. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  38054. }
  38055. var options = this.options;
  38056. return new Promise( function ( resolve, reject ) {
  38057. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  38058. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  38059. } );
  38060. } );
  38061. };
  38062. /**
  38063. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38064. * @param {number} bufferViewIndex
  38065. * @return {Promise<ArrayBuffer>}
  38066. */
  38067. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  38068. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  38069. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  38070. var byteLength = bufferViewDef.byteLength || 0;
  38071. var byteOffset = bufferViewDef.byteOffset || 0;
  38072. return buffer.slice( byteOffset, byteOffset + byteLength );
  38073. } );
  38074. };
  38075. /**
  38076. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  38077. * @param {number} accessorIndex
  38078. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  38079. */
  38080. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  38081. var parser = this;
  38082. var json = this.json;
  38083. var accessorDef = this.json.accessors[ accessorIndex ];
  38084. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  38085. // Ignore empty accessors, which may be used to declare runtime
  38086. // information about attributes coming from another source (e.g. Draco
  38087. // compression extension).
  38088. return Promise.resolve( null );
  38089. }
  38090. var pendingBufferViews = [];
  38091. if ( accessorDef.bufferView !== undefined ) {
  38092. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  38093. } else {
  38094. pendingBufferViews.push( null );
  38095. }
  38096. if ( accessorDef.sparse !== undefined ) {
  38097. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  38098. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  38099. }
  38100. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  38101. var bufferView = bufferViews[ 0 ];
  38102. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  38103. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  38104. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  38105. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  38106. var itemBytes = elementBytes * itemSize;
  38107. var byteOffset = accessorDef.byteOffset || 0;
  38108. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  38109. var normalized = accessorDef.normalized === true;
  38110. var array, bufferAttribute;
  38111. // The buffer is not interleaved if the stride is the item size in bytes.
  38112. if ( byteStride && byteStride !== itemBytes ) {
  38113. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  38114. // This makes sure that IBA.count reflects accessor.count properly
  38115. var ibSlice = Math.floor( byteOffset / byteStride );
  38116. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  38117. var ib = parser.cache.get( ibCacheKey );
  38118. if ( ! ib ) {
  38119. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  38120. // Integer parameters to IB/IBA are in array elements, not bytes.
  38121. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  38122. parser.cache.add( ibCacheKey, ib );
  38123. }
  38124. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  38125. } else {
  38126. if ( bufferView === null ) {
  38127. array = new TypedArray( accessorDef.count * itemSize );
  38128. } else {
  38129. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  38130. }
  38131. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  38132. }
  38133. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  38134. if ( accessorDef.sparse !== undefined ) {
  38135. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  38136. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  38137. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  38138. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  38139. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  38140. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  38141. if ( bufferView !== null ) {
  38142. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  38143. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  38144. }
  38145. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  38146. var index = sparseIndices[ i ];
  38147. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  38148. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  38149. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  38150. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  38151. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  38152. }
  38153. }
  38154. return bufferAttribute;
  38155. } );
  38156. };
  38157. /**
  38158. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  38159. * @param {number} textureIndex
  38160. * @return {Promise<THREE.Texture>}
  38161. */
  38162. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  38163. var parser = this;
  38164. var json = this.json;
  38165. var options = this.options;
  38166. var textureDef = json.textures[ textureIndex ];
  38167. var textureExtensions = textureDef.extensions || {};
  38168. var source;
  38169. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  38170. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  38171. } else {
  38172. source = json.images[ textureDef.source ];
  38173. }
  38174. var loader;
  38175. if ( source.uri ) {
  38176. loader = options.manager.getHandler( source.uri );
  38177. }
  38178. if ( ! loader ) {
  38179. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  38180. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  38181. : this.textureLoader;
  38182. }
  38183. return this.loadTextureImage( textureIndex, source, loader );
  38184. };
  38185. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  38186. var parser = this;
  38187. var json = this.json;
  38188. var options = this.options;
  38189. var textureDef = json.textures[ textureIndex ];
  38190. var URL = self.URL || self.webkitURL;
  38191. var sourceURI = source.uri;
  38192. var isObjectURL = false;
  38193. if ( source.bufferView !== undefined ) {
  38194. // Load binary image data from bufferView, if provided.
  38195. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  38196. isObjectURL = true;
  38197. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  38198. sourceURI = URL.createObjectURL( blob );
  38199. return sourceURI;
  38200. } );
  38201. }
  38202. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  38203. return new Promise( function ( resolve, reject ) {
  38204. var onLoad = resolve;
  38205. if ( loader.isImageBitmapLoader === true ) {
  38206. onLoad = function ( imageBitmap ) {
  38207. resolve( new THREE.CanvasTexture( imageBitmap ) );
  38208. };
  38209. }
  38210. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  38211. } );
  38212. } ).then( function ( texture ) {
  38213. // Clean up resources and configure Texture.
  38214. if ( isObjectURL === true ) {
  38215. URL.revokeObjectURL( sourceURI );
  38216. }
  38217. texture.flipY = false;
  38218. if ( textureDef.name ) texture.name = textureDef.name;
  38219. // Ignore unknown mime types, like DDS files.
  38220. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  38221. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  38222. }
  38223. var samplers = json.samplers || {};
  38224. var sampler = samplers[ textureDef.sampler ] || {};
  38225. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  38226. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  38227. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  38228. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  38229. parser.associations.set( texture, {
  38230. type: 'textures',
  38231. index: textureIndex
  38232. } );
  38233. return texture;
  38234. } );
  38235. };
  38236. /**
  38237. * Asynchronously assigns a texture to the given material parameters.
  38238. * @param {Object} materialParams
  38239. * @param {string} mapName
  38240. * @param {Object} mapDef
  38241. * @return {Promise}
  38242. */
  38243. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  38244. var parser = this;
  38245. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  38246. if ( ! texture.isCompressedTexture ) {
  38247. switch ( mapName ) {
  38248. case 'aoMap':
  38249. case 'emissiveMap':
  38250. case 'metalnessMap':
  38251. case 'normalMap':
  38252. case 'roughnessMap':
  38253. texture.format = THREE.RGBFormat;
  38254. break;
  38255. }
  38256. }
  38257. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  38258. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  38259. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  38260. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  38261. }
  38262. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  38263. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  38264. if ( transform ) {
  38265. var gltfReference = parser.associations.get( texture );
  38266. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  38267. parser.associations.set( texture, gltfReference );
  38268. }
  38269. }
  38270. materialParams[ mapName ] = texture;
  38271. } );
  38272. };
  38273. /**
  38274. * Assigns final material to a Mesh, Line, or Points instance. The instance
  38275. * already has a material (generated from the glTF material options alone)
  38276. * but reuse of the same glTF material may require multiple threejs materials
  38277. * to accomodate different primitive types, defines, etc. New materials will
  38278. * be created if necessary, and reused from a cache.
  38279. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  38280. */
  38281. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  38282. var geometry = mesh.geometry;
  38283. var material = mesh.material;
  38284. var useVertexTangents = geometry.attributes.tangent !== undefined;
  38285. var useVertexColors = geometry.attributes.color !== undefined;
  38286. var useFlatShading = geometry.attributes.normal === undefined;
  38287. var useSkinning = mesh.isSkinnedMesh === true;
  38288. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  38289. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  38290. if ( mesh.isPoints ) {
  38291. var cacheKey = 'PointsMaterial:' + material.uuid;
  38292. var pointsMaterial = this.cache.get( cacheKey );
  38293. if ( ! pointsMaterial ) {
  38294. pointsMaterial = new THREE.PointsMaterial();
  38295. THREE.Material.prototype.copy.call( pointsMaterial, material );
  38296. pointsMaterial.color.copy( material.color );
  38297. pointsMaterial.map = material.map;
  38298. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  38299. this.cache.add( cacheKey, pointsMaterial );
  38300. }
  38301. material = pointsMaterial;
  38302. } else if ( mesh.isLine ) {
  38303. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  38304. var lineMaterial = this.cache.get( cacheKey );
  38305. if ( ! lineMaterial ) {
  38306. lineMaterial = new THREE.LineBasicMaterial();
  38307. THREE.Material.prototype.copy.call( lineMaterial, material );
  38308. lineMaterial.color.copy( material.color );
  38309. this.cache.add( cacheKey, lineMaterial );
  38310. }
  38311. material = lineMaterial;
  38312. }
  38313. // Clone the material if it will be modified
  38314. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  38315. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  38316. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  38317. if ( useSkinning ) cacheKey += 'skinning:';
  38318. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  38319. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  38320. if ( useFlatShading ) cacheKey += 'flat-shading:';
  38321. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  38322. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  38323. var cachedMaterial = this.cache.get( cacheKey );
  38324. if ( ! cachedMaterial ) {
  38325. cachedMaterial = material.clone();
  38326. if ( useSkinning ) cachedMaterial.skinning = true;
  38327. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  38328. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  38329. if ( useFlatShading ) cachedMaterial.flatShading = true;
  38330. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  38331. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  38332. this.cache.add( cacheKey, cachedMaterial );
  38333. this.associations.set( cachedMaterial, this.associations.get( material ) );
  38334. }
  38335. material = cachedMaterial;
  38336. }
  38337. // workarounds for mesh and geometry
  38338. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  38339. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  38340. }
  38341. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38342. if ( material.normalScale && ! useVertexTangents ) {
  38343. material.normalScale.y = - material.normalScale.y;
  38344. }
  38345. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  38346. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  38347. }
  38348. mesh.material = material;
  38349. };
  38350. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  38351. return THREE.MeshStandardMaterial;
  38352. };
  38353. /**
  38354. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  38355. * @param {number} materialIndex
  38356. * @return {Promise<THREE.Material>}
  38357. */
  38358. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  38359. var parser = this;
  38360. var json = this.json;
  38361. var extensions = this.extensions;
  38362. var materialDef = json.materials[ materialIndex ];
  38363. var materialType;
  38364. var materialParams = {};
  38365. var materialExtensions = materialDef.extensions || {};
  38366. var pending = [];
  38367. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  38368. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  38369. materialType = sgExtension.getMaterialType();
  38370. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  38371. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  38372. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  38373. materialType = kmuExtension.getMaterialType();
  38374. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  38375. } else {
  38376. // Specification:
  38377. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  38378. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  38379. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38380. materialParams.opacity = 1.0;
  38381. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  38382. var array = metallicRoughness.baseColorFactor;
  38383. materialParams.color.fromArray( array );
  38384. materialParams.opacity = array[ 3 ];
  38385. }
  38386. if ( metallicRoughness.baseColorTexture !== undefined ) {
  38387. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  38388. }
  38389. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  38390. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  38391. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  38392. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38393. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38394. }
  38395. materialType = this._invokeOne( function ( ext ) {
  38396. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  38397. } );
  38398. pending.push( this._invokeAll( function ( ext ) {
  38399. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  38400. } ) );
  38401. }
  38402. if ( materialDef.doubleSided === true ) {
  38403. materialParams.side = THREE.DoubleSide;
  38404. }
  38405. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  38406. if ( alphaMode === ALPHA_MODES.BLEND ) {
  38407. materialParams.transparent = true;
  38408. // See: https://github.com/mrdoob/three.js/issues/17706
  38409. materialParams.depthWrite = false;
  38410. } else {
  38411. materialParams.transparent = false;
  38412. if ( alphaMode === ALPHA_MODES.MASK ) {
  38413. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  38414. }
  38415. }
  38416. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38417. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  38418. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  38419. if ( materialDef.normalTexture.scale !== undefined ) {
  38420. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  38421. }
  38422. }
  38423. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38424. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  38425. if ( materialDef.occlusionTexture.strength !== undefined ) {
  38426. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  38427. }
  38428. }
  38429. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38430. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  38431. }
  38432. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38433. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  38434. }
  38435. return Promise.all( pending ).then( function () {
  38436. var material;
  38437. if ( materialType === GLTFMeshStandardSGMaterial ) {
  38438. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  38439. } else {
  38440. material = new materialType( materialParams );
  38441. }
  38442. if ( materialDef.name ) material.name = materialDef.name;
  38443. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  38444. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  38445. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  38446. assignExtrasToUserData( material, materialDef );
  38447. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  38448. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  38449. return material;
  38450. } );
  38451. };
  38452. /**
  38453. * @param {THREE.BufferGeometry} geometry
  38454. * @param {GLTF.Primitive} primitiveDef
  38455. * @param {GLTFParser} parser
  38456. */
  38457. function computeBounds( geometry, primitiveDef, parser ) {
  38458. var attributes = primitiveDef.attributes;
  38459. var box = new THREE.Box3();
  38460. if ( attributes.POSITION !== undefined ) {
  38461. var accessor = parser.json.accessors[ attributes.POSITION ];
  38462. var min = accessor.min;
  38463. var max = accessor.max;
  38464. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38465. if ( min !== undefined && max !== undefined ) {
  38466. box.set(
  38467. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  38468. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  38469. } else {
  38470. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38471. return;
  38472. }
  38473. } else {
  38474. return;
  38475. }
  38476. var targets = primitiveDef.targets;
  38477. if ( targets !== undefined ) {
  38478. var maxDisplacement = new THREE.Vector3();
  38479. var vector = new THREE.Vector3();
  38480. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38481. var target = targets[ i ];
  38482. if ( target.POSITION !== undefined ) {
  38483. var accessor = parser.json.accessors[ target.POSITION ];
  38484. var min = accessor.min;
  38485. var max = accessor.max;
  38486. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38487. if ( min !== undefined && max !== undefined ) {
  38488. // we need to get max of absolute components because target weight is [-1,1]
  38489. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  38490. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  38491. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  38492. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  38493. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  38494. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  38495. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  38496. maxDisplacement.max( vector );
  38497. } else {
  38498. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38499. }
  38500. }
  38501. }
  38502. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  38503. box.expandByVector( maxDisplacement );
  38504. }
  38505. geometry.boundingBox = box;
  38506. var sphere = new THREE.Sphere();
  38507. box.getCenter( sphere.center );
  38508. sphere.radius = box.min.distanceTo( box.max ) / 2;
  38509. geometry.boundingSphere = sphere;
  38510. }
  38511. /**
  38512. * @param {THREE.BufferGeometry} geometry
  38513. * @param {GLTF.Primitive} primitiveDef
  38514. * @param {GLTFParser} parser
  38515. * @return {Promise<THREE.BufferGeometry>}
  38516. */
  38517. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  38518. var attributes = primitiveDef.attributes;
  38519. var pending = [];
  38520. function assignAttributeAccessor( accessorIndex, attributeName ) {
  38521. return parser.getDependency( 'accessor', accessorIndex )
  38522. .then( function ( accessor ) {
  38523. geometry.setAttribute( attributeName, accessor );
  38524. } );
  38525. }
  38526. for ( var gltfAttributeName in attributes ) {
  38527. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  38528. // Skip attributes already provided by e.g. Draco extension.
  38529. if ( threeAttributeName in geometry.attributes ) continue;
  38530. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  38531. }
  38532. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  38533. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  38534. geometry.setIndex( accessor );
  38535. } );
  38536. pending.push( accessor );
  38537. }
  38538. assignExtrasToUserData( geometry, primitiveDef );
  38539. computeBounds( geometry, primitiveDef, parser );
  38540. return Promise.all( pending ).then( function () {
  38541. return primitiveDef.targets !== undefined
  38542. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  38543. : geometry;
  38544. } );
  38545. }
  38546. /**
  38547. * @param {THREE.BufferGeometry} geometry
  38548. * @param {Number} drawMode
  38549. * @return {THREE.BufferGeometry}
  38550. */
  38551. function toTrianglesDrawMode( geometry, drawMode ) {
  38552. var index = geometry.getIndex();
  38553. // generate index if not present
  38554. if ( index === null ) {
  38555. var indices = [];
  38556. var position = geometry.getAttribute( 'position' );
  38557. if ( position !== undefined ) {
  38558. for ( var i = 0; i < position.count; i ++ ) {
  38559. indices.push( i );
  38560. }
  38561. geometry.setIndex( indices );
  38562. index = geometry.getIndex();
  38563. } else {
  38564. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  38565. return geometry;
  38566. }
  38567. }
  38568. //
  38569. var numberOfTriangles = index.count - 2;
  38570. var newIndices = [];
  38571. if ( drawMode === THREE.TriangleFanDrawMode ) {
  38572. // gl.TRIANGLE_FAN
  38573. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  38574. newIndices.push( index.getX( 0 ) );
  38575. newIndices.push( index.getX( i ) );
  38576. newIndices.push( index.getX( i + 1 ) );
  38577. }
  38578. } else {
  38579. // gl.TRIANGLE_STRIP
  38580. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  38581. if ( i % 2 === 0 ) {
  38582. newIndices.push( index.getX( i ) );
  38583. newIndices.push( index.getX( i + 1 ) );
  38584. newIndices.push( index.getX( i + 2 ) );
  38585. } else {
  38586. newIndices.push( index.getX( i + 2 ) );
  38587. newIndices.push( index.getX( i + 1 ) );
  38588. newIndices.push( index.getX( i ) );
  38589. }
  38590. }
  38591. }
  38592. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  38593. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  38594. }
  38595. // build final geometry
  38596. var newGeometry = geometry.clone();
  38597. newGeometry.setIndex( newIndices );
  38598. return newGeometry;
  38599. }
  38600. /**
  38601. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  38602. *
  38603. * Creates BufferGeometries from primitives.
  38604. *
  38605. * @param {Array<GLTF.Primitive>} primitives
  38606. * @return {Promise<Array<THREE.BufferGeometry>>}
  38607. */
  38608. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  38609. var parser = this;
  38610. var extensions = this.extensions;
  38611. var cache = this.primitiveCache;
  38612. function createDracoPrimitive( primitive ) {
  38613. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  38614. .decodePrimitive( primitive, parser )
  38615. .then( function ( geometry ) {
  38616. return addPrimitiveAttributes( geometry, primitive, parser );
  38617. } );
  38618. }
  38619. var pending = [];
  38620. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38621. var primitive = primitives[ i ];
  38622. var cacheKey = createPrimitiveKey( primitive );
  38623. // See if we've already created this geometry
  38624. var cached = cache[ cacheKey ];
  38625. if ( cached ) {
  38626. // Use the cached geometry if it exists
  38627. pending.push( cached.promise );
  38628. } else {
  38629. var geometryPromise;
  38630. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  38631. // Use DRACO geometry if available
  38632. geometryPromise = createDracoPrimitive( primitive );
  38633. } else {
  38634. // Otherwise create a new geometry
  38635. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  38636. }
  38637. // Cache this geometry
  38638. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  38639. pending.push( geometryPromise );
  38640. }
  38641. }
  38642. return Promise.all( pending );
  38643. };
  38644. /**
  38645. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  38646. * @param {number} meshIndex
  38647. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  38648. */
  38649. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  38650. var parser = this;
  38651. var json = this.json;
  38652. var meshDef = json.meshes[ meshIndex ];
  38653. var primitives = meshDef.primitives;
  38654. var pending = [];
  38655. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38656. var material = primitives[ i ].material === undefined
  38657. ? createDefaultMaterial( this.cache )
  38658. : this.getDependency( 'material', primitives[ i ].material );
  38659. pending.push( material );
  38660. }
  38661. pending.push( parser.loadGeometries( primitives ) );
  38662. return Promise.all( pending ).then( function ( results ) {
  38663. var materials = results.slice( 0, results.length - 1 );
  38664. var geometries = results[ results.length - 1 ];
  38665. var meshes = [];
  38666. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  38667. var geometry = geometries[ i ];
  38668. var primitive = primitives[ i ];
  38669. // 1. create Mesh
  38670. var mesh;
  38671. var material = materials[ i ];
  38672. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  38673. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  38674. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  38675. primitive.mode === undefined ) {
  38676. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  38677. mesh = meshDef.isSkinnedMesh === true
  38678. ? new THREE.SkinnedMesh( geometry, material )
  38679. : new THREE.Mesh( geometry, material );
  38680. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  38681. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  38682. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  38683. mesh.normalizeSkinWeights();
  38684. }
  38685. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  38686. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  38687. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  38688. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  38689. }
  38690. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  38691. mesh = new THREE.LineSegments( geometry, material );
  38692. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  38693. mesh = new THREE.Line( geometry, material );
  38694. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  38695. mesh = new THREE.LineLoop( geometry, material );
  38696. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  38697. mesh = new THREE.Points( geometry, material );
  38698. } else {
  38699. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  38700. }
  38701. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  38702. updateMorphTargets( mesh, meshDef );
  38703. }
  38704. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  38705. if ( geometries.length > 1 ) mesh.name += '_' + i;
  38706. assignExtrasToUserData( mesh, meshDef );
  38707. parser.assignFinalMaterial( mesh );
  38708. meshes.push( mesh );
  38709. }
  38710. if ( meshes.length === 1 ) {
  38711. return meshes[ 0 ];
  38712. }
  38713. var group = new THREE.Group();
  38714. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  38715. group.add( meshes[ i ] );
  38716. }
  38717. return group;
  38718. } );
  38719. };
  38720. /**
  38721. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  38722. * @param {number} cameraIndex
  38723. * @return {Promise<THREE.Camera>}
  38724. */
  38725. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  38726. var camera;
  38727. var cameraDef = this.json.cameras[ cameraIndex ];
  38728. var params = cameraDef[ cameraDef.type ];
  38729. if ( ! params ) {
  38730. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  38731. return;
  38732. }
  38733. if ( cameraDef.type === 'perspective' ) {
  38734. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  38735. } else if ( cameraDef.type === 'orthographic' ) {
  38736. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  38737. }
  38738. if ( cameraDef.name ) camera.name = cameraDef.name;
  38739. assignExtrasToUserData( camera, cameraDef );
  38740. return Promise.resolve( camera );
  38741. };
  38742. /**
  38743. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  38744. * @param {number} skinIndex
  38745. * @return {Promise<Object>}
  38746. */
  38747. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  38748. var skinDef = this.json.skins[ skinIndex ];
  38749. var skinEntry = { joints: skinDef.joints };
  38750. if ( skinDef.inverseBindMatrices === undefined ) {
  38751. return Promise.resolve( skinEntry );
  38752. }
  38753. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  38754. skinEntry.inverseBindMatrices = accessor;
  38755. return skinEntry;
  38756. } );
  38757. };
  38758. /**
  38759. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  38760. * @param {number} animationIndex
  38761. * @return {Promise<THREE.AnimationClip>}
  38762. */
  38763. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  38764. var json = this.json;
  38765. var animationDef = json.animations[ animationIndex ];
  38766. var pendingNodes = [];
  38767. var pendingInputAccessors = [];
  38768. var pendingOutputAccessors = [];
  38769. var pendingSamplers = [];
  38770. var pendingTargets = [];
  38771. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  38772. var channel = animationDef.channels[ i ];
  38773. var sampler = animationDef.samplers[ channel.sampler ];
  38774. var target = channel.target;
  38775. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  38776. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  38777. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  38778. pendingNodes.push( this.getDependency( 'node', name ) );
  38779. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  38780. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  38781. pendingSamplers.push( sampler );
  38782. pendingTargets.push( target );
  38783. }
  38784. return Promise.all( [
  38785. Promise.all( pendingNodes ),
  38786. Promise.all( pendingInputAccessors ),
  38787. Promise.all( pendingOutputAccessors ),
  38788. Promise.all( pendingSamplers ),
  38789. Promise.all( pendingTargets )
  38790. ] ).then( function ( dependencies ) {
  38791. var nodes = dependencies[ 0 ];
  38792. var inputAccessors = dependencies[ 1 ];
  38793. var outputAccessors = dependencies[ 2 ];
  38794. var samplers = dependencies[ 3 ];
  38795. var targets = dependencies[ 4 ];
  38796. var tracks = [];
  38797. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  38798. var node = nodes[ i ];
  38799. var inputAccessor = inputAccessors[ i ];
  38800. var outputAccessor = outputAccessors[ i ];
  38801. var sampler = samplers[ i ];
  38802. var target = targets[ i ];
  38803. if ( node === undefined ) continue;
  38804. node.updateMatrix();
  38805. node.matrixAutoUpdate = true;
  38806. var TypedKeyframeTrack;
  38807. switch ( PATH_PROPERTIES[ target.path ] ) {
  38808. case PATH_PROPERTIES.weights:
  38809. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  38810. break;
  38811. case PATH_PROPERTIES.rotation:
  38812. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  38813. break;
  38814. case PATH_PROPERTIES.position:
  38815. case PATH_PROPERTIES.scale:
  38816. default:
  38817. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  38818. break;
  38819. }
  38820. var targetName = node.name ? node.name : node.uuid;
  38821. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  38822. var targetNames = [];
  38823. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  38824. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  38825. node.traverse( function ( object ) {
  38826. if ( object.isMesh === true && object.morphTargetInfluences ) {
  38827. targetNames.push( object.name ? object.name : object.uuid );
  38828. }
  38829. } );
  38830. } else {
  38831. targetNames.push( targetName );
  38832. }
  38833. var outputArray = outputAccessor.array;
  38834. if ( outputAccessor.normalized ) {
  38835. var scale;
  38836. if ( outputArray.constructor === Int8Array ) {
  38837. scale = 1 / 127;
  38838. } else if ( outputArray.constructor === Uint8Array ) {
  38839. scale = 1 / 255;
  38840. } else if ( outputArray.constructor == Int16Array ) {
  38841. scale = 1 / 32767;
  38842. } else if ( outputArray.constructor === Uint16Array ) {
  38843. scale = 1 / 65535;
  38844. } else {
  38845. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  38846. }
  38847. var scaled = new Float32Array( outputArray.length );
  38848. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  38849. scaled[ j ] = outputArray[ j ] * scale;
  38850. }
  38851. outputArray = scaled;
  38852. }
  38853. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  38854. var track = new TypedKeyframeTrack(
  38855. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  38856. inputAccessor.array,
  38857. outputArray,
  38858. interpolation
  38859. );
  38860. // Override interpolation with custom factory method.
  38861. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  38862. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  38863. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  38864. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  38865. // must be divided by three to get the interpolant's sampleSize argument.
  38866. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  38867. };
  38868. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  38869. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  38870. }
  38871. tracks.push( track );
  38872. }
  38873. }
  38874. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  38875. return new THREE.AnimationClip( name, undefined, tracks );
  38876. } );
  38877. };
  38878. /**
  38879. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  38880. * @param {number} nodeIndex
  38881. * @return {Promise<THREE.Object3D>}
  38882. */
  38883. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  38884. var json = this.json;
  38885. var extensions = this.extensions;
  38886. var parser = this;
  38887. var nodeDef = json.nodes[ nodeIndex ];
  38888. return ( function () {
  38889. var pending = [];
  38890. if ( nodeDef.mesh !== undefined ) {
  38891. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  38892. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  38893. // if weights are provided on the node, override weights on the mesh.
  38894. if ( nodeDef.weights !== undefined ) {
  38895. node.traverse( function ( o ) {
  38896. if ( ! o.isMesh ) return;
  38897. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  38898. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  38899. }
  38900. } );
  38901. }
  38902. return node;
  38903. } ) );
  38904. }
  38905. if ( nodeDef.camera !== undefined ) {
  38906. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  38907. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  38908. } ) );
  38909. }
  38910. if ( nodeDef.extensions
  38911. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  38912. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  38913. var lightIndex = nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light;
  38914. pending.push( parser.getDependency( 'light', lightIndex ).then( function ( light ) {
  38915. return parser._getNodeRef( parser.lightCache, lightIndex, light );
  38916. } ) );
  38917. }
  38918. return Promise.all( pending );
  38919. }() ).then( function ( objects ) {
  38920. var node;
  38921. // .isBone isn't in glTF spec. See ._markDefs
  38922. if ( nodeDef.isBone === true ) {
  38923. node = new THREE.Bone();
  38924. } else if ( objects.length > 1 ) {
  38925. node = new THREE.Group();
  38926. } else if ( objects.length === 1 ) {
  38927. node = objects[ 0 ];
  38928. } else {
  38929. node = new THREE.Object3D();
  38930. }
  38931. if ( node !== objects[ 0 ] ) {
  38932. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  38933. node.add( objects[ i ] );
  38934. }
  38935. }
  38936. if ( nodeDef.name ) {
  38937. node.userData.name = nodeDef.name;
  38938. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  38939. }
  38940. assignExtrasToUserData( node, nodeDef );
  38941. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  38942. if ( nodeDef.matrix !== undefined ) {
  38943. var matrix = new THREE.Matrix4();
  38944. matrix.fromArray( nodeDef.matrix );
  38945. node.applyMatrix4( matrix );
  38946. } else {
  38947. if ( nodeDef.translation !== undefined ) {
  38948. node.position.fromArray( nodeDef.translation );
  38949. }
  38950. if ( nodeDef.rotation !== undefined ) {
  38951. node.quaternion.fromArray( nodeDef.rotation );
  38952. }
  38953. if ( nodeDef.scale !== undefined ) {
  38954. node.scale.fromArray( nodeDef.scale );
  38955. }
  38956. }
  38957. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  38958. return node;
  38959. } );
  38960. };
  38961. /**
  38962. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  38963. * @param {number} sceneIndex
  38964. * @return {Promise<THREE.Group>}
  38965. */
  38966. GLTFParser.prototype.loadScene = function () {
  38967. // scene node hierachy builder
  38968. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  38969. var nodeDef = json.nodes[ nodeId ];
  38970. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  38971. if ( nodeDef.skin === undefined ) return node;
  38972. // build skeleton here as well
  38973. var skinEntry;
  38974. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  38975. skinEntry = skin;
  38976. var pendingJoints = [];
  38977. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  38978. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  38979. }
  38980. return Promise.all( pendingJoints );
  38981. } ).then( function ( jointNodes ) {
  38982. node.traverse( function ( mesh ) {
  38983. if ( ! mesh.isMesh ) return;
  38984. var bones = [];
  38985. var boneInverses = [];
  38986. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  38987. var jointNode = jointNodes[ j ];
  38988. if ( jointNode ) {
  38989. bones.push( jointNode );
  38990. var mat = new THREE.Matrix4();
  38991. if ( skinEntry.inverseBindMatrices !== undefined ) {
  38992. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  38993. }
  38994. boneInverses.push( mat );
  38995. } else {
  38996. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  38997. }
  38998. }
  38999. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  39000. } );
  39001. return node;
  39002. } );
  39003. } ).then( function ( node ) {
  39004. // build node hierachy
  39005. parentObject.add( node );
  39006. var pending = [];
  39007. if ( nodeDef.children ) {
  39008. var children = nodeDef.children;
  39009. for ( var i = 0, il = children.length; i < il; i ++ ) {
  39010. var child = children[ i ];
  39011. pending.push( buildNodeHierachy( child, node, json, parser ) );
  39012. }
  39013. }
  39014. return Promise.all( pending );
  39015. } );
  39016. }
  39017. return function loadScene( sceneIndex ) {
  39018. var json = this.json;
  39019. var extensions = this.extensions;
  39020. var sceneDef = this.json.scenes[ sceneIndex ];
  39021. var parser = this;
  39022. // Loader returns Group, not Scene.
  39023. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  39024. var scene = new THREE.Group();
  39025. if ( sceneDef.name ) scene.name = sceneDef.name;
  39026. assignExtrasToUserData( scene, sceneDef );
  39027. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  39028. var nodeIds = sceneDef.nodes || [];
  39029. var pending = [];
  39030. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  39031. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  39032. }
  39033. return Promise.all( pending ).then( function () {
  39034. return scene;
  39035. } );
  39036. };
  39037. }();
  39038. return GLTFLoader;
  39039. } )();
  39040. },{}],60:[function(_dereq_,module,exports){
  39041. console.warn( "THREE.MTLLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  39042. /**
  39043. * Loads a Wavefront .mtl file specifying materials
  39044. */
  39045. THREE.MTLLoader = function ( manager ) {
  39046. THREE.Loader.call( this, manager );
  39047. };
  39048. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  39049. constructor: THREE.MTLLoader,
  39050. /**
  39051. * Loads and parses a MTL asset from a URL.
  39052. *
  39053. * @param {String} url - URL to the MTL file.
  39054. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  39055. * @param {Function} [onProgress] - Callback for download progress.
  39056. * @param {Function} [onError] - Callback for download errors.
  39057. *
  39058. * @see setPath setResourcePath
  39059. *
  39060. * @note In order for relative texture references to resolve correctly
  39061. * you must call setResourcePath() explicitly prior to load.
  39062. */
  39063. load: function ( url, onLoad, onProgress, onError ) {
  39064. var scope = this;
  39065. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  39066. var loader = new THREE.FileLoader( this.manager );
  39067. loader.setPath( this.path );
  39068. loader.setRequestHeader( this.requestHeader );
  39069. loader.load( url, function ( text ) {
  39070. try {
  39071. onLoad( scope.parse( text, path ) );
  39072. } catch ( e ) {
  39073. if ( onError ) {
  39074. onError( e );
  39075. } else {
  39076. console.error( e );
  39077. }
  39078. scope.manager.itemError( url );
  39079. }
  39080. }, onProgress, onError );
  39081. },
  39082. setMaterialOptions: function ( value ) {
  39083. this.materialOptions = value;
  39084. return this;
  39085. },
  39086. /**
  39087. * Parses a MTL file.
  39088. *
  39089. * @param {String} text - Content of MTL file
  39090. * @return {THREE.MTLLoader.MaterialCreator}
  39091. *
  39092. * @see setPath setResourcePath
  39093. *
  39094. * @note In order for relative texture references to resolve correctly
  39095. * you must call setResourcePath() explicitly prior to parse.
  39096. */
  39097. parse: function ( text, path ) {
  39098. var lines = text.split( '\n' );
  39099. var info = {};
  39100. var delimiter_pattern = /\s+/;
  39101. var materialsInfo = {};
  39102. for ( var i = 0; i < lines.length; i ++ ) {
  39103. var line = lines[ i ];
  39104. line = line.trim();
  39105. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  39106. // Blank line or comment ignore
  39107. continue;
  39108. }
  39109. var pos = line.indexOf( ' ' );
  39110. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  39111. key = key.toLowerCase();
  39112. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  39113. value = value.trim();
  39114. if ( key === 'newmtl' ) {
  39115. // New material
  39116. info = { name: value };
  39117. materialsInfo[ value ] = info;
  39118. } else {
  39119. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  39120. var ss = value.split( delimiter_pattern, 3 );
  39121. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  39122. } else {
  39123. info[ key ] = value;
  39124. }
  39125. }
  39126. }
  39127. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  39128. materialCreator.setCrossOrigin( this.crossOrigin );
  39129. materialCreator.setManager( this.manager );
  39130. materialCreator.setMaterials( materialsInfo );
  39131. return materialCreator;
  39132. }
  39133. } );
  39134. /**
  39135. * Create a new THREE.MTLLoader.MaterialCreator
  39136. * @param baseUrl - Url relative to which textures are loaded
  39137. * @param options - Set of options on how to construct the materials
  39138. * side: Which side to apply the material
  39139. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  39140. * wrap: What type of wrapping to apply for textures
  39141. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  39142. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  39143. * Default: false, assumed to be already normalized
  39144. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  39145. * Default: false
  39146. * @constructor
  39147. */
  39148. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  39149. this.baseUrl = baseUrl || '';
  39150. this.options = options;
  39151. this.materialsInfo = {};
  39152. this.materials = {};
  39153. this.materialsArray = [];
  39154. this.nameLookup = {};
  39155. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  39156. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  39157. };
  39158. THREE.MTLLoader.MaterialCreator.prototype = {
  39159. constructor: THREE.MTLLoader.MaterialCreator,
  39160. crossOrigin: 'anonymous',
  39161. setCrossOrigin: function ( value ) {
  39162. this.crossOrigin = value;
  39163. return this;
  39164. },
  39165. setManager: function ( value ) {
  39166. this.manager = value;
  39167. },
  39168. setMaterials: function ( materialsInfo ) {
  39169. this.materialsInfo = this.convert( materialsInfo );
  39170. this.materials = {};
  39171. this.materialsArray = [];
  39172. this.nameLookup = {};
  39173. },
  39174. convert: function ( materialsInfo ) {
  39175. if ( ! this.options ) return materialsInfo;
  39176. var converted = {};
  39177. for ( var mn in materialsInfo ) {
  39178. // Convert materials info into normalized form based on options
  39179. var mat = materialsInfo[ mn ];
  39180. var covmat = {};
  39181. converted[ mn ] = covmat;
  39182. for ( var prop in mat ) {
  39183. var save = true;
  39184. var value = mat[ prop ];
  39185. var lprop = prop.toLowerCase();
  39186. switch ( lprop ) {
  39187. case 'kd':
  39188. case 'ka':
  39189. case 'ks':
  39190. // Diffuse color (color under white light) using RGB values
  39191. if ( this.options && this.options.normalizeRGB ) {
  39192. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  39193. }
  39194. if ( this.options && this.options.ignoreZeroRGBs ) {
  39195. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  39196. // ignore
  39197. save = false;
  39198. }
  39199. }
  39200. break;
  39201. default:
  39202. break;
  39203. }
  39204. if ( save ) {
  39205. covmat[ lprop ] = value;
  39206. }
  39207. }
  39208. }
  39209. return converted;
  39210. },
  39211. preload: function () {
  39212. for ( var mn in this.materialsInfo ) {
  39213. this.create( mn );
  39214. }
  39215. },
  39216. getIndex: function ( materialName ) {
  39217. return this.nameLookup[ materialName ];
  39218. },
  39219. getAsArray: function () {
  39220. var index = 0;
  39221. for ( var mn in this.materialsInfo ) {
  39222. this.materialsArray[ index ] = this.create( mn );
  39223. this.nameLookup[ mn ] = index;
  39224. index ++;
  39225. }
  39226. return this.materialsArray;
  39227. },
  39228. create: function ( materialName ) {
  39229. if ( this.materials[ materialName ] === undefined ) {
  39230. this.createMaterial_( materialName );
  39231. }
  39232. return this.materials[ materialName ];
  39233. },
  39234. createMaterial_: function ( materialName ) {
  39235. // Create material
  39236. var scope = this;
  39237. var mat = this.materialsInfo[ materialName ];
  39238. var params = {
  39239. name: materialName,
  39240. side: this.side
  39241. };
  39242. function resolveURL( baseUrl, url ) {
  39243. if ( typeof url !== 'string' || url === '' )
  39244. return '';
  39245. // Absolute URL
  39246. if ( /^https?:\/\//i.test( url ) ) return url;
  39247. return baseUrl + url;
  39248. }
  39249. function setMapForType( mapType, value ) {
  39250. if ( params[ mapType ] ) return; // Keep the first encountered texture
  39251. var texParams = scope.getTextureParams( value, params );
  39252. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  39253. map.repeat.copy( texParams.scale );
  39254. map.offset.copy( texParams.offset );
  39255. map.wrapS = scope.wrap;
  39256. map.wrapT = scope.wrap;
  39257. params[ mapType ] = map;
  39258. }
  39259. for ( var prop in mat ) {
  39260. var value = mat[ prop ];
  39261. var n;
  39262. if ( value === '' ) continue;
  39263. switch ( prop.toLowerCase() ) {
  39264. // Ns is material specular exponent
  39265. case 'kd':
  39266. // Diffuse color (color under white light) using RGB values
  39267. params.color = new THREE.Color().fromArray( value );
  39268. break;
  39269. case 'ks':
  39270. // Specular color (color when light is reflected from shiny surface) using RGB values
  39271. params.specular = new THREE.Color().fromArray( value );
  39272. break;
  39273. case 'ke':
  39274. // Emissive using RGB values
  39275. params.emissive = new THREE.Color().fromArray( value );
  39276. break;
  39277. case 'map_kd':
  39278. // Diffuse texture map
  39279. setMapForType( "map", value );
  39280. break;
  39281. case 'map_ks':
  39282. // Specular map
  39283. setMapForType( "specularMap", value );
  39284. break;
  39285. case 'map_ke':
  39286. // Emissive map
  39287. setMapForType( "emissiveMap", value );
  39288. break;
  39289. case 'norm':
  39290. setMapForType( "normalMap", value );
  39291. break;
  39292. case 'map_bump':
  39293. case 'bump':
  39294. // Bump texture map
  39295. setMapForType( "bumpMap", value );
  39296. break;
  39297. case 'map_d':
  39298. // Alpha map
  39299. setMapForType( "alphaMap", value );
  39300. params.transparent = true;
  39301. break;
  39302. case 'ns':
  39303. // The specular exponent (defines the focus of the specular highlight)
  39304. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  39305. params.shininess = parseFloat( value );
  39306. break;
  39307. case 'd':
  39308. n = parseFloat( value );
  39309. if ( n < 1 ) {
  39310. params.opacity = n;
  39311. params.transparent = true;
  39312. }
  39313. break;
  39314. case 'tr':
  39315. n = parseFloat( value );
  39316. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  39317. if ( n > 0 ) {
  39318. params.opacity = 1 - n;
  39319. params.transparent = true;
  39320. }
  39321. break;
  39322. default:
  39323. break;
  39324. }
  39325. }
  39326. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  39327. return this.materials[ materialName ];
  39328. },
  39329. getTextureParams: function ( value, matParams ) {
  39330. var texParams = {
  39331. scale: new THREE.Vector2( 1, 1 ),
  39332. offset: new THREE.Vector2( 0, 0 )
  39333. };
  39334. var items = value.split( /\s+/ );
  39335. var pos;
  39336. pos = items.indexOf( '-bm' );
  39337. if ( pos >= 0 ) {
  39338. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  39339. items.splice( pos, 2 );
  39340. }
  39341. pos = items.indexOf( '-s' );
  39342. if ( pos >= 0 ) {
  39343. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39344. items.splice( pos, 4 ); // we expect 3 parameters here!
  39345. }
  39346. pos = items.indexOf( '-o' );
  39347. if ( pos >= 0 ) {
  39348. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39349. items.splice( pos, 4 ); // we expect 3 parameters here!
  39350. }
  39351. texParams.url = items.join( ' ' ).trim();
  39352. return texParams;
  39353. },
  39354. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  39355. var texture;
  39356. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  39357. var loader = manager.getHandler( url );
  39358. if ( loader === null ) {
  39359. loader = new THREE.TextureLoader( manager );
  39360. }
  39361. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  39362. texture = loader.load( url, onLoad, onProgress, onError );
  39363. if ( mapping !== undefined ) texture.mapping = mapping;
  39364. return texture;
  39365. }
  39366. };
  39367. },{}],61:[function(_dereq_,module,exports){
  39368. console.warn( "THREE.OBJLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  39369. THREE.OBJLoader = ( function () {
  39370. // o object_name | g group_name
  39371. var object_pattern = /^[og]\s*(.+)?/;
  39372. // mtllib file_reference
  39373. var material_library_pattern = /^mtllib /;
  39374. // usemtl material_name
  39375. var material_use_pattern = /^usemtl /;
  39376. // usemap map_name
  39377. var map_use_pattern = /^usemap /;
  39378. var vA = new THREE.Vector3();
  39379. var vB = new THREE.Vector3();
  39380. var vC = new THREE.Vector3();
  39381. var ab = new THREE.Vector3();
  39382. var cb = new THREE.Vector3();
  39383. function ParserState() {
  39384. var state = {
  39385. objects: [],
  39386. object: {},
  39387. vertices: [],
  39388. normals: [],
  39389. colors: [],
  39390. uvs: [],
  39391. materials: {},
  39392. materialLibraries: [],
  39393. startObject: function ( name, fromDeclaration ) {
  39394. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  39395. // file. We need to use it for the first parsed g/o to keep things in sync.
  39396. if ( this.object && this.object.fromDeclaration === false ) {
  39397. this.object.name = name;
  39398. this.object.fromDeclaration = ( fromDeclaration !== false );
  39399. return;
  39400. }
  39401. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  39402. if ( this.object && typeof this.object._finalize === 'function' ) {
  39403. this.object._finalize( true );
  39404. }
  39405. this.object = {
  39406. name: name || '',
  39407. fromDeclaration: ( fromDeclaration !== false ),
  39408. geometry: {
  39409. vertices: [],
  39410. normals: [],
  39411. colors: [],
  39412. uvs: [],
  39413. hasNormalIndices: false,
  39414. hasUVIndices: false
  39415. },
  39416. materials: [],
  39417. smooth: true,
  39418. startMaterial: function ( name, libraries ) {
  39419. var previous = this._finalize( false );
  39420. // New usemtl declaration overwrites an inherited material, except if faces were declared
  39421. // after the material, then it must be preserved for proper MultiMaterial continuation.
  39422. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  39423. this.materials.splice( previous.index, 1 );
  39424. }
  39425. var material = {
  39426. index: this.materials.length,
  39427. name: name || '',
  39428. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  39429. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  39430. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  39431. groupEnd: - 1,
  39432. groupCount: - 1,
  39433. inherited: false,
  39434. clone: function ( index ) {
  39435. var cloned = {
  39436. index: ( typeof index === 'number' ? index : this.index ),
  39437. name: this.name,
  39438. mtllib: this.mtllib,
  39439. smooth: this.smooth,
  39440. groupStart: 0,
  39441. groupEnd: - 1,
  39442. groupCount: - 1,
  39443. inherited: false
  39444. };
  39445. cloned.clone = this.clone.bind( cloned );
  39446. return cloned;
  39447. }
  39448. };
  39449. this.materials.push( material );
  39450. return material;
  39451. },
  39452. currentMaterial: function () {
  39453. if ( this.materials.length > 0 ) {
  39454. return this.materials[ this.materials.length - 1 ];
  39455. }
  39456. return undefined;
  39457. },
  39458. _finalize: function ( end ) {
  39459. var lastMultiMaterial = this.currentMaterial();
  39460. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  39461. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  39462. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  39463. lastMultiMaterial.inherited = false;
  39464. }
  39465. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  39466. if ( end && this.materials.length > 1 ) {
  39467. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  39468. if ( this.materials[ mi ].groupCount <= 0 ) {
  39469. this.materials.splice( mi, 1 );
  39470. }
  39471. }
  39472. }
  39473. // Guarantee at least one empty material, this makes the creation later more straight forward.
  39474. if ( end && this.materials.length === 0 ) {
  39475. this.materials.push( {
  39476. name: '',
  39477. smooth: this.smooth
  39478. } );
  39479. }
  39480. return lastMultiMaterial;
  39481. }
  39482. };
  39483. // Inherit previous objects material.
  39484. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  39485. // If a usemtl declaration is encountered while this new object is being parsed, it will
  39486. // overwrite the inherited material. Exception being that there was already face declarations
  39487. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  39488. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  39489. var declared = previousMaterial.clone( 0 );
  39490. declared.inherited = true;
  39491. this.object.materials.push( declared );
  39492. }
  39493. this.objects.push( this.object );
  39494. },
  39495. finalize: function () {
  39496. if ( this.object && typeof this.object._finalize === 'function' ) {
  39497. this.object._finalize( true );
  39498. }
  39499. },
  39500. parseVertexIndex: function ( value, len ) {
  39501. var index = parseInt( value, 10 );
  39502. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39503. },
  39504. parseNormalIndex: function ( value, len ) {
  39505. var index = parseInt( value, 10 );
  39506. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39507. },
  39508. parseUVIndex: function ( value, len ) {
  39509. var index = parseInt( value, 10 );
  39510. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  39511. },
  39512. addVertex: function ( a, b, c ) {
  39513. var src = this.vertices;
  39514. var dst = this.object.geometry.vertices;
  39515. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39516. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39517. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39518. },
  39519. addVertexPoint: function ( a ) {
  39520. var src = this.vertices;
  39521. var dst = this.object.geometry.vertices;
  39522. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39523. },
  39524. addVertexLine: function ( a ) {
  39525. var src = this.vertices;
  39526. var dst = this.object.geometry.vertices;
  39527. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39528. },
  39529. addNormal: function ( a, b, c ) {
  39530. var src = this.normals;
  39531. var dst = this.object.geometry.normals;
  39532. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39533. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39534. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39535. },
  39536. addFaceNormal: function ( a, b, c ) {
  39537. var src = this.vertices;
  39538. var dst = this.object.geometry.normals;
  39539. vA.fromArray( src, a );
  39540. vB.fromArray( src, b );
  39541. vC.fromArray( src, c );
  39542. cb.subVectors( vC, vB );
  39543. ab.subVectors( vA, vB );
  39544. cb.cross( ab );
  39545. cb.normalize();
  39546. dst.push( cb.x, cb.y, cb.z );
  39547. dst.push( cb.x, cb.y, cb.z );
  39548. dst.push( cb.x, cb.y, cb.z );
  39549. },
  39550. addColor: function ( a, b, c ) {
  39551. var src = this.colors;
  39552. var dst = this.object.geometry.colors;
  39553. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39554. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39555. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39556. },
  39557. addUV: function ( a, b, c ) {
  39558. var src = this.uvs;
  39559. var dst = this.object.geometry.uvs;
  39560. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39561. dst.push( src[ b + 0 ], src[ b + 1 ] );
  39562. dst.push( src[ c + 0 ], src[ c + 1 ] );
  39563. },
  39564. addDefaultUV: function () {
  39565. var dst = this.object.geometry.uvs;
  39566. dst.push( 0, 0 );
  39567. dst.push( 0, 0 );
  39568. dst.push( 0, 0 );
  39569. },
  39570. addUVLine: function ( a ) {
  39571. var src = this.uvs;
  39572. var dst = this.object.geometry.uvs;
  39573. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39574. },
  39575. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  39576. var vLen = this.vertices.length;
  39577. var ia = this.parseVertexIndex( a, vLen );
  39578. var ib = this.parseVertexIndex( b, vLen );
  39579. var ic = this.parseVertexIndex( c, vLen );
  39580. this.addVertex( ia, ib, ic );
  39581. this.addColor( ia, ib, ic );
  39582. // normals
  39583. if ( na !== undefined && na !== '' ) {
  39584. var nLen = this.normals.length;
  39585. ia = this.parseNormalIndex( na, nLen );
  39586. ib = this.parseNormalIndex( nb, nLen );
  39587. ic = this.parseNormalIndex( nc, nLen );
  39588. this.addNormal( ia, ib, ic );
  39589. this.object.geometry.hasNormalIndices = true;
  39590. } else {
  39591. this.addFaceNormal( ia, ib, ic );
  39592. }
  39593. // uvs
  39594. if ( ua !== undefined && ua !== '' ) {
  39595. var uvLen = this.uvs.length;
  39596. ia = this.parseUVIndex( ua, uvLen );
  39597. ib = this.parseUVIndex( ub, uvLen );
  39598. ic = this.parseUVIndex( uc, uvLen );
  39599. this.addUV( ia, ib, ic );
  39600. this.object.geometry.hasUVIndices = true;
  39601. } else {
  39602. // add placeholder values (for inconsistent face definitions)
  39603. this.addDefaultUV();
  39604. }
  39605. },
  39606. addPointGeometry: function ( vertices ) {
  39607. this.object.geometry.type = 'Points';
  39608. var vLen = this.vertices.length;
  39609. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39610. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39611. }
  39612. },
  39613. addLineGeometry: function ( vertices, uvs ) {
  39614. this.object.geometry.type = 'Line';
  39615. var vLen = this.vertices.length;
  39616. var uvLen = this.uvs.length;
  39617. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39618. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39619. }
  39620. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  39621. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  39622. }
  39623. }
  39624. };
  39625. state.startObject( '', false );
  39626. return state;
  39627. }
  39628. //
  39629. function OBJLoader( manager ) {
  39630. THREE.Loader.call( this, manager );
  39631. this.materials = null;
  39632. }
  39633. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  39634. constructor: OBJLoader,
  39635. load: function ( url, onLoad, onProgress, onError ) {
  39636. var scope = this;
  39637. var loader = new THREE.FileLoader( scope.manager );
  39638. loader.setPath( this.path );
  39639. loader.setRequestHeader( this.requestHeader );
  39640. loader.load( url, function ( text ) {
  39641. try {
  39642. onLoad( scope.parse( text ) );
  39643. } catch ( e ) {
  39644. if ( onError ) {
  39645. onError( e );
  39646. } else {
  39647. console.error( e );
  39648. }
  39649. scope.manager.itemError( url );
  39650. }
  39651. }, onProgress, onError );
  39652. },
  39653. setMaterials: function ( materials ) {
  39654. this.materials = materials;
  39655. return this;
  39656. },
  39657. parse: function ( text ) {
  39658. var state = new ParserState();
  39659. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  39660. // This is faster than String.split with regex that splits on both
  39661. text = text.replace( /\r\n/g, '\n' );
  39662. }
  39663. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  39664. // join lines separated by a line continuation character (\)
  39665. text = text.replace( /\\\n/g, '' );
  39666. }
  39667. var lines = text.split( '\n' );
  39668. var line = '', lineFirstChar = '';
  39669. var lineLength = 0;
  39670. var result = [];
  39671. // Faster to just trim left side of the line. Use if available.
  39672. var trimLeft = ( typeof ''.trimLeft === 'function' );
  39673. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  39674. line = lines[ i ];
  39675. line = trimLeft ? line.trimLeft() : line.trim();
  39676. lineLength = line.length;
  39677. if ( lineLength === 0 ) continue;
  39678. lineFirstChar = line.charAt( 0 );
  39679. // @todo invoke passed in handler if any
  39680. if ( lineFirstChar === '#' ) continue;
  39681. if ( lineFirstChar === 'v' ) {
  39682. var data = line.split( /\s+/ );
  39683. switch ( data[ 0 ] ) {
  39684. case 'v':
  39685. state.vertices.push(
  39686. parseFloat( data[ 1 ] ),
  39687. parseFloat( data[ 2 ] ),
  39688. parseFloat( data[ 3 ] )
  39689. );
  39690. if ( data.length >= 7 ) {
  39691. state.colors.push(
  39692. parseFloat( data[ 4 ] ),
  39693. parseFloat( data[ 5 ] ),
  39694. parseFloat( data[ 6 ] )
  39695. );
  39696. } else {
  39697. // if no colors are defined, add placeholders so color and vertex indices match
  39698. state.colors.push( undefined, undefined, undefined );
  39699. }
  39700. break;
  39701. case 'vn':
  39702. state.normals.push(
  39703. parseFloat( data[ 1 ] ),
  39704. parseFloat( data[ 2 ] ),
  39705. parseFloat( data[ 3 ] )
  39706. );
  39707. break;
  39708. case 'vt':
  39709. state.uvs.push(
  39710. parseFloat( data[ 1 ] ),
  39711. parseFloat( data[ 2 ] )
  39712. );
  39713. break;
  39714. }
  39715. } else if ( lineFirstChar === 'f' ) {
  39716. var lineData = line.substr( 1 ).trim();
  39717. var vertexData = lineData.split( /\s+/ );
  39718. var faceVertices = [];
  39719. // Parse the face vertex data into an easy to work with format
  39720. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  39721. var vertex = vertexData[ j ];
  39722. if ( vertex.length > 0 ) {
  39723. var vertexParts = vertex.split( '/' );
  39724. faceVertices.push( vertexParts );
  39725. }
  39726. }
  39727. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  39728. var v1 = faceVertices[ 0 ];
  39729. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  39730. var v2 = faceVertices[ j ];
  39731. var v3 = faceVertices[ j + 1 ];
  39732. state.addFace(
  39733. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  39734. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  39735. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  39736. );
  39737. }
  39738. } else if ( lineFirstChar === 'l' ) {
  39739. var lineParts = line.substring( 1 ).trim().split( " " );
  39740. var lineVertices = [], lineUVs = [];
  39741. if ( line.indexOf( "/" ) === - 1 ) {
  39742. lineVertices = lineParts;
  39743. } else {
  39744. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  39745. var parts = lineParts[ li ].split( "/" );
  39746. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  39747. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  39748. }
  39749. }
  39750. state.addLineGeometry( lineVertices, lineUVs );
  39751. } else if ( lineFirstChar === 'p' ) {
  39752. var lineData = line.substr( 1 ).trim();
  39753. var pointData = lineData.split( " " );
  39754. state.addPointGeometry( pointData );
  39755. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  39756. // o object_name
  39757. // or
  39758. // g group_name
  39759. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  39760. // var name = result[ 0 ].substr( 1 ).trim();
  39761. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  39762. state.startObject( name );
  39763. } else if ( material_use_pattern.test( line ) ) {
  39764. // material
  39765. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  39766. } else if ( material_library_pattern.test( line ) ) {
  39767. // mtl file
  39768. state.materialLibraries.push( line.substring( 7 ).trim() );
  39769. } else if ( map_use_pattern.test( line ) ) {
  39770. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  39771. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  39772. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  39773. } else if ( lineFirstChar === 's' ) {
  39774. result = line.split( ' ' );
  39775. // smooth shading
  39776. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  39777. // but does not define a usemtl for each face set.
  39778. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  39779. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  39780. // where explicit usemtl defines geometry groups.
  39781. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  39782. /*
  39783. * http://paulbourke.net/dataformats/obj/
  39784. * or
  39785. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  39786. *
  39787. * From chapter "Grouping" Syntax explanation "s group_number":
  39788. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  39789. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  39790. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  39791. * than 0."
  39792. */
  39793. if ( result.length > 1 ) {
  39794. var value = result[ 1 ].trim().toLowerCase();
  39795. state.object.smooth = ( value !== '0' && value !== 'off' );
  39796. } else {
  39797. // ZBrush can produce "s" lines #11707
  39798. state.object.smooth = true;
  39799. }
  39800. var material = state.object.currentMaterial();
  39801. if ( material ) material.smooth = state.object.smooth;
  39802. } else {
  39803. // Handle null terminated files without exception
  39804. if ( line === '\0' ) continue;
  39805. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  39806. }
  39807. }
  39808. state.finalize();
  39809. var container = new THREE.Group();
  39810. container.materialLibraries = [].concat( state.materialLibraries );
  39811. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  39812. var object = state.objects[ i ];
  39813. var geometry = object.geometry;
  39814. var materials = object.materials;
  39815. var isLine = ( geometry.type === 'Line' );
  39816. var isPoints = ( geometry.type === 'Points' );
  39817. var hasVertexColors = false;
  39818. // Skip o/g line declarations that did not follow with any faces
  39819. if ( geometry.vertices.length === 0 ) continue;
  39820. var buffergeometry = new THREE.BufferGeometry();
  39821. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  39822. if ( geometry.hasNormalIndices === true ) {
  39823. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  39824. }
  39825. if ( geometry.colors.length > 0 ) {
  39826. hasVertexColors = true;
  39827. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  39828. }
  39829. if ( geometry.hasUVIndices === true ) {
  39830. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  39831. }
  39832. // Create materials
  39833. var createdMaterials = [];
  39834. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39835. var sourceMaterial = materials[ mi ];
  39836. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  39837. var material = state.materials[ materialHash ];
  39838. if ( this.materials !== null ) {
  39839. material = this.materials.create( sourceMaterial.name );
  39840. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  39841. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  39842. var materialLine = new THREE.LineBasicMaterial();
  39843. THREE.Material.prototype.copy.call( materialLine, material );
  39844. materialLine.color.copy( material.color );
  39845. material = materialLine;
  39846. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  39847. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  39848. THREE.Material.prototype.copy.call( materialPoints, material );
  39849. materialPoints.color.copy( material.color );
  39850. materialPoints.map = material.map;
  39851. material = materialPoints;
  39852. }
  39853. }
  39854. if ( material === undefined ) {
  39855. if ( isLine ) {
  39856. material = new THREE.LineBasicMaterial();
  39857. } else if ( isPoints ) {
  39858. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  39859. } else {
  39860. material = new THREE.MeshPhongMaterial();
  39861. }
  39862. material.name = sourceMaterial.name;
  39863. material.flatShading = sourceMaterial.smooth ? false : true;
  39864. material.vertexColors = hasVertexColors;
  39865. state.materials[ materialHash ] = material;
  39866. }
  39867. createdMaterials.push( material );
  39868. }
  39869. // Create mesh
  39870. var mesh;
  39871. if ( createdMaterials.length > 1 ) {
  39872. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39873. var sourceMaterial = materials[ mi ];
  39874. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  39875. }
  39876. if ( isLine ) {
  39877. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  39878. } else if ( isPoints ) {
  39879. mesh = new THREE.Points( buffergeometry, createdMaterials );
  39880. } else {
  39881. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  39882. }
  39883. } else {
  39884. if ( isLine ) {
  39885. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  39886. } else if ( isPoints ) {
  39887. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  39888. } else {
  39889. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  39890. }
  39891. }
  39892. mesh.name = object.name;
  39893. container.add( mesh );
  39894. }
  39895. return container;
  39896. }
  39897. } );
  39898. return OBJLoader;
  39899. } )();
  39900. },{}],62:[function(_dereq_,module,exports){
  39901. var createLayout = _dereq_('layout-bmfont-text')
  39902. var inherits = _dereq_('inherits')
  39903. var createIndices = _dereq_('quad-indices')
  39904. var buffer = _dereq_('three-buffer-vertex-data')
  39905. var assign = _dereq_('object-assign')
  39906. var vertices = _dereq_('./lib/vertices')
  39907. var utils = _dereq_('./lib/utils')
  39908. var Base = THREE.BufferGeometry
  39909. module.exports = function createTextGeometry (opt) {
  39910. return new TextGeometry(opt)
  39911. }
  39912. function TextGeometry (opt) {
  39913. Base.call(this)
  39914. if (typeof opt === 'string') {
  39915. opt = { text: opt }
  39916. }
  39917. // use these as default values for any subsequent
  39918. // calls to update()
  39919. this._opt = assign({}, opt)
  39920. // also do an initial setup...
  39921. if (opt) this.update(opt)
  39922. }
  39923. inherits(TextGeometry, Base)
  39924. TextGeometry.prototype.update = function (opt) {
  39925. if (typeof opt === 'string') {
  39926. opt = { text: opt }
  39927. }
  39928. // use constructor defaults
  39929. opt = assign({}, this._opt, opt)
  39930. if (!opt.font) {
  39931. throw new TypeError('must specify a { font } in options')
  39932. }
  39933. this.layout = createLayout(opt)
  39934. // get vec2 texcoords
  39935. var flipY = opt.flipY !== false
  39936. // the desired BMFont data
  39937. var font = opt.font
  39938. // determine texture size from font file
  39939. var texWidth = font.common.scaleW
  39940. var texHeight = font.common.scaleH
  39941. // get visible glyphs
  39942. var glyphs = this.layout.glyphs.filter(function (glyph) {
  39943. var bitmap = glyph.data
  39944. return bitmap.width * bitmap.height > 0
  39945. })
  39946. // provide visible glyphs for convenience
  39947. this.visibleGlyphs = glyphs
  39948. // get common vertex data
  39949. var positions = vertices.positions(glyphs)
  39950. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  39951. var indices = createIndices({
  39952. clockwise: true,
  39953. type: 'uint16',
  39954. count: glyphs.length
  39955. })
  39956. // update vertex data
  39957. buffer.index(this, indices, 1, 'uint16')
  39958. buffer.attr(this, 'position', positions, 2)
  39959. buffer.attr(this, 'uv', uvs, 2)
  39960. // update multipage data
  39961. if (!opt.multipage && 'page' in this.attributes) {
  39962. // disable multipage rendering
  39963. this.removeAttribute('page')
  39964. } else if (opt.multipage) {
  39965. var pages = vertices.pages(glyphs)
  39966. // enable multipage rendering
  39967. buffer.attr(this, 'page', pages, 1)
  39968. }
  39969. }
  39970. TextGeometry.prototype.computeBoundingSphere = function () {
  39971. if (this.boundingSphere === null) {
  39972. this.boundingSphere = new THREE.Sphere()
  39973. }
  39974. //LIVECODING.SPACE changes!!! FIX - move to LCS codebase
  39975. if(this.attributes.position) {
  39976. var positions = this.attributes.position.array
  39977. var itemSize = this.attributes.position.itemSize
  39978. if (!positions || !itemSize || positions.length < 2) {
  39979. this.boundingSphere.radius = 0
  39980. this.boundingSphere.center.set(0, 0, 0)
  39981. return
  39982. }
  39983. utils.computeSphere(positions, this.boundingSphere)
  39984. if (isNaN(this.boundingSphere.radius)) {
  39985. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  39986. 'Computed radius is NaN. The ' +
  39987. '"position" attribute is likely to have NaN values.')
  39988. }
  39989. }
  39990. }
  39991. TextGeometry.prototype.computeBoundingBox = function () {
  39992. if (this.boundingBox === null) {
  39993. this.boundingBox = new THREE.Box3()
  39994. }
  39995. var bbox = this.boundingBox
  39996. var positions = this.attributes.position.array
  39997. var itemSize = this.attributes.position.itemSize
  39998. if (!positions || !itemSize || positions.length < 2) {
  39999. bbox.makeEmpty()
  40000. return
  40001. }
  40002. utils.computeBox(positions, bbox)
  40003. }
  40004. },{"./lib/utils":63,"./lib/vertices":64,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":65}],63:[function(_dereq_,module,exports){
  40005. var itemSize = 2
  40006. var box = { min: [0, 0], max: [0, 0] }
  40007. function bounds (positions) {
  40008. var count = positions.length / itemSize
  40009. box.min[0] = positions[0]
  40010. box.min[1] = positions[1]
  40011. box.max[0] = positions[0]
  40012. box.max[1] = positions[1]
  40013. for (var i = 0; i < count; i++) {
  40014. var x = positions[i * itemSize + 0]
  40015. var y = positions[i * itemSize + 1]
  40016. box.min[0] = Math.min(x, box.min[0])
  40017. box.min[1] = Math.min(y, box.min[1])
  40018. box.max[0] = Math.max(x, box.max[0])
  40019. box.max[1] = Math.max(y, box.max[1])
  40020. }
  40021. }
  40022. module.exports.computeBox = function (positions, output) {
  40023. bounds(positions)
  40024. output.min.set(box.min[0], box.min[1], 0)
  40025. output.max.set(box.max[0], box.max[1], 0)
  40026. }
  40027. module.exports.computeSphere = function (positions, output) {
  40028. bounds(positions)
  40029. var minX = box.min[0]
  40030. var minY = box.min[1]
  40031. var maxX = box.max[0]
  40032. var maxY = box.max[1]
  40033. var width = maxX - minX
  40034. var height = maxY - minY
  40035. var length = Math.sqrt(width * width + height * height)
  40036. output.center.set(minX + width / 2, minY + height / 2, 0)
  40037. output.radius = length / 2
  40038. }
  40039. },{}],64:[function(_dereq_,module,exports){
  40040. module.exports.pages = function pages (glyphs) {
  40041. var pages = new Float32Array(glyphs.length * 4 * 1)
  40042. var i = 0
  40043. glyphs.forEach(function (glyph) {
  40044. var id = glyph.data.page || 0
  40045. pages[i++] = id
  40046. pages[i++] = id
  40047. pages[i++] = id
  40048. pages[i++] = id
  40049. })
  40050. return pages
  40051. }
  40052. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  40053. var uvs = new Float32Array(glyphs.length * 4 * 2)
  40054. var i = 0
  40055. glyphs.forEach(function (glyph) {
  40056. var bitmap = glyph.data
  40057. var bw = (bitmap.x + bitmap.width)
  40058. var bh = (bitmap.y + bitmap.height)
  40059. // top left position
  40060. var u0 = bitmap.x / texWidth
  40061. var v1 = bitmap.y / texHeight
  40062. var u1 = bw / texWidth
  40063. var v0 = bh / texHeight
  40064. if (flipY) {
  40065. v1 = (texHeight - bitmap.y) / texHeight
  40066. v0 = (texHeight - bh) / texHeight
  40067. }
  40068. // BL
  40069. uvs[i++] = u0
  40070. uvs[i++] = v1
  40071. // TL
  40072. uvs[i++] = u0
  40073. uvs[i++] = v0
  40074. // TR
  40075. uvs[i++] = u1
  40076. uvs[i++] = v0
  40077. // BR
  40078. uvs[i++] = u1
  40079. uvs[i++] = v1
  40080. })
  40081. return uvs
  40082. }
  40083. module.exports.positions = function positions (glyphs) {
  40084. var positions = new Float32Array(glyphs.length * 4 * 2)
  40085. var i = 0
  40086. glyphs.forEach(function (glyph) {
  40087. var bitmap = glyph.data
  40088. // bottom left position
  40089. var x = glyph.position[0] + bitmap.xoffset
  40090. var y = glyph.position[1] + bitmap.yoffset
  40091. // quad size
  40092. var w = bitmap.width
  40093. var h = bitmap.height
  40094. // BL
  40095. positions[i++] = x
  40096. positions[i++] = y
  40097. // TL
  40098. positions[i++] = x
  40099. positions[i++] = y + h
  40100. // TR
  40101. positions[i++] = x + w
  40102. positions[i++] = y + h
  40103. // BR
  40104. positions[i++] = x + w
  40105. positions[i++] = y
  40106. })
  40107. return positions
  40108. }
  40109. },{}],65:[function(_dereq_,module,exports){
  40110. var flatten = _dereq_('flatten-vertex-data')
  40111. var warned = false;
  40112. module.exports.attr = setAttribute
  40113. module.exports.index = setIndex
  40114. function setIndex (geometry, data, itemSize, dtype) {
  40115. if (typeof itemSize !== 'number') itemSize = 1
  40116. if (typeof dtype !== 'string') dtype = 'uint16'
  40117. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  40118. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  40119. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  40120. if (newAttrib) {
  40121. if (isR69) geometry.addAttribute('index', newAttrib)
  40122. else geometry.index = newAttrib
  40123. }
  40124. }
  40125. function setAttribute (geometry, key, data, itemSize, dtype) {
  40126. if (typeof itemSize !== 'number') itemSize = 3
  40127. if (typeof dtype !== 'string') dtype = 'float32'
  40128. if (Array.isArray(data) &&
  40129. Array.isArray(data[0]) &&
  40130. data[0].length !== itemSize) {
  40131. throw new Error('Nested vertex array has unexpected size; expected ' +
  40132. itemSize + ' but found ' + data[0].length)
  40133. }
  40134. var attrib = geometry.getAttribute(key)
  40135. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  40136. geometry.setAttribute(key, newAttrib)
  40137. }
  40138. function updateAttribute (attrib, data, itemSize, dtype) {
  40139. data = data || []
  40140. // create a new array with desired type
  40141. data = flatten(data, dtype)
  40142. attrib = new THREE.BufferAttribute(data, itemSize);
  40143. attrib.itemSize = itemSize;
  40144. attrib.needsUpdate = true;
  40145. return attrib
  40146. }
  40147. // Test whether the attribute needs to be re-created,
  40148. // returns false if we can re-use it as-is.
  40149. function rebuildAttribute (attrib, data, itemSize) {
  40150. if (attrib.itemSize !== itemSize) return true
  40151. if (!attrib.array) return true
  40152. var attribLength = attrib.array.length
  40153. if (Array.isArray(data) && Array.isArray(data[0])) {
  40154. // [ [ x, y, z ] ]
  40155. return attribLength !== data.length * itemSize
  40156. } else {
  40157. // [ x, y, z ]
  40158. return attribLength !== data.length
  40159. }
  40160. return false
  40161. }
  40162. },{"flatten-vertex-data":23}],66:[function(_dereq_,module,exports){
  40163. (function (setImmediate,clearImmediate){
  40164. var nextTick = _dereq_('process/browser.js').nextTick;
  40165. var apply = Function.prototype.apply;
  40166. var slice = Array.prototype.slice;
  40167. var immediateIds = {};
  40168. var nextImmediateId = 0;
  40169. // DOM APIs, for completeness
  40170. exports.setTimeout = function() {
  40171. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  40172. };
  40173. exports.setInterval = function() {
  40174. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  40175. };
  40176. exports.clearTimeout =
  40177. exports.clearInterval = function(timeout) { timeout.close(); };
  40178. function Timeout(id, clearFn) {
  40179. this._id = id;
  40180. this._clearFn = clearFn;
  40181. }
  40182. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  40183. Timeout.prototype.close = function() {
  40184. this._clearFn.call(window, this._id);
  40185. };
  40186. // Does not start the time, just sets up the members needed.
  40187. exports.enroll = function(item, msecs) {
  40188. clearTimeout(item._idleTimeoutId);
  40189. item._idleTimeout = msecs;
  40190. };
  40191. exports.unenroll = function(item) {
  40192. clearTimeout(item._idleTimeoutId);
  40193. item._idleTimeout = -1;
  40194. };
  40195. exports._unrefActive = exports.active = function(item) {
  40196. clearTimeout(item._idleTimeoutId);
  40197. var msecs = item._idleTimeout;
  40198. if (msecs >= 0) {
  40199. item._idleTimeoutId = setTimeout(function onTimeout() {
  40200. if (item._onTimeout)
  40201. item._onTimeout();
  40202. }, msecs);
  40203. }
  40204. };
  40205. // That's not how node.js implements it but the exposed api is the same.
  40206. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  40207. var id = nextImmediateId++;
  40208. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  40209. immediateIds[id] = true;
  40210. nextTick(function onNextTick() {
  40211. if (immediateIds[id]) {
  40212. // fn.call() is faster so we optimize for the common use-case
  40213. // @see http://jsperf.com/call-apply-segu
  40214. if (args) {
  40215. fn.apply(null, args);
  40216. } else {
  40217. fn.call(null);
  40218. }
  40219. // Prevent ids from leaking
  40220. exports.clearImmediate(id);
  40221. }
  40222. });
  40223. return id;
  40224. };
  40225. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  40226. delete immediateIds[id];
  40227. };
  40228. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  40229. },{"process/browser.js":49,"timers":66}],67:[function(_dereq_,module,exports){
  40230. (function (global){
  40231. /**
  40232. * @license
  40233. * webvr-polyfill
  40234. * Copyright (c) 2015-2017 Google
  40235. * Licensed under the Apache License, Version 2.0 (the "License");
  40236. * you may not use this file except in compliance with the License.
  40237. * You may obtain a copy of the License at
  40238. *
  40239. * http://www.apache.org/licenses/LICENSE-2.0
  40240. *
  40241. * Unless required by applicable law or agreed to in writing, software
  40242. * distributed under the License is distributed on an "AS IS" BASIS,
  40243. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40244. * See the License for the specific language governing permissions and
  40245. * limitations under the License.
  40246. */
  40247. /**
  40248. * @license
  40249. * cardboard-vr-display
  40250. * Copyright (c) 2015-2017 Google
  40251. * Licensed under the Apache License, Version 2.0 (the "License");
  40252. * you may not use this file except in compliance with the License.
  40253. * You may obtain a copy of the License at
  40254. *
  40255. * http://www.apache.org/licenses/LICENSE-2.0
  40256. *
  40257. * Unless required by applicable law or agreed to in writing, software
  40258. * distributed under the License is distributed on an "AS IS" BASIS,
  40259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40260. * See the License for the specific language governing permissions and
  40261. * limitations under the License.
  40262. */
  40263. /**
  40264. * @license
  40265. * webvr-polyfill-dpdb
  40266. * Copyright (c) 2017 Google
  40267. * Licensed under the Apache License, Version 2.0 (the "License");
  40268. * you may not use this file except in compliance with the License.
  40269. * You may obtain a copy of the License at
  40270. *
  40271. * http://www.apache.org/licenses/LICENSE-2.0
  40272. *
  40273. * Unless required by applicable law or agreed to in writing, software
  40274. * distributed under the License is distributed on an "AS IS" BASIS,
  40275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40276. * See the License for the specific language governing permissions and
  40277. * limitations under the License.
  40278. */
  40279. /**
  40280. * @license
  40281. * wglu-preserve-state
  40282. * Copyright (c) 2016, Brandon Jones.
  40283. *
  40284. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40285. * of this software and associated documentation files (the "Software"), to deal
  40286. * in the Software without restriction, including without limitation the rights
  40287. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40288. * copies of the Software, and to permit persons to whom the Software is
  40289. * furnished to do so, subject to the following conditions:
  40290. *
  40291. * The above copyright notice and this permission notice shall be included in
  40292. * all copies or substantial portions of the Software.
  40293. *
  40294. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40295. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40296. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40297. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40298. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40299. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40300. * THE SOFTWARE.
  40301. */
  40302. /**
  40303. * @license
  40304. * nosleep.js
  40305. * Copyright (c) 2017, Rich Tibbett
  40306. *
  40307. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40308. * of this software and associated documentation files (the "Software"), to deal
  40309. * in the Software without restriction, including without limitation the rights
  40310. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40311. * copies of the Software, and to permit persons to whom the Software is
  40312. * furnished to do so, subject to the following conditions:
  40313. *
  40314. * The above copyright notice and this permission notice shall be included in
  40315. * all copies or substantial portions of the Software.
  40316. *
  40317. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40318. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40319. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40320. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40321. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40322. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40323. * THE SOFTWARE.
  40324. */
  40325. (function (global, factory) {
  40326. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  40327. typeof define === 'function' && define.amd ? define(factory) :
  40328. (global.WebVRPolyfill = factory());
  40329. }(this, (function () { 'use strict';
  40330. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  40331. function unwrapExports (x) {
  40332. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  40333. }
  40334. function createCommonjsModule(fn, module) {
  40335. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40336. }
  40337. var isMobile = function isMobile() {
  40338. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  40339. );
  40340. };
  40341. var copyArray = function copyArray(source, dest) {
  40342. for (var i = 0, n = source.length; i < n; i++) {
  40343. dest[i] = source[i];
  40344. }
  40345. };
  40346. var extend = function extend(dest, src) {
  40347. for (var key in src) {
  40348. if (src.hasOwnProperty(key)) {
  40349. dest[key] = src[key];
  40350. }
  40351. }
  40352. return dest;
  40353. };
  40354. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  40355. /**
  40356. * @license
  40357. * cardboard-vr-display
  40358. * Copyright (c) 2015-2017 Google
  40359. * Licensed under the Apache License, Version 2.0 (the "License");
  40360. * you may not use this file except in compliance with the License.
  40361. * You may obtain a copy of the License at
  40362. *
  40363. * http://www.apache.org/licenses/LICENSE-2.0
  40364. *
  40365. * Unless required by applicable law or agreed to in writing, software
  40366. * distributed under the License is distributed on an "AS IS" BASIS,
  40367. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40368. * See the License for the specific language governing permissions and
  40369. * limitations under the License.
  40370. */
  40371. /**
  40372. * @license
  40373. * gl-preserve-state
  40374. * Copyright (c) 2016, Brandon Jones.
  40375. *
  40376. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40377. * of this software and associated documentation files (the "Software"), to deal
  40378. * in the Software without restriction, including without limitation the rights
  40379. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40380. * copies of the Software, and to permit persons to whom the Software is
  40381. * furnished to do so, subject to the following conditions:
  40382. *
  40383. * The above copyright notice and this permission notice shall be included in
  40384. * all copies or substantial portions of the Software.
  40385. *
  40386. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40387. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40388. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40389. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40390. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40391. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40392. * THE SOFTWARE.
  40393. */
  40394. /**
  40395. * @license
  40396. * webvr-polyfill-dpdb
  40397. * Copyright (c) 2015-2017 Google
  40398. * Licensed under the Apache License, Version 2.0 (the "License");
  40399. * you may not use this file except in compliance with the License.
  40400. * You may obtain a copy of the License at
  40401. *
  40402. * http://www.apache.org/licenses/LICENSE-2.0
  40403. *
  40404. * Unless required by applicable law or agreed to in writing, software
  40405. * distributed under the License is distributed on an "AS IS" BASIS,
  40406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40407. * See the License for the specific language governing permissions and
  40408. * limitations under the License.
  40409. */
  40410. /**
  40411. * @license
  40412. * nosleep.js
  40413. * Copyright (c) 2017, Rich Tibbett
  40414. *
  40415. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40416. * of this software and associated documentation files (the "Software"), to deal
  40417. * in the Software without restriction, including without limitation the rights
  40418. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40419. * copies of the Software, and to permit persons to whom the Software is
  40420. * furnished to do so, subject to the following conditions:
  40421. *
  40422. * The above copyright notice and this permission notice shall be included in
  40423. * all copies or substantial portions of the Software.
  40424. *
  40425. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40426. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40427. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40428. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40429. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40430. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40431. * THE SOFTWARE.
  40432. */
  40433. (function (global, factory) {
  40434. module.exports = factory();
  40435. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  40436. if (!(instance instanceof Constructor)) {
  40437. throw new TypeError("Cannot call a class as a function");
  40438. }
  40439. };
  40440. var createClass = function () {
  40441. function defineProperties(target, props) {
  40442. for (var i = 0; i < props.length; i++) {
  40443. var descriptor = props[i];
  40444. descriptor.enumerable = descriptor.enumerable || false;
  40445. descriptor.configurable = true;
  40446. if ("value" in descriptor) descriptor.writable = true;
  40447. Object.defineProperty(target, descriptor.key, descriptor);
  40448. }
  40449. }
  40450. return function (Constructor, protoProps, staticProps) {
  40451. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  40452. if (staticProps) defineProperties(Constructor, staticProps);
  40453. return Constructor;
  40454. };
  40455. }();
  40456. var slicedToArray = function () {
  40457. function sliceIterator(arr, i) {
  40458. var _arr = [];
  40459. var _n = true;
  40460. var _d = false;
  40461. var _e = undefined;
  40462. try {
  40463. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  40464. _arr.push(_s.value);
  40465. if (i && _arr.length === i) break;
  40466. }
  40467. } catch (err) {
  40468. _d = true;
  40469. _e = err;
  40470. } finally {
  40471. try {
  40472. if (!_n && _i["return"]) _i["return"]();
  40473. } finally {
  40474. if (_d) throw _e;
  40475. }
  40476. }
  40477. return _arr;
  40478. }
  40479. return function (arr, i) {
  40480. if (Array.isArray(arr)) {
  40481. return arr;
  40482. } else if (Symbol.iterator in Object(arr)) {
  40483. return sliceIterator(arr, i);
  40484. } else {
  40485. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  40486. }
  40487. };
  40488. }();
  40489. var MIN_TIMESTEP = 0.001;
  40490. var MAX_TIMESTEP = 1;
  40491. var dataUri = function dataUri(mimeType, svg) {
  40492. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  40493. };
  40494. var lerp = function lerp(a, b, t) {
  40495. return a + (b - a) * t;
  40496. };
  40497. var isIOS = function () {
  40498. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  40499. return function () {
  40500. return isIOS;
  40501. };
  40502. }();
  40503. var isWebViewAndroid = function () {
  40504. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  40505. return function () {
  40506. return isWebViewAndroid;
  40507. };
  40508. }();
  40509. var isSafari = function () {
  40510. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  40511. return function () {
  40512. return isSafari;
  40513. };
  40514. }();
  40515. var isFirefoxAndroid = function () {
  40516. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  40517. return function () {
  40518. return isFirefoxAndroid;
  40519. };
  40520. }();
  40521. var getChromeVersion = function () {
  40522. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  40523. var value = match ? parseInt(match[1], 10) : null;
  40524. return function () {
  40525. return value;
  40526. };
  40527. }();
  40528. var isSafariWithoutDeviceMotion = function () {
  40529. var value = false;
  40530. value = isIOS() && isSafari() && navigator.userAgent.indexOf('13_4') !== -1;
  40531. return function () {
  40532. return value;
  40533. };
  40534. }();
  40535. var isChromeWithoutDeviceMotion = function () {
  40536. var value = false;
  40537. if (getChromeVersion() === 65) {
  40538. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  40539. if (match) {
  40540. var _match$1$split = match[1].split('.'),
  40541. _match$1$split2 = slicedToArray(_match$1$split, 4),
  40542. major = _match$1$split2[0],
  40543. minor = _match$1$split2[1],
  40544. branch = _match$1$split2[2],
  40545. build = _match$1$split2[3];
  40546. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  40547. }
  40548. }
  40549. return function () {
  40550. return value;
  40551. };
  40552. }();
  40553. var isR7 = function () {
  40554. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  40555. return function () {
  40556. return isR7;
  40557. };
  40558. }();
  40559. var isLandscapeMode = function isLandscapeMode() {
  40560. var rtn = window.orientation == 90 || window.orientation == -90;
  40561. return isR7() ? !rtn : rtn;
  40562. };
  40563. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  40564. if (isNaN(timestampDeltaS)) {
  40565. return false;
  40566. }
  40567. if (timestampDeltaS <= MIN_TIMESTEP) {
  40568. return false;
  40569. }
  40570. if (timestampDeltaS > MAX_TIMESTEP) {
  40571. return false;
  40572. }
  40573. return true;
  40574. };
  40575. var getScreenWidth = function getScreenWidth() {
  40576. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40577. };
  40578. var getScreenHeight = function getScreenHeight() {
  40579. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40580. };
  40581. var requestFullscreen = function requestFullscreen(element) {
  40582. if (isWebViewAndroid()) {
  40583. return false;
  40584. }
  40585. if (element.requestFullscreen) {
  40586. element.requestFullscreen();
  40587. } else if (element.webkitRequestFullscreen) {
  40588. element.webkitRequestFullscreen();
  40589. } else if (element.mozRequestFullScreen) {
  40590. element.mozRequestFullScreen();
  40591. } else if (element.msRequestFullscreen) {
  40592. element.msRequestFullscreen();
  40593. } else {
  40594. return false;
  40595. }
  40596. return true;
  40597. };
  40598. var exitFullscreen = function exitFullscreen() {
  40599. if (document.exitFullscreen) {
  40600. document.exitFullscreen();
  40601. } else if (document.webkitExitFullscreen) {
  40602. document.webkitExitFullscreen();
  40603. } else if (document.mozCancelFullScreen) {
  40604. document.mozCancelFullScreen();
  40605. } else if (document.msExitFullscreen) {
  40606. document.msExitFullscreen();
  40607. } else {
  40608. return false;
  40609. }
  40610. return true;
  40611. };
  40612. var getFullscreenElement = function getFullscreenElement() {
  40613. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  40614. };
  40615. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  40616. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  40617. gl.shaderSource(vertexShader, vertexSource);
  40618. gl.compileShader(vertexShader);
  40619. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  40620. gl.shaderSource(fragmentShader, fragmentSource);
  40621. gl.compileShader(fragmentShader);
  40622. var program = gl.createProgram();
  40623. gl.attachShader(program, vertexShader);
  40624. gl.attachShader(program, fragmentShader);
  40625. for (var attribName in attribLocationMap) {
  40626. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  40627. }gl.linkProgram(program);
  40628. gl.deleteShader(vertexShader);
  40629. gl.deleteShader(fragmentShader);
  40630. return program;
  40631. };
  40632. var getProgramUniforms = function getProgramUniforms(gl, program) {
  40633. var uniforms = {};
  40634. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  40635. var uniformName = '';
  40636. for (var i = 0; i < uniformCount; i++) {
  40637. var uniformInfo = gl.getActiveUniform(program, i);
  40638. uniformName = uniformInfo.name.replace('[0]', '');
  40639. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  40640. }
  40641. return uniforms;
  40642. };
  40643. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  40644. var lr = 1 / (left - right),
  40645. bt = 1 / (bottom - top),
  40646. nf = 1 / (near - far);
  40647. out[0] = -2 * lr;
  40648. out[1] = 0;
  40649. out[2] = 0;
  40650. out[3] = 0;
  40651. out[4] = 0;
  40652. out[5] = -2 * bt;
  40653. out[6] = 0;
  40654. out[7] = 0;
  40655. out[8] = 0;
  40656. out[9] = 0;
  40657. out[10] = 2 * nf;
  40658. out[11] = 0;
  40659. out[12] = (left + right) * lr;
  40660. out[13] = (top + bottom) * bt;
  40661. out[14] = (far + near) * nf;
  40662. out[15] = 1;
  40663. return out;
  40664. };
  40665. var isMobile = function isMobile() {
  40666. var check = false;
  40667. (function (a) {
  40668. 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;
  40669. })(navigator.userAgent || navigator.vendor || window.opera);
  40670. return check;
  40671. };
  40672. var extend = function extend(dest, src) {
  40673. for (var key in src) {
  40674. if (src.hasOwnProperty(key)) {
  40675. dest[key] = src[key];
  40676. }
  40677. }
  40678. return dest;
  40679. };
  40680. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  40681. if (isIOS()) {
  40682. var width = canvas.style.width;
  40683. var height = canvas.style.height;
  40684. canvas.style.width = parseInt(width) + 1 + 'px';
  40685. canvas.style.height = parseInt(height) + 'px';
  40686. setTimeout(function () {
  40687. canvas.style.width = width;
  40688. canvas.style.height = height;
  40689. }, 100);
  40690. }
  40691. window.canvas = canvas;
  40692. };
  40693. var frameDataFromPose = function () {
  40694. var piOver180 = Math.PI / 180.0;
  40695. var rad45 = Math.PI * 0.25;
  40696. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  40697. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  40698. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  40699. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  40700. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  40701. xScale = 2.0 / (leftTan + rightTan),
  40702. yScale = 2.0 / (upTan + downTan);
  40703. out[0] = xScale;
  40704. out[1] = 0.0;
  40705. out[2] = 0.0;
  40706. out[3] = 0.0;
  40707. out[4] = 0.0;
  40708. out[5] = yScale;
  40709. out[6] = 0.0;
  40710. out[7] = 0.0;
  40711. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  40712. out[9] = (upTan - downTan) * yScale * 0.5;
  40713. out[10] = far / (near - far);
  40714. out[11] = -1.0;
  40715. out[12] = 0.0;
  40716. out[13] = 0.0;
  40717. out[14] = far * near / (near - far);
  40718. out[15] = 0.0;
  40719. return out;
  40720. }
  40721. function mat4_fromRotationTranslation(out, q, v) {
  40722. var x = q[0],
  40723. y = q[1],
  40724. z = q[2],
  40725. w = q[3],
  40726. x2 = x + x,
  40727. y2 = y + y,
  40728. z2 = z + z,
  40729. xx = x * x2,
  40730. xy = x * y2,
  40731. xz = x * z2,
  40732. yy = y * y2,
  40733. yz = y * z2,
  40734. zz = z * z2,
  40735. wx = w * x2,
  40736. wy = w * y2,
  40737. wz = w * z2;
  40738. out[0] = 1 - (yy + zz);
  40739. out[1] = xy + wz;
  40740. out[2] = xz - wy;
  40741. out[3] = 0;
  40742. out[4] = xy - wz;
  40743. out[5] = 1 - (xx + zz);
  40744. out[6] = yz + wx;
  40745. out[7] = 0;
  40746. out[8] = xz + wy;
  40747. out[9] = yz - wx;
  40748. out[10] = 1 - (xx + yy);
  40749. out[11] = 0;
  40750. out[12] = v[0];
  40751. out[13] = v[1];
  40752. out[14] = v[2];
  40753. out[15] = 1;
  40754. return out;
  40755. }
  40756. function mat4_translate(out, a, v) {
  40757. var x = v[0],
  40758. y = v[1],
  40759. z = v[2],
  40760. a00,
  40761. a01,
  40762. a02,
  40763. a03,
  40764. a10,
  40765. a11,
  40766. a12,
  40767. a13,
  40768. a20,
  40769. a21,
  40770. a22,
  40771. a23;
  40772. if (a === out) {
  40773. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  40774. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  40775. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  40776. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  40777. } else {
  40778. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  40779. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  40780. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  40781. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  40782. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  40783. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  40784. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  40785. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  40786. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  40787. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  40788. }
  40789. return out;
  40790. }
  40791. function mat4_invert(out, a) {
  40792. var a00 = a[0],
  40793. a01 = a[1],
  40794. a02 = a[2],
  40795. a03 = a[3],
  40796. a10 = a[4],
  40797. a11 = a[5],
  40798. a12 = a[6],
  40799. a13 = a[7],
  40800. a20 = a[8],
  40801. a21 = a[9],
  40802. a22 = a[10],
  40803. a23 = a[11],
  40804. a30 = a[12],
  40805. a31 = a[13],
  40806. a32 = a[14],
  40807. a33 = a[15],
  40808. b00 = a00 * a11 - a01 * a10,
  40809. b01 = a00 * a12 - a02 * a10,
  40810. b02 = a00 * a13 - a03 * a10,
  40811. b03 = a01 * a12 - a02 * a11,
  40812. b04 = a01 * a13 - a03 * a11,
  40813. b05 = a02 * a13 - a03 * a12,
  40814. b06 = a20 * a31 - a21 * a30,
  40815. b07 = a20 * a32 - a22 * a30,
  40816. b08 = a20 * a33 - a23 * a30,
  40817. b09 = a21 * a32 - a22 * a31,
  40818. b10 = a21 * a33 - a23 * a31,
  40819. b11 = a22 * a33 - a23 * a32,
  40820. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  40821. if (!det) {
  40822. return null;
  40823. }
  40824. det = 1.0 / det;
  40825. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  40826. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  40827. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  40828. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  40829. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  40830. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  40831. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  40832. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  40833. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  40834. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  40835. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  40836. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  40837. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  40838. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  40839. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  40840. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  40841. return out;
  40842. }
  40843. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  40844. var defaultPosition = new Float32Array([0, 0, 0]);
  40845. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  40846. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  40847. var orientation = pose.orientation || defaultOrientation;
  40848. var position = pose.position || defaultPosition;
  40849. mat4_fromRotationTranslation(view, orientation, position);
  40850. if (offset) mat4_translate(view, view, offset);
  40851. mat4_invert(view, view);
  40852. }
  40853. return function (frameData, pose, vrDisplay) {
  40854. if (!frameData || !pose) return false;
  40855. frameData.pose = pose;
  40856. frameData.timestamp = pose.timestamp;
  40857. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  40858. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  40859. return true;
  40860. };
  40861. }();
  40862. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  40863. var isFramed = window.self !== window.top;
  40864. var refOrigin = getOriginFromUrl(document.referrer);
  40865. var thisOrigin = getOriginFromUrl(window.location.href);
  40866. return isFramed && refOrigin !== thisOrigin;
  40867. };
  40868. var getOriginFromUrl = function getOriginFromUrl(url) {
  40869. var domainIdx;
  40870. var protoSepIdx = url.indexOf("://");
  40871. if (protoSepIdx !== -1) {
  40872. domainIdx = protoSepIdx + 3;
  40873. } else {
  40874. domainIdx = 0;
  40875. }
  40876. var domainEndIdx = url.indexOf('/', domainIdx);
  40877. if (domainEndIdx === -1) {
  40878. domainEndIdx = url.length;
  40879. }
  40880. return url.substring(0, domainEndIdx);
  40881. };
  40882. var getQuaternionAngle = function getQuaternionAngle(quat) {
  40883. if (quat.w > 1) {
  40884. console.warn('getQuaternionAngle: w > 1');
  40885. return 0;
  40886. }
  40887. var angle = 2 * Math.acos(quat.w);
  40888. return angle;
  40889. };
  40890. var warnOnce = function () {
  40891. var observedWarnings = {};
  40892. return function (key, message) {
  40893. if (observedWarnings[key] === undefined) {
  40894. console.warn('webvr-polyfill: ' + message);
  40895. observedWarnings[key] = true;
  40896. }
  40897. };
  40898. }();
  40899. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  40900. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  40901. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  40902. };
  40903. function WGLUPreserveGLState(gl, bindings, callback) {
  40904. if (!bindings) {
  40905. callback(gl);
  40906. return;
  40907. }
  40908. var boundValues = [];
  40909. var activeTexture = null;
  40910. for (var i = 0; i < bindings.length; ++i) {
  40911. var binding = bindings[i];
  40912. switch (binding) {
  40913. case gl.TEXTURE_BINDING_2D:
  40914. case gl.TEXTURE_BINDING_CUBE_MAP:
  40915. var textureUnit = bindings[++i];
  40916. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  40917. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  40918. boundValues.push(null, null);
  40919. break;
  40920. }
  40921. if (!activeTexture) {
  40922. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40923. }
  40924. gl.activeTexture(textureUnit);
  40925. boundValues.push(gl.getParameter(binding), null);
  40926. break;
  40927. case gl.ACTIVE_TEXTURE:
  40928. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40929. boundValues.push(null);
  40930. break;
  40931. default:
  40932. boundValues.push(gl.getParameter(binding));
  40933. break;
  40934. }
  40935. }
  40936. callback(gl);
  40937. for (var i = 0; i < bindings.length; ++i) {
  40938. var binding = bindings[i];
  40939. var boundValue = boundValues[i];
  40940. switch (binding) {
  40941. case gl.ACTIVE_TEXTURE:
  40942. break;
  40943. case gl.ARRAY_BUFFER_BINDING:
  40944. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  40945. break;
  40946. case gl.COLOR_CLEAR_VALUE:
  40947. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40948. break;
  40949. case gl.COLOR_WRITEMASK:
  40950. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40951. break;
  40952. case gl.CURRENT_PROGRAM:
  40953. gl.useProgram(boundValue);
  40954. break;
  40955. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  40956. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  40957. break;
  40958. case gl.FRAMEBUFFER_BINDING:
  40959. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  40960. break;
  40961. case gl.RENDERBUFFER_BINDING:
  40962. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  40963. break;
  40964. case gl.TEXTURE_BINDING_2D:
  40965. var textureUnit = bindings[++i];
  40966. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40967. break;
  40968. gl.activeTexture(textureUnit);
  40969. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  40970. break;
  40971. case gl.TEXTURE_BINDING_CUBE_MAP:
  40972. var textureUnit = bindings[++i];
  40973. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40974. break;
  40975. gl.activeTexture(textureUnit);
  40976. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  40977. break;
  40978. case gl.VIEWPORT:
  40979. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40980. break;
  40981. case gl.BLEND:
  40982. case gl.CULL_FACE:
  40983. case gl.DEPTH_TEST:
  40984. case gl.SCISSOR_TEST:
  40985. case gl.STENCIL_TEST:
  40986. if (boundValue) {
  40987. gl.enable(binding);
  40988. } else {
  40989. gl.disable(binding);
  40990. }
  40991. break;
  40992. default:
  40993. console.log("No GL restore behavior for 0x" + binding.toString(16));
  40994. break;
  40995. }
  40996. if (activeTexture) {
  40997. gl.activeTexture(activeTexture);
  40998. }
  40999. }
  41000. }
  41001. var glPreserveState = WGLUPreserveGLState;
  41002. 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');
  41003. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  41004. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  41005. this.gl = gl;
  41006. this.cardboardUI = cardboardUI;
  41007. this.bufferScale = bufferScale;
  41008. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  41009. this.ctxAttribs = gl.getContextAttributes();
  41010. this.instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  41011. this.meshWidth = 20;
  41012. this.meshHeight = 20;
  41013. this.bufferWidth = gl.drawingBufferWidth;
  41014. this.bufferHeight = gl.drawingBufferHeight;
  41015. this.realBindFramebuffer = gl.bindFramebuffer;
  41016. this.realEnable = gl.enable;
  41017. this.realDisable = gl.disable;
  41018. this.realColorMask = gl.colorMask;
  41019. this.realClearColor = gl.clearColor;
  41020. this.realViewport = gl.viewport;
  41021. if (!isIOS()) {
  41022. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  41023. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  41024. }
  41025. this.isPatched = false;
  41026. this.lastBoundFramebuffer = null;
  41027. this.cullFace = false;
  41028. this.depthTest = false;
  41029. this.blend = false;
  41030. this.scissorTest = false;
  41031. this.stencilTest = false;
  41032. this.viewport = [0, 0, 0, 0];
  41033. this.colorMask = [true, true, true, true];
  41034. this.clearColor = [0, 0, 0, 0];
  41035. this.attribs = {
  41036. position: 0,
  41037. texCoord: 1
  41038. };
  41039. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  41040. this.uniforms = getProgramUniforms(gl, this.program);
  41041. this.viewportOffsetScale = new Float32Array(8);
  41042. this.setTextureBounds();
  41043. this.vertexBuffer = gl.createBuffer();
  41044. this.indexBuffer = gl.createBuffer();
  41045. this.indexCount = 0;
  41046. this.renderTarget = gl.createTexture();
  41047. this.framebuffer = gl.createFramebuffer();
  41048. this.depthStencilBuffer = null;
  41049. this.depthBuffer = null;
  41050. this.stencilBuffer = null;
  41051. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  41052. this.depthStencilBuffer = gl.createRenderbuffer();
  41053. } else if (this.ctxAttribs.depth) {
  41054. this.depthBuffer = gl.createRenderbuffer();
  41055. } else if (this.ctxAttribs.stencil) {
  41056. this.stencilBuffer = gl.createRenderbuffer();
  41057. }
  41058. this.patch();
  41059. this.onResize();
  41060. }
  41061. CardboardDistorter.prototype.destroy = function () {
  41062. var gl = this.gl;
  41063. this.unpatch();
  41064. gl.deleteProgram(this.program);
  41065. gl.deleteBuffer(this.vertexBuffer);
  41066. gl.deleteBuffer(this.indexBuffer);
  41067. gl.deleteTexture(this.renderTarget);
  41068. gl.deleteFramebuffer(this.framebuffer);
  41069. if (this.depthStencilBuffer) {
  41070. gl.deleteRenderbuffer(this.depthStencilBuffer);
  41071. }
  41072. if (this.depthBuffer) {
  41073. gl.deleteRenderbuffer(this.depthBuffer);
  41074. }
  41075. if (this.stencilBuffer) {
  41076. gl.deleteRenderbuffer(this.stencilBuffer);
  41077. }
  41078. if (this.cardboardUI) {
  41079. this.cardboardUI.destroy();
  41080. }
  41081. };
  41082. CardboardDistorter.prototype.onResize = function () {
  41083. var gl = this.gl;
  41084. var self = this;
  41085. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  41086. glPreserveState(gl, glState, function (gl) {
  41087. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  41088. if (self.scissorTest) {
  41089. self.realDisable.call(gl, gl.SCISSOR_TEST);
  41090. }
  41091. self.realColorMask.call(gl, true, true, true, true);
  41092. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41093. self.realClearColor.call(gl, 0, 0, 0, 1);
  41094. gl.clear(gl.COLOR_BUFFER_BIT);
  41095. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  41096. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  41097. 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);
  41098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  41099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  41100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  41101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  41102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  41103. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  41104. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  41105. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  41106. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  41107. } else if (self.ctxAttribs.depth) {
  41108. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  41109. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  41110. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  41111. } else if (self.ctxAttribs.stencil) {
  41112. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  41113. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  41114. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  41115. }
  41116. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  41117. console.error('Framebuffer incomplete!');
  41118. }
  41119. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  41120. if (self.scissorTest) {
  41121. self.realEnable.call(gl, gl.SCISSOR_TEST);
  41122. }
  41123. self.realColorMask.apply(gl, self.colorMask);
  41124. self.realViewport.apply(gl, self.viewport);
  41125. self.realClearColor.apply(gl, self.clearColor);
  41126. });
  41127. if (this.cardboardUI) {
  41128. this.cardboardUI.onResize();
  41129. }
  41130. };
  41131. CardboardDistorter.prototype.patch = function () {
  41132. if (this.isPatched) {
  41133. return;
  41134. }
  41135. var self = this;
  41136. var canvas = this.gl.canvas;
  41137. var gl = this.gl;
  41138. if (!isIOS()) {
  41139. canvas.width = getScreenWidth() * this.bufferScale;
  41140. canvas.height = getScreenHeight() * this.bufferScale;
  41141. Object.defineProperty(canvas, 'width', {
  41142. configurable: true,
  41143. enumerable: true,
  41144. get: function get() {
  41145. return self.bufferWidth;
  41146. },
  41147. set: function set(value) {
  41148. self.bufferWidth = value;
  41149. self.realCanvasWidth.set.call(canvas, value);
  41150. self.onResize();
  41151. }
  41152. });
  41153. Object.defineProperty(canvas, 'height', {
  41154. configurable: true,
  41155. enumerable: true,
  41156. get: function get() {
  41157. return self.bufferHeight;
  41158. },
  41159. set: function set(value) {
  41160. self.bufferHeight = value;
  41161. self.realCanvasHeight.set.call(canvas, value);
  41162. self.onResize();
  41163. }
  41164. });
  41165. }
  41166. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  41167. if (this.lastBoundFramebuffer == null) {
  41168. this.lastBoundFramebuffer = this.framebuffer;
  41169. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  41170. }
  41171. this.gl.bindFramebuffer = function (target, framebuffer) {
  41172. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  41173. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  41174. };
  41175. this.cullFace = gl.getParameter(gl.CULL_FACE);
  41176. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  41177. this.blend = gl.getParameter(gl.BLEND);
  41178. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  41179. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  41180. gl.enable = function (pname) {
  41181. switch (pname) {
  41182. case gl.CULL_FACE:
  41183. self.cullFace = true;break;
  41184. case gl.DEPTH_TEST:
  41185. self.depthTest = true;break;
  41186. case gl.BLEND:
  41187. self.blend = true;break;
  41188. case gl.SCISSOR_TEST:
  41189. self.scissorTest = true;break;
  41190. case gl.STENCIL_TEST:
  41191. self.stencilTest = true;break;
  41192. }
  41193. self.realEnable.call(gl, pname);
  41194. };
  41195. gl.disable = function (pname) {
  41196. switch (pname) {
  41197. case gl.CULL_FACE:
  41198. self.cullFace = false;break;
  41199. case gl.DEPTH_TEST:
  41200. self.depthTest = false;break;
  41201. case gl.BLEND:
  41202. self.blend = false;break;
  41203. case gl.SCISSOR_TEST:
  41204. self.scissorTest = false;break;
  41205. case gl.STENCIL_TEST:
  41206. self.stencilTest = false;break;
  41207. }
  41208. self.realDisable.call(gl, pname);
  41209. };
  41210. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  41211. gl.colorMask = function (r, g, b, a) {
  41212. self.colorMask[0] = r;
  41213. self.colorMask[1] = g;
  41214. self.colorMask[2] = b;
  41215. self.colorMask[3] = a;
  41216. self.realColorMask.call(gl, r, g, b, a);
  41217. };
  41218. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  41219. gl.clearColor = function (r, g, b, a) {
  41220. self.clearColor[0] = r;
  41221. self.clearColor[1] = g;
  41222. self.clearColor[2] = b;
  41223. self.clearColor[3] = a;
  41224. self.realClearColor.call(gl, r, g, b, a);
  41225. };
  41226. this.viewport = gl.getParameter(gl.VIEWPORT);
  41227. gl.viewport = function (x, y, w, h) {
  41228. self.viewport[0] = x;
  41229. self.viewport[1] = y;
  41230. self.viewport[2] = w;
  41231. self.viewport[3] = h;
  41232. self.realViewport.call(gl, x, y, w, h);
  41233. };
  41234. this.isPatched = true;
  41235. safariCssSizeWorkaround(canvas);
  41236. };
  41237. CardboardDistorter.prototype.unpatch = function () {
  41238. if (!this.isPatched) {
  41239. return;
  41240. }
  41241. var gl = this.gl;
  41242. var canvas = this.gl.canvas;
  41243. if (!isIOS()) {
  41244. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  41245. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  41246. }
  41247. canvas.width = this.bufferWidth;
  41248. canvas.height = this.bufferHeight;
  41249. gl.bindFramebuffer = this.realBindFramebuffer;
  41250. gl.enable = this.realEnable;
  41251. gl.disable = this.realDisable;
  41252. gl.colorMask = this.realColorMask;
  41253. gl.clearColor = this.realClearColor;
  41254. gl.viewport = this.realViewport;
  41255. if (this.lastBoundFramebuffer == this.framebuffer) {
  41256. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  41257. }
  41258. this.isPatched = false;
  41259. setTimeout(function () {
  41260. safariCssSizeWorkaround(canvas);
  41261. }, 1);
  41262. };
  41263. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  41264. if (!leftBounds) {
  41265. leftBounds = [0, 0, 0.5, 1];
  41266. }
  41267. if (!rightBounds) {
  41268. rightBounds = [0.5, 0, 0.5, 1];
  41269. }
  41270. this.viewportOffsetScale[0] = leftBounds[0];
  41271. this.viewportOffsetScale[1] = leftBounds[1];
  41272. this.viewportOffsetScale[2] = leftBounds[2];
  41273. this.viewportOffsetScale[3] = leftBounds[3];
  41274. this.viewportOffsetScale[4] = rightBounds[0];
  41275. this.viewportOffsetScale[5] = rightBounds[1];
  41276. this.viewportOffsetScale[6] = rightBounds[2];
  41277. this.viewportOffsetScale[7] = rightBounds[3];
  41278. };
  41279. CardboardDistorter.prototype.submitFrame = function () {
  41280. var gl = this.gl;
  41281. var self = this;
  41282. var glState = [];
  41283. if (!this.dirtySubmitFrameBindings) {
  41284. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  41285. }
  41286. glPreserveState(gl, glState, function (gl) {
  41287. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  41288. var positionDivisor = 0;
  41289. var texCoordDivisor = 0;
  41290. if (self.instanceExt) {
  41291. positionDivisor = gl.getVertexAttrib(self.attribs.position, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  41292. texCoordDivisor = gl.getVertexAttrib(self.attribs.texCoord, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  41293. }
  41294. if (self.cullFace) {
  41295. self.realDisable.call(gl, gl.CULL_FACE);
  41296. }
  41297. if (self.depthTest) {
  41298. self.realDisable.call(gl, gl.DEPTH_TEST);
  41299. }
  41300. if (self.blend) {
  41301. self.realDisable.call(gl, gl.BLEND);
  41302. }
  41303. if (self.scissorTest) {
  41304. self.realDisable.call(gl, gl.SCISSOR_TEST);
  41305. }
  41306. if (self.stencilTest) {
  41307. self.realDisable.call(gl, gl.STENCIL_TEST);
  41308. }
  41309. self.realColorMask.call(gl, true, true, true, true);
  41310. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41311. if (self.ctxAttribs.alpha || isIOS()) {
  41312. self.realClearColor.call(gl, 0, 0, 0, 1);
  41313. gl.clear(gl.COLOR_BUFFER_BIT);
  41314. }
  41315. gl.useProgram(self.program);
  41316. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41317. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41318. gl.enableVertexAttribArray(self.attribs.position);
  41319. gl.enableVertexAttribArray(self.attribs.texCoord);
  41320. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  41321. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  41322. if (self.instanceExt) {
  41323. if (positionDivisor != 0) {
  41324. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, 0);
  41325. }
  41326. if (texCoordDivisor != 0) {
  41327. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, 0);
  41328. }
  41329. }
  41330. gl.activeTexture(gl.TEXTURE0);
  41331. gl.uniform1i(self.uniforms.diffuse, 0);
  41332. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  41333. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  41334. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  41335. if (self.cardboardUI) {
  41336. self.cardboardUI.renderNoState();
  41337. }
  41338. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  41339. if (!self.ctxAttribs.preserveDrawingBuffer) {
  41340. self.realClearColor.call(gl, 0, 0, 0, 0);
  41341. gl.clear(gl.COLOR_BUFFER_BIT);
  41342. }
  41343. if (!self.dirtySubmitFrameBindings) {
  41344. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  41345. }
  41346. if (self.cullFace) {
  41347. self.realEnable.call(gl, gl.CULL_FACE);
  41348. }
  41349. if (self.depthTest) {
  41350. self.realEnable.call(gl, gl.DEPTH_TEST);
  41351. }
  41352. if (self.blend) {
  41353. self.realEnable.call(gl, gl.BLEND);
  41354. }
  41355. if (self.scissorTest) {
  41356. self.realEnable.call(gl, gl.SCISSOR_TEST);
  41357. }
  41358. if (self.stencilTest) {
  41359. self.realEnable.call(gl, gl.STENCIL_TEST);
  41360. }
  41361. self.realColorMask.apply(gl, self.colorMask);
  41362. self.realViewport.apply(gl, self.viewport);
  41363. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  41364. self.realClearColor.apply(gl, self.clearColor);
  41365. }
  41366. if (self.instanceExt) {
  41367. if (positionDivisor != 0) {
  41368. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, positionDivisor);
  41369. }
  41370. if (texCoordDivisor != 0) {
  41371. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, texCoordDivisor);
  41372. }
  41373. }
  41374. });
  41375. if (isIOS()) {
  41376. var canvas = gl.canvas;
  41377. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  41378. self.bufferWidth = canvas.width;
  41379. self.bufferHeight = canvas.height;
  41380. self.onResize();
  41381. }
  41382. }
  41383. };
  41384. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  41385. var gl = this.gl;
  41386. var self = this;
  41387. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  41388. glPreserveState(gl, glState, function (gl) {
  41389. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  41390. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41391. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  41392. if (!self.indexCount) {
  41393. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  41394. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41395. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  41396. self.indexCount = indices.length;
  41397. }
  41398. });
  41399. };
  41400. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  41401. var vertices = new Float32Array(2 * width * height * 5);
  41402. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  41403. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  41404. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  41405. var vidx = 0;
  41406. for (var e = 0; e < 2; e++) {
  41407. for (var j = 0; j < height; j++) {
  41408. for (var i = 0; i < width; i++, vidx++) {
  41409. var u = i / (width - 1);
  41410. var v = j / (height - 1);
  41411. var s = u;
  41412. var t = v;
  41413. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  41414. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  41415. var d = Math.sqrt(x * x + y * y);
  41416. var r = deviceInfo.distortion.distortInverse(d);
  41417. var p = x * r / d;
  41418. var q = y * r / d;
  41419. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  41420. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  41421. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  41422. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  41423. vertices[vidx * 5 + 0] = u;
  41424. vertices[vidx * 5 + 1] = v;
  41425. vertices[vidx * 5 + 2] = s;
  41426. vertices[vidx * 5 + 3] = t;
  41427. vertices[vidx * 5 + 4] = e;
  41428. }
  41429. }
  41430. var w = lensFrustum[2] - lensFrustum[0];
  41431. lensFrustum[0] = -(w + lensFrustum[0]);
  41432. lensFrustum[2] = w - lensFrustum[2];
  41433. w = noLensFrustum[2] - noLensFrustum[0];
  41434. noLensFrustum[0] = -(w + noLensFrustum[0]);
  41435. noLensFrustum[2] = w - noLensFrustum[2];
  41436. viewport.x = 1 - (viewport.x + viewport.width);
  41437. }
  41438. return vertices;
  41439. };
  41440. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  41441. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  41442. var halfwidth = width / 2;
  41443. var halfheight = height / 2;
  41444. var vidx = 0;
  41445. var iidx = 0;
  41446. for (var e = 0; e < 2; e++) {
  41447. for (var j = 0; j < height; j++) {
  41448. for (var i = 0; i < width; i++, vidx++) {
  41449. if (i == 0 || j == 0) continue;
  41450. if (i <= halfwidth == j <= halfheight) {
  41451. indices[iidx++] = vidx;
  41452. indices[iidx++] = vidx - width - 1;
  41453. indices[iidx++] = vidx - width;
  41454. indices[iidx++] = vidx - width - 1;
  41455. indices[iidx++] = vidx;
  41456. indices[iidx++] = vidx - 1;
  41457. } else {
  41458. indices[iidx++] = vidx - 1;
  41459. indices[iidx++] = vidx - width;
  41460. indices[iidx++] = vidx;
  41461. indices[iidx++] = vidx - width;
  41462. indices[iidx++] = vidx - 1;
  41463. indices[iidx++] = vidx - width - 1;
  41464. }
  41465. }
  41466. }
  41467. }
  41468. return indices;
  41469. };
  41470. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  41471. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  41472. if (descriptor.get === undefined || descriptor.set === undefined) {
  41473. descriptor.configurable = true;
  41474. descriptor.enumerable = true;
  41475. descriptor.get = function () {
  41476. return this.getAttribute(attrName);
  41477. };
  41478. descriptor.set = function (val) {
  41479. this.setAttribute(attrName, val);
  41480. };
  41481. }
  41482. return descriptor;
  41483. };
  41484. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  41485. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  41486. var DEG2RAD = Math.PI / 180.0;
  41487. var kAnglePerGearSection = 60;
  41488. var kOuterRimEndAngle = 12;
  41489. var kInnerRimBeginAngle = 20;
  41490. var kOuterRadius = 1;
  41491. var kMiddleRadius = 0.75;
  41492. var kInnerRadius = 0.3125;
  41493. var kCenterLineThicknessDp = 4;
  41494. var kButtonWidthDp = 28;
  41495. var kTouchSlopFactor = 1.5;
  41496. function CardboardUI(gl) {
  41497. this.gl = gl;
  41498. this.attribs = {
  41499. position: 0
  41500. };
  41501. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  41502. this.uniforms = getProgramUniforms(gl, this.program);
  41503. this.vertexBuffer = gl.createBuffer();
  41504. this.gearOffset = 0;
  41505. this.gearVertexCount = 0;
  41506. this.arrowOffset = 0;
  41507. this.arrowVertexCount = 0;
  41508. this.projMat = new Float32Array(16);
  41509. this.listener = null;
  41510. this.onResize();
  41511. }
  41512. CardboardUI.prototype.destroy = function () {
  41513. var gl = this.gl;
  41514. if (this.listener) {
  41515. gl.canvas.removeEventListener('click', this.listener, false);
  41516. }
  41517. gl.deleteProgram(this.program);
  41518. gl.deleteBuffer(this.vertexBuffer);
  41519. };
  41520. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  41521. var canvas = this.gl.canvas;
  41522. this.listener = function (event) {
  41523. var midline = canvas.clientWidth / 2;
  41524. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  41525. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  41526. optionsCallback(event);
  41527. }
  41528. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  41529. backCallback(event);
  41530. }
  41531. };
  41532. canvas.addEventListener('click', this.listener, false);
  41533. };
  41534. CardboardUI.prototype.onResize = function () {
  41535. var gl = this.gl;
  41536. var self = this;
  41537. var glState = [gl.ARRAY_BUFFER_BINDING];
  41538. glPreserveState(gl, glState, function (gl) {
  41539. var vertices = [];
  41540. var midline = gl.drawingBufferWidth / 2;
  41541. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  41542. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  41543. var dps = scalingRatio * window.devicePixelRatio;
  41544. var lineWidth = kCenterLineThicknessDp * dps / 2;
  41545. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  41546. var buttonScale = kButtonWidthDp * dps / 2;
  41547. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  41548. vertices.push(midline - lineWidth, buttonSize);
  41549. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  41550. vertices.push(midline + lineWidth, buttonSize);
  41551. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  41552. self.gearOffset = vertices.length / 2;
  41553. function addGearSegment(theta, r) {
  41554. var angle = (90 - theta) * DEG2RAD;
  41555. var x = Math.cos(angle);
  41556. var y = Math.sin(angle);
  41557. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  41558. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  41559. }
  41560. for (var i = 0; i <= 6; i++) {
  41561. var segmentTheta = i * kAnglePerGearSection;
  41562. addGearSegment(segmentTheta, kOuterRadius);
  41563. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  41564. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  41565. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  41566. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  41567. }
  41568. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  41569. self.arrowOffset = vertices.length / 2;
  41570. function addArrowVertex(x, y) {
  41571. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  41572. }
  41573. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  41574. addArrowVertex(0, buttonScale);
  41575. addArrowVertex(buttonScale, 0);
  41576. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  41577. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  41578. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41579. addArrowVertex(0, buttonScale);
  41580. addArrowVertex(buttonScale, buttonScale * 2);
  41581. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  41582. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41583. addArrowVertex(0, buttonScale);
  41584. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  41585. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  41586. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  41587. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  41588. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  41589. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41590. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  41591. });
  41592. };
  41593. CardboardUI.prototype.render = function () {
  41594. var gl = this.gl;
  41595. var self = this;
  41596. 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];
  41597. glPreserveState(gl, glState, function (gl) {
  41598. gl.disable(gl.CULL_FACE);
  41599. gl.disable(gl.DEPTH_TEST);
  41600. gl.disable(gl.BLEND);
  41601. gl.disable(gl.SCISSOR_TEST);
  41602. gl.disable(gl.STENCIL_TEST);
  41603. gl.colorMask(true, true, true, true);
  41604. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41605. self.renderNoState();
  41606. });
  41607. };
  41608. CardboardUI.prototype.renderNoState = function () {
  41609. var gl = this.gl;
  41610. gl.useProgram(this.program);
  41611. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  41612. gl.enableVertexAttribArray(this.attribs.position);
  41613. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  41614. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  41615. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  41616. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  41617. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  41618. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  41619. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  41620. };
  41621. function Distortion(coefficients) {
  41622. this.coefficients = coefficients;
  41623. }
  41624. Distortion.prototype.distortInverse = function (radius) {
  41625. var r0 = 0;
  41626. var r1 = 1;
  41627. var dr0 = radius - this.distort(r0);
  41628. while (Math.abs(r1 - r0) > 0.0001 ) {
  41629. var dr1 = radius - this.distort(r1);
  41630. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  41631. r0 = r1;
  41632. r1 = r2;
  41633. dr0 = dr1;
  41634. }
  41635. return r1;
  41636. };
  41637. Distortion.prototype.distort = function (radius) {
  41638. var r2 = radius * radius;
  41639. var ret = 0;
  41640. for (var i = 0; i < this.coefficients.length; i++) {
  41641. ret = r2 * (ret + this.coefficients[i]);
  41642. }
  41643. return (ret + 1) * radius;
  41644. };
  41645. var degToRad = Math.PI / 180;
  41646. var radToDeg = 180 / Math.PI;
  41647. var Vector3 = function Vector3(x, y, z) {
  41648. this.x = x || 0;
  41649. this.y = y || 0;
  41650. this.z = z || 0;
  41651. };
  41652. Vector3.prototype = {
  41653. constructor: Vector3,
  41654. set: function set(x, y, z) {
  41655. this.x = x;
  41656. this.y = y;
  41657. this.z = z;
  41658. return this;
  41659. },
  41660. copy: function copy(v) {
  41661. this.x = v.x;
  41662. this.y = v.y;
  41663. this.z = v.z;
  41664. return this;
  41665. },
  41666. length: function length() {
  41667. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  41668. },
  41669. normalize: function normalize() {
  41670. var scalar = this.length();
  41671. if (scalar !== 0) {
  41672. var invScalar = 1 / scalar;
  41673. this.multiplyScalar(invScalar);
  41674. } else {
  41675. this.x = 0;
  41676. this.y = 0;
  41677. this.z = 0;
  41678. }
  41679. return this;
  41680. },
  41681. multiplyScalar: function multiplyScalar(scalar) {
  41682. this.x *= scalar;
  41683. this.y *= scalar;
  41684. this.z *= scalar;
  41685. },
  41686. applyQuaternion: function applyQuaternion(q) {
  41687. var x = this.x;
  41688. var y = this.y;
  41689. var z = this.z;
  41690. var qx = q.x;
  41691. var qy = q.y;
  41692. var qz = q.z;
  41693. var qw = q.w;
  41694. var ix = qw * x + qy * z - qz * y;
  41695. var iy = qw * y + qz * x - qx * z;
  41696. var iz = qw * z + qx * y - qy * x;
  41697. var iw = -qx * x - qy * y - qz * z;
  41698. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  41699. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  41700. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  41701. return this;
  41702. },
  41703. dot: function dot(v) {
  41704. return this.x * v.x + this.y * v.y + this.z * v.z;
  41705. },
  41706. crossVectors: function crossVectors(a, b) {
  41707. var ax = a.x,
  41708. ay = a.y,
  41709. az = a.z;
  41710. var bx = b.x,
  41711. by = b.y,
  41712. bz = b.z;
  41713. this.x = ay * bz - az * by;
  41714. this.y = az * bx - ax * bz;
  41715. this.z = ax * by - ay * bx;
  41716. return this;
  41717. }
  41718. };
  41719. var Quaternion = function Quaternion(x, y, z, w) {
  41720. this.x = x || 0;
  41721. this.y = y || 0;
  41722. this.z = z || 0;
  41723. this.w = w !== undefined ? w : 1;
  41724. };
  41725. Quaternion.prototype = {
  41726. constructor: Quaternion,
  41727. set: function set(x, y, z, w) {
  41728. this.x = x;
  41729. this.y = y;
  41730. this.z = z;
  41731. this.w = w;
  41732. return this;
  41733. },
  41734. copy: function copy(quaternion) {
  41735. this.x = quaternion.x;
  41736. this.y = quaternion.y;
  41737. this.z = quaternion.z;
  41738. this.w = quaternion.w;
  41739. return this;
  41740. },
  41741. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  41742. var c1 = Math.cos(x / 2);
  41743. var c2 = Math.cos(y / 2);
  41744. var c3 = Math.cos(z / 2);
  41745. var s1 = Math.sin(x / 2);
  41746. var s2 = Math.sin(y / 2);
  41747. var s3 = Math.sin(z / 2);
  41748. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41749. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41750. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  41751. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  41752. return this;
  41753. },
  41754. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  41755. var c1 = Math.cos(x / 2);
  41756. var c2 = Math.cos(y / 2);
  41757. var c3 = Math.cos(z / 2);
  41758. var s1 = Math.sin(x / 2);
  41759. var s2 = Math.sin(y / 2);
  41760. var s3 = Math.sin(z / 2);
  41761. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41762. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41763. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  41764. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  41765. return this;
  41766. },
  41767. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  41768. var halfAngle = angle / 2,
  41769. s = Math.sin(halfAngle);
  41770. this.x = axis.x * s;
  41771. this.y = axis.y * s;
  41772. this.z = axis.z * s;
  41773. this.w = Math.cos(halfAngle);
  41774. return this;
  41775. },
  41776. multiply: function multiply(q) {
  41777. return this.multiplyQuaternions(this, q);
  41778. },
  41779. multiplyQuaternions: function multiplyQuaternions(a, b) {
  41780. var qax = a.x,
  41781. qay = a.y,
  41782. qaz = a.z,
  41783. qaw = a.w;
  41784. var qbx = b.x,
  41785. qby = b.y,
  41786. qbz = b.z,
  41787. qbw = b.w;
  41788. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  41789. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  41790. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  41791. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  41792. return this;
  41793. },
  41794. inverse: function inverse() {
  41795. this.x *= -1;
  41796. this.y *= -1;
  41797. this.z *= -1;
  41798. this.normalize();
  41799. return this;
  41800. },
  41801. normalize: function normalize() {
  41802. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  41803. if (l === 0) {
  41804. this.x = 0;
  41805. this.y = 0;
  41806. this.z = 0;
  41807. this.w = 1;
  41808. } else {
  41809. l = 1 / l;
  41810. this.x = this.x * l;
  41811. this.y = this.y * l;
  41812. this.z = this.z * l;
  41813. this.w = this.w * l;
  41814. }
  41815. return this;
  41816. },
  41817. slerp: function slerp(qb, t) {
  41818. if (t === 0) return this;
  41819. if (t === 1) return this.copy(qb);
  41820. var x = this.x,
  41821. y = this.y,
  41822. z = this.z,
  41823. w = this.w;
  41824. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  41825. if (cosHalfTheta < 0) {
  41826. this.w = -qb.w;
  41827. this.x = -qb.x;
  41828. this.y = -qb.y;
  41829. this.z = -qb.z;
  41830. cosHalfTheta = -cosHalfTheta;
  41831. } else {
  41832. this.copy(qb);
  41833. }
  41834. if (cosHalfTheta >= 1.0) {
  41835. this.w = w;
  41836. this.x = x;
  41837. this.y = y;
  41838. this.z = z;
  41839. return this;
  41840. }
  41841. var halfTheta = Math.acos(cosHalfTheta);
  41842. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  41843. if (Math.abs(sinHalfTheta) < 0.001) {
  41844. this.w = 0.5 * (w + this.w);
  41845. this.x = 0.5 * (x + this.x);
  41846. this.y = 0.5 * (y + this.y);
  41847. this.z = 0.5 * (z + this.z);
  41848. return this;
  41849. }
  41850. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  41851. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  41852. this.w = w * ratioA + this.w * ratioB;
  41853. this.x = x * ratioA + this.x * ratioB;
  41854. this.y = y * ratioA + this.y * ratioB;
  41855. this.z = z * ratioA + this.z * ratioB;
  41856. return this;
  41857. },
  41858. setFromUnitVectors: function () {
  41859. var v1, r;
  41860. var EPS = 0.000001;
  41861. return function (vFrom, vTo) {
  41862. if (v1 === undefined) v1 = new Vector3();
  41863. r = vFrom.dot(vTo) + 1;
  41864. if (r < EPS) {
  41865. r = 0;
  41866. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  41867. v1.set(-vFrom.y, vFrom.x, 0);
  41868. } else {
  41869. v1.set(0, -vFrom.z, vFrom.y);
  41870. }
  41871. } else {
  41872. v1.crossVectors(vFrom, vTo);
  41873. }
  41874. this.x = v1.x;
  41875. this.y = v1.y;
  41876. this.z = v1.z;
  41877. this.w = r;
  41878. this.normalize();
  41879. return this;
  41880. };
  41881. }()
  41882. };
  41883. function Device(params) {
  41884. this.width = params.width || getScreenWidth();
  41885. this.height = params.height || getScreenHeight();
  41886. this.widthMeters = params.widthMeters;
  41887. this.heightMeters = params.heightMeters;
  41888. this.bevelMeters = params.bevelMeters;
  41889. }
  41890. var DEFAULT_ANDROID = new Device({
  41891. widthMeters: 0.110,
  41892. heightMeters: 0.062,
  41893. bevelMeters: 0.004
  41894. });
  41895. var DEFAULT_IOS = new Device({
  41896. widthMeters: 0.1038,
  41897. heightMeters: 0.0584,
  41898. bevelMeters: 0.004
  41899. });
  41900. var Viewers = {
  41901. CardboardV1: new CardboardViewer({
  41902. id: 'CardboardV1',
  41903. label: 'Cardboard I/O 2014',
  41904. fov: 40,
  41905. interLensDistance: 0.060,
  41906. baselineLensDistance: 0.035,
  41907. screenLensDistance: 0.042,
  41908. distortionCoefficients: [0.441, 0.156],
  41909. 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]
  41910. }),
  41911. CardboardV2: new CardboardViewer({
  41912. id: 'CardboardV2',
  41913. label: 'Cardboard I/O 2015',
  41914. fov: 60,
  41915. interLensDistance: 0.064,
  41916. baselineLensDistance: 0.035,
  41917. screenLensDistance: 0.039,
  41918. distortionCoefficients: [0.34, 0.55],
  41919. 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]
  41920. })
  41921. };
  41922. function DeviceInfo(deviceParams, additionalViewers) {
  41923. this.viewer = Viewers.CardboardV2;
  41924. this.updateDeviceParams(deviceParams);
  41925. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41926. for (var i = 0; i < additionalViewers.length; i++) {
  41927. var viewer = additionalViewers[i];
  41928. Viewers[viewer.id] = new CardboardViewer(viewer);
  41929. }
  41930. }
  41931. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  41932. this.device = this.determineDevice_(deviceParams) || this.device;
  41933. };
  41934. DeviceInfo.prototype.getDevice = function () {
  41935. return this.device;
  41936. };
  41937. DeviceInfo.prototype.setViewer = function (viewer) {
  41938. this.viewer = viewer;
  41939. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41940. };
  41941. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  41942. if (!deviceParams) {
  41943. if (isIOS()) {
  41944. console.warn('Using fallback iOS device measurements.');
  41945. return DEFAULT_IOS;
  41946. } else {
  41947. console.warn('Using fallback Android device measurements.');
  41948. return DEFAULT_ANDROID;
  41949. }
  41950. }
  41951. var METERS_PER_INCH = 0.0254;
  41952. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  41953. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  41954. var width = getScreenWidth();
  41955. var height = getScreenHeight();
  41956. return new Device({
  41957. widthMeters: metersPerPixelX * width,
  41958. heightMeters: metersPerPixelY * height,
  41959. bevelMeters: deviceParams.bevelMm * 0.001
  41960. });
  41961. };
  41962. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  41963. var viewer = this.viewer;
  41964. var device = this.device;
  41965. var distortion = this.distortion;
  41966. var eyeToScreenDistance = viewer.screenLensDistance;
  41967. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  41968. var innerDist = viewer.interLensDistance / 2;
  41969. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  41970. var topDist = device.heightMeters - bottomDist;
  41971. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  41972. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  41973. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  41974. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  41975. return {
  41976. leftDegrees: Math.min(outerAngle, viewer.fov),
  41977. rightDegrees: Math.min(innerAngle, viewer.fov),
  41978. downDegrees: Math.min(bottomAngle, viewer.fov),
  41979. upDegrees: Math.min(topAngle, viewer.fov)
  41980. };
  41981. };
  41982. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  41983. var viewer = this.viewer;
  41984. var device = this.device;
  41985. var distortion = this.distortion;
  41986. var fovLeft = Math.tan(-degToRad * viewer.fov);
  41987. var fovTop = Math.tan(degToRad * viewer.fov);
  41988. var fovRight = Math.tan(degToRad * viewer.fov);
  41989. var fovBottom = Math.tan(-degToRad * viewer.fov);
  41990. var halfWidth = device.widthMeters / 4;
  41991. var halfHeight = device.heightMeters / 2;
  41992. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  41993. var centerX = viewer.interLensDistance / 2 - halfWidth;
  41994. var centerY = -verticalLensOffset;
  41995. var centerZ = viewer.screenLensDistance;
  41996. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  41997. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  41998. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  41999. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  42000. var result = new Float32Array(4);
  42001. result[0] = Math.max(fovLeft, screenLeft);
  42002. result[1] = Math.min(fovTop, screenTop);
  42003. result[2] = Math.min(fovRight, screenRight);
  42004. result[3] = Math.max(fovBottom, screenBottom);
  42005. return result;
  42006. };
  42007. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  42008. var viewer = this.viewer;
  42009. var device = this.device;
  42010. var distortion = this.distortion;
  42011. var result = new Float32Array(4);
  42012. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42013. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42014. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42015. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42016. var halfWidth = device.widthMeters / 4;
  42017. var halfHeight = device.heightMeters / 2;
  42018. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  42019. var centerX = viewer.interLensDistance / 2 - halfWidth;
  42020. var centerY = -verticalLensOffset;
  42021. var centerZ = viewer.screenLensDistance;
  42022. var screenLeft = (centerX - halfWidth) / centerZ;
  42023. var screenTop = (centerY + halfHeight) / centerZ;
  42024. var screenRight = (centerX + halfWidth) / centerZ;
  42025. var screenBottom = (centerY - halfHeight) / centerZ;
  42026. result[0] = Math.max(fovLeft, screenLeft);
  42027. result[1] = Math.min(fovTop, screenTop);
  42028. result[2] = Math.min(fovRight, screenRight);
  42029. result[3] = Math.max(fovBottom, screenBottom);
  42030. return result;
  42031. };
  42032. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  42033. var viewer = this.viewer;
  42034. var device = this.device;
  42035. var dist = viewer.screenLensDistance;
  42036. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  42037. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  42038. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  42039. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  42040. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  42041. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  42042. return {
  42043. x: left,
  42044. y: bottom,
  42045. width: right - left,
  42046. height: top - bottom
  42047. };
  42048. };
  42049. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  42050. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  42051. };
  42052. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  42053. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  42054. return {
  42055. leftDegrees: fov.rightDegrees,
  42056. rightDegrees: fov.leftDegrees,
  42057. upDegrees: fov.upDegrees,
  42058. downDegrees: fov.downDegrees
  42059. };
  42060. };
  42061. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  42062. var p = this.getUndistortedParams_();
  42063. return {
  42064. leftDegrees: radToDeg * Math.atan(p.outerDist),
  42065. rightDegrees: radToDeg * Math.atan(p.innerDist),
  42066. downDegrees: radToDeg * Math.atan(p.bottomDist),
  42067. upDegrees: radToDeg * Math.atan(p.topDist)
  42068. };
  42069. };
  42070. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  42071. var p = this.getUndistortedParams_();
  42072. var viewer = this.viewer;
  42073. var device = this.device;
  42074. var eyeToScreenDistance = viewer.screenLensDistance;
  42075. var screenWidth = device.widthMeters / eyeToScreenDistance;
  42076. var screenHeight = device.heightMeters / eyeToScreenDistance;
  42077. var xPxPerTanAngle = device.width / screenWidth;
  42078. var yPxPerTanAngle = device.height / screenHeight;
  42079. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  42080. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  42081. return {
  42082. x: x,
  42083. y: y,
  42084. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  42085. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  42086. };
  42087. };
  42088. DeviceInfo.prototype.getUndistortedParams_ = function () {
  42089. var viewer = this.viewer;
  42090. var device = this.device;
  42091. var distortion = this.distortion;
  42092. var eyeToScreenDistance = viewer.screenLensDistance;
  42093. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  42094. var screenWidth = device.widthMeters / eyeToScreenDistance;
  42095. var screenHeight = device.heightMeters / eyeToScreenDistance;
  42096. var eyePosX = screenWidth / 2 - halfLensDistance;
  42097. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  42098. var maxFov = viewer.fov;
  42099. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  42100. var outerDist = Math.min(eyePosX, viewerMax);
  42101. var innerDist = Math.min(halfLensDistance, viewerMax);
  42102. var bottomDist = Math.min(eyePosY, viewerMax);
  42103. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  42104. return {
  42105. outerDist: outerDist,
  42106. innerDist: innerDist,
  42107. topDist: topDist,
  42108. bottomDist: bottomDist,
  42109. eyePosX: eyePosX,
  42110. eyePosY: eyePosY
  42111. };
  42112. };
  42113. function CardboardViewer(params) {
  42114. this.id = params.id;
  42115. this.label = params.label;
  42116. this.fov = params.fov;
  42117. this.interLensDistance = params.interLensDistance;
  42118. this.baselineLensDistance = params.baselineLensDistance;
  42119. this.screenLensDistance = params.screenLensDistance;
  42120. this.distortionCoefficients = params.distortionCoefficients;
  42121. this.inverseCoefficients = params.inverseCoefficients;
  42122. }
  42123. DeviceInfo.Viewers = Viewers;
  42124. var format = 1;
  42125. var last_updated = "2019-11-09T17:36:14Z";
  42126. 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}];
  42127. var DPDB_CACHE = {
  42128. format: format,
  42129. last_updated: last_updated,
  42130. devices: devices
  42131. };
  42132. function Dpdb(url, onDeviceParamsUpdated) {
  42133. this.dpdb = DPDB_CACHE;
  42134. this.recalculateDeviceParams_();
  42135. if (url) {
  42136. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  42137. var xhr = new XMLHttpRequest();
  42138. var obj = this;
  42139. xhr.open('GET', url, true);
  42140. xhr.addEventListener('load', function () {
  42141. obj.loading = false;
  42142. if (xhr.status >= 200 && xhr.status <= 299) {
  42143. obj.dpdb = JSON.parse(xhr.response);
  42144. obj.recalculateDeviceParams_();
  42145. } else {
  42146. console.error('Error loading online DPDB!');
  42147. }
  42148. });
  42149. xhr.send();
  42150. }
  42151. }
  42152. Dpdb.prototype.getDeviceParams = function () {
  42153. return this.deviceParams;
  42154. };
  42155. Dpdb.prototype.recalculateDeviceParams_ = function () {
  42156. var newDeviceParams = this.calcDeviceParams_();
  42157. if (newDeviceParams) {
  42158. this.deviceParams = newDeviceParams;
  42159. if (this.onDeviceParamsUpdated) {
  42160. this.onDeviceParamsUpdated(this.deviceParams);
  42161. }
  42162. } else {
  42163. console.error('Failed to recalculate device parameters.');
  42164. }
  42165. };
  42166. Dpdb.prototype.calcDeviceParams_ = function () {
  42167. var db = this.dpdb;
  42168. if (!db) {
  42169. console.error('DPDB not available.');
  42170. return null;
  42171. }
  42172. if (db.format != 1) {
  42173. console.error('DPDB has unexpected format version.');
  42174. return null;
  42175. }
  42176. if (!db.devices || !db.devices.length) {
  42177. console.error('DPDB does not have a devices section.');
  42178. return null;
  42179. }
  42180. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  42181. var width = getScreenWidth();
  42182. var height = getScreenHeight();
  42183. if (!db.devices) {
  42184. console.error('DPDB has no devices section.');
  42185. return null;
  42186. }
  42187. for (var i = 0; i < db.devices.length; i++) {
  42188. var device = db.devices[i];
  42189. if (!device.rules) {
  42190. console.warn('Device[' + i + '] has no rules section.');
  42191. continue;
  42192. }
  42193. if (device.type != 'ios' && device.type != 'android') {
  42194. console.warn('Device[' + i + '] has invalid type.');
  42195. continue;
  42196. }
  42197. if (isIOS() != (device.type == 'ios')) continue;
  42198. var matched = false;
  42199. for (var j = 0; j < device.rules.length; j++) {
  42200. var rule = device.rules[j];
  42201. if (this.ruleMatches_(rule, userAgent, width, height)) {
  42202. matched = true;
  42203. break;
  42204. }
  42205. }
  42206. if (!matched) continue;
  42207. var xdpi = device.dpi[0] || device.dpi;
  42208. var ydpi = device.dpi[1] || device.dpi;
  42209. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  42210. }
  42211. console.warn('No DPDB device match.');
  42212. return null;
  42213. };
  42214. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  42215. if (!rule.ua && !rule.res) return false;
  42216. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  42217. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  42218. if (rule.res) {
  42219. if (!rule.res[0] || !rule.res[1]) return false;
  42220. var resX = rule.res[0];
  42221. var resY = rule.res[1];
  42222. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  42223. return false;
  42224. }
  42225. }
  42226. return true;
  42227. };
  42228. function DeviceParams(params) {
  42229. this.xdpi = params.xdpi;
  42230. this.ydpi = params.ydpi;
  42231. this.bevelMm = params.bevelMm;
  42232. }
  42233. function SensorSample(sample, timestampS) {
  42234. this.set(sample, timestampS);
  42235. }
  42236. SensorSample.prototype.set = function (sample, timestampS) {
  42237. this.sample = sample;
  42238. this.timestampS = timestampS;
  42239. };
  42240. SensorSample.prototype.copy = function (sensorSample) {
  42241. this.set(sensorSample.sample, sensorSample.timestampS);
  42242. };
  42243. function ComplementaryFilter(kFilter, isDebug) {
  42244. this.kFilter = kFilter;
  42245. this.isDebug = isDebug;
  42246. this.currentAccelMeasurement = new SensorSample();
  42247. this.currentGyroMeasurement = new SensorSample();
  42248. this.previousGyroMeasurement = new SensorSample();
  42249. if (isIOS()) {
  42250. this.filterQ = new Quaternion(-1, 0, 0, 1);
  42251. } else {
  42252. this.filterQ = new Quaternion(1, 0, 0, 1);
  42253. }
  42254. this.previousFilterQ = new Quaternion();
  42255. this.previousFilterQ.copy(this.filterQ);
  42256. this.accelQ = new Quaternion();
  42257. this.isOrientationInitialized = false;
  42258. this.estimatedGravity = new Vector3();
  42259. this.measuredGravity = new Vector3();
  42260. this.gyroIntegralQ = new Quaternion();
  42261. }
  42262. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  42263. this.currentAccelMeasurement.set(vector, timestampS);
  42264. };
  42265. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  42266. this.currentGyroMeasurement.set(vector, timestampS);
  42267. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  42268. if (isTimestampDeltaValid(deltaT)) {
  42269. this.run_();
  42270. }
  42271. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  42272. };
  42273. ComplementaryFilter.prototype.run_ = function () {
  42274. if (!this.isOrientationInitialized) {
  42275. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  42276. this.previousFilterQ.copy(this.accelQ);
  42277. this.isOrientationInitialized = true;
  42278. return;
  42279. }
  42280. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  42281. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  42282. this.gyroIntegralQ.multiply(gyroDeltaQ);
  42283. this.filterQ.copy(this.previousFilterQ);
  42284. this.filterQ.multiply(gyroDeltaQ);
  42285. var invFilterQ = new Quaternion();
  42286. invFilterQ.copy(this.filterQ);
  42287. invFilterQ.inverse();
  42288. this.estimatedGravity.set(0, 0, -1);
  42289. this.estimatedGravity.applyQuaternion(invFilterQ);
  42290. this.estimatedGravity.normalize();
  42291. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  42292. this.measuredGravity.normalize();
  42293. var deltaQ = new Quaternion();
  42294. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  42295. deltaQ.inverse();
  42296. if (this.isDebug) {
  42297. 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));
  42298. }
  42299. var targetQ = new Quaternion();
  42300. targetQ.copy(this.filterQ);
  42301. targetQ.multiply(deltaQ);
  42302. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  42303. this.previousFilterQ.copy(this.filterQ);
  42304. };
  42305. ComplementaryFilter.prototype.getOrientation = function () {
  42306. return this.filterQ;
  42307. };
  42308. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  42309. var normAccel = new Vector3();
  42310. normAccel.copy(accel);
  42311. normAccel.normalize();
  42312. var quat = new Quaternion();
  42313. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  42314. quat.inverse();
  42315. return quat;
  42316. };
  42317. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  42318. var quat = new Quaternion();
  42319. var axis = new Vector3();
  42320. axis.copy(gyro);
  42321. axis.normalize();
  42322. quat.setFromAxisAngle(axis, gyro.length() * dt);
  42323. return quat;
  42324. };
  42325. function PosePredictor(predictionTimeS, isDebug) {
  42326. this.predictionTimeS = predictionTimeS;
  42327. this.isDebug = isDebug;
  42328. this.previousQ = new Quaternion();
  42329. this.previousTimestampS = null;
  42330. this.deltaQ = new Quaternion();
  42331. this.outQ = new Quaternion();
  42332. }
  42333. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  42334. if (!this.previousTimestampS) {
  42335. this.previousQ.copy(currentQ);
  42336. this.previousTimestampS = timestampS;
  42337. return currentQ;
  42338. }
  42339. var axis = new Vector3();
  42340. axis.copy(gyro);
  42341. axis.normalize();
  42342. var angularSpeed = gyro.length();
  42343. if (angularSpeed < degToRad * 20) {
  42344. if (this.isDebug) {
  42345. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  42346. }
  42347. this.outQ.copy(currentQ);
  42348. this.previousQ.copy(currentQ);
  42349. return this.outQ;
  42350. }
  42351. var predictAngle = angularSpeed * this.predictionTimeS;
  42352. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  42353. this.outQ.copy(this.previousQ);
  42354. this.outQ.multiply(this.deltaQ);
  42355. this.previousQ.copy(currentQ);
  42356. this.previousTimestampS = timestampS;
  42357. return this.outQ;
  42358. };
  42359. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  42360. this.yawOnly = yawOnly;
  42361. this.accelerometer = new Vector3();
  42362. this.gyroscope = new Vector3();
  42363. this.filter = new ComplementaryFilter(kFilter, isDebug);
  42364. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  42365. this.isFirefoxAndroid = isFirefoxAndroid();
  42366. this.isIOS = isIOS();
  42367. var chromeVersion = getChromeVersion();
  42368. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  42369. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion() || isSafariWithoutDeviceMotion();
  42370. this.filterToWorldQ = new Quaternion();
  42371. if (isIOS()) {
  42372. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  42373. } else {
  42374. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42375. }
  42376. this.inverseWorldToScreenQ = new Quaternion();
  42377. this.worldToScreenQ = new Quaternion();
  42378. this.originalPoseAdjustQ = new Quaternion();
  42379. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  42380. this.setScreenTransform_();
  42381. if (isLandscapeMode()) {
  42382. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  42383. }
  42384. this.resetQ = new Quaternion();
  42385. this.orientationOut_ = new Float32Array(4);
  42386. this.start();
  42387. }
  42388. FusionPoseSensor.prototype.getPosition = function () {
  42389. return null;
  42390. };
  42391. FusionPoseSensor.prototype.getOrientation = function () {
  42392. var orientation = void 0;
  42393. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  42394. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  42395. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  42396. var y = new Quaternion();
  42397. if (window.orientation === -90) {
  42398. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  42399. } else {
  42400. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  42401. }
  42402. return z.multiply(y);
  42403. }();
  42404. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  42405. var q = new Quaternion();
  42406. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42407. return q;
  42408. }();
  42409. orientation = this._deviceOrientationQ;
  42410. var out = new Quaternion();
  42411. out.copy(orientation);
  42412. out.multiply(this.deviceOrientationFilterToWorldQ);
  42413. out.multiply(this.resetQ);
  42414. out.multiply(this.worldToScreenQ);
  42415. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  42416. if (this.yawOnly) {
  42417. out.x = 0;
  42418. out.z = 0;
  42419. out.normalize();
  42420. }
  42421. this.orientationOut_[0] = out.x;
  42422. this.orientationOut_[1] = out.y;
  42423. this.orientationOut_[2] = out.z;
  42424. this.orientationOut_[3] = out.w;
  42425. return this.orientationOut_;
  42426. } else {
  42427. var filterOrientation = this.filter.getOrientation();
  42428. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  42429. }
  42430. var out = new Quaternion();
  42431. out.copy(this.filterToWorldQ);
  42432. out.multiply(this.resetQ);
  42433. out.multiply(orientation);
  42434. out.multiply(this.worldToScreenQ);
  42435. if (this.yawOnly) {
  42436. out.x = 0;
  42437. out.z = 0;
  42438. out.normalize();
  42439. }
  42440. this.orientationOut_[0] = out.x;
  42441. this.orientationOut_[1] = out.y;
  42442. this.orientationOut_[2] = out.z;
  42443. this.orientationOut_[3] = out.w;
  42444. return this.orientationOut_;
  42445. };
  42446. FusionPoseSensor.prototype.resetPose = function () {
  42447. this.resetQ.copy(this.filter.getOrientation());
  42448. this.resetQ.x = 0;
  42449. this.resetQ.y = 0;
  42450. this.resetQ.z *= -1;
  42451. this.resetQ.normalize();
  42452. if (isLandscapeMode()) {
  42453. this.resetQ.multiply(this.inverseWorldToScreenQ);
  42454. }
  42455. this.resetQ.multiply(this.originalPoseAdjustQ);
  42456. };
  42457. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  42458. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  42459. var alpha = e.alpha,
  42460. beta = e.beta,
  42461. gamma = e.gamma;
  42462. alpha = (alpha || 0) * Math.PI / 180;
  42463. beta = (beta || 0) * Math.PI / 180;
  42464. gamma = (gamma || 0) * Math.PI / 180;
  42465. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  42466. };
  42467. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  42468. this.updateDeviceMotion_(deviceMotion);
  42469. };
  42470. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  42471. var accGravity = deviceMotion.accelerationIncludingGravity;
  42472. var rotRate = deviceMotion.rotationRate;
  42473. var timestampS = deviceMotion.timeStamp / 1000;
  42474. var deltaS = timestampS - this.previousTimestampS;
  42475. if (deltaS < 0) {
  42476. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  42477. this.previousTimestampS = timestampS;
  42478. return;
  42479. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  42480. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  42481. this.previousTimestampS = timestampS;
  42482. return;
  42483. }
  42484. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  42485. if (rotRate) {
  42486. if (isR7()) {
  42487. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  42488. } else {
  42489. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  42490. }
  42491. if (!this.isDeviceMotionInRadians) {
  42492. this.gyroscope.multiplyScalar(Math.PI / 180);
  42493. }
  42494. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  42495. }
  42496. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  42497. this.previousTimestampS = timestampS;
  42498. };
  42499. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  42500. this.setScreenTransform_();
  42501. };
  42502. FusionPoseSensor.prototype.onMessage_ = function (event) {
  42503. var message = event.data;
  42504. if (!message || !message.type) {
  42505. return;
  42506. }
  42507. var type = message.type.toLowerCase();
  42508. if (type !== 'devicemotion') {
  42509. return;
  42510. }
  42511. this.updateDeviceMotion_(message.deviceMotionEvent);
  42512. };
  42513. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  42514. this.worldToScreenQ.set(0, 0, 0, 1);
  42515. switch (window.orientation) {
  42516. case 0:
  42517. break;
  42518. case 90:
  42519. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  42520. break;
  42521. case -90:
  42522. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  42523. break;
  42524. case 180:
  42525. break;
  42526. }
  42527. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  42528. this.inverseWorldToScreenQ.inverse();
  42529. };
  42530. FusionPoseSensor.prototype.start = function () {
  42531. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  42532. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  42533. this.onMessageCallback_ = this.onMessage_.bind(this);
  42534. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  42535. if (isIOS() && isInsideCrossOriginIFrame()) {
  42536. window.addEventListener('message', this.onMessageCallback_);
  42537. }
  42538. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  42539. if (this.isWithoutDeviceMotion) {
  42540. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42541. } else {
  42542. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  42543. }
  42544. };
  42545. FusionPoseSensor.prototype.stop = function () {
  42546. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  42547. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42548. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  42549. window.removeEventListener('message', this.onMessageCallback_);
  42550. };
  42551. var SENSOR_FREQUENCY = 60;
  42552. var X_AXIS = new Vector3(1, 0, 0);
  42553. var Z_AXIS = new Vector3(0, 0, 1);
  42554. var SENSOR_TO_VR = new Quaternion();
  42555. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  42556. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  42557. var PoseSensor = function () {
  42558. function PoseSensor(config) {
  42559. classCallCheck(this, PoseSensor);
  42560. this.config = config;
  42561. this.sensor = null;
  42562. this.fusionSensor = null;
  42563. this._out = new Float32Array(4);
  42564. this.api = null;
  42565. this.errors = [];
  42566. this._sensorQ = new Quaternion();
  42567. this._outQ = new Quaternion();
  42568. this._onSensorRead = this._onSensorRead.bind(this);
  42569. this._onSensorError = this._onSensorError.bind(this);
  42570. this.init();
  42571. }
  42572. createClass(PoseSensor, [{
  42573. key: 'init',
  42574. value: function init() {
  42575. var sensor = null;
  42576. try {
  42577. sensor = new RelativeOrientationSensor({
  42578. frequency: SENSOR_FREQUENCY,
  42579. referenceFrame: 'screen'
  42580. });
  42581. sensor.addEventListener('error', this._onSensorError);
  42582. } catch (error) {
  42583. this.errors.push(error);
  42584. if (error.name === 'SecurityError') {
  42585. console.error('Cannot construct sensors due to the Feature Policy');
  42586. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  42587. this.useDeviceMotion();
  42588. } else if (error.name === 'ReferenceError') {
  42589. this.useDeviceMotion();
  42590. } else {
  42591. console.error(error);
  42592. }
  42593. }
  42594. if (sensor) {
  42595. this.api = 'sensor';
  42596. this.sensor = sensor;
  42597. this.sensor.addEventListener('reading', this._onSensorRead);
  42598. this.sensor.start();
  42599. }
  42600. }
  42601. }, {
  42602. key: 'useDeviceMotion',
  42603. value: function useDeviceMotion() {
  42604. this.api = 'devicemotion';
  42605. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  42606. if (this.sensor) {
  42607. this.sensor.removeEventListener('reading', this._onSensorRead);
  42608. this.sensor.removeEventListener('error', this._onSensorError);
  42609. this.sensor = null;
  42610. }
  42611. }
  42612. }, {
  42613. key: 'getOrientation',
  42614. value: function getOrientation() {
  42615. if (this.fusionSensor) {
  42616. return this.fusionSensor.getOrientation();
  42617. }
  42618. if (!this.sensor || !this.sensor.quaternion) {
  42619. this._out[0] = this._out[1] = this._out[2] = 0;
  42620. this._out[3] = 1;
  42621. return this._out;
  42622. }
  42623. var q = this.sensor.quaternion;
  42624. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  42625. var out = this._outQ;
  42626. out.copy(SENSOR_TO_VR);
  42627. out.multiply(this._sensorQ);
  42628. if (this.config.YAW_ONLY) {
  42629. out.x = out.z = 0;
  42630. out.normalize();
  42631. }
  42632. this._out[0] = out.x;
  42633. this._out[1] = out.y;
  42634. this._out[2] = out.z;
  42635. this._out[3] = out.w;
  42636. return this._out;
  42637. }
  42638. }, {
  42639. key: '_onSensorError',
  42640. value: function _onSensorError(event) {
  42641. this.errors.push(event.error);
  42642. if (event.error.name === 'NotAllowedError') {
  42643. console.error('Permission to access sensor was denied');
  42644. } else if (event.error.name === 'NotReadableError') {
  42645. console.error('Sensor could not be read');
  42646. } else {
  42647. console.error(event.error);
  42648. }
  42649. this.useDeviceMotion();
  42650. }
  42651. }, {
  42652. key: '_onSensorRead',
  42653. value: function _onSensorRead() {}
  42654. }]);
  42655. return PoseSensor;
  42656. }();
  42657. 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>";
  42658. function RotateInstructions() {
  42659. this.loadIcon_();
  42660. var overlay = document.createElement('div');
  42661. var s = overlay.style;
  42662. s.position = 'fixed';
  42663. s.top = 0;
  42664. s.right = 0;
  42665. s.bottom = 0;
  42666. s.left = 0;
  42667. s.backgroundColor = 'gray';
  42668. s.fontFamily = 'sans-serif';
  42669. s.zIndex = 1000000;
  42670. var img = document.createElement('img');
  42671. img.src = this.icon;
  42672. var s = img.style;
  42673. s.marginLeft = '25%';
  42674. s.marginTop = '25%';
  42675. s.width = '50%';
  42676. overlay.appendChild(img);
  42677. var text = document.createElement('div');
  42678. var s = text.style;
  42679. s.textAlign = 'center';
  42680. s.fontSize = '16px';
  42681. s.lineHeight = '24px';
  42682. s.margin = '24px 25%';
  42683. s.width = '50%';
  42684. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  42685. overlay.appendChild(text);
  42686. var snackbar = document.createElement('div');
  42687. var s = snackbar.style;
  42688. s.backgroundColor = '#CFD8DC';
  42689. s.position = 'fixed';
  42690. s.bottom = 0;
  42691. s.width = '100%';
  42692. s.height = '48px';
  42693. s.padding = '14px 24px';
  42694. s.boxSizing = 'border-box';
  42695. s.color = '#656A6B';
  42696. overlay.appendChild(snackbar);
  42697. var snackbarText = document.createElement('div');
  42698. snackbarText.style.float = 'left';
  42699. snackbarText.innerHTML = 'No Cardboard viewer?';
  42700. var snackbarButton = document.createElement('a');
  42701. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  42702. snackbarButton.innerHTML = 'get one';
  42703. snackbarButton.target = '_blank';
  42704. var s = snackbarButton.style;
  42705. s.float = 'right';
  42706. s.fontWeight = 600;
  42707. s.textTransform = 'uppercase';
  42708. s.borderLeft = '1px solid gray';
  42709. s.paddingLeft = '24px';
  42710. s.textDecoration = 'none';
  42711. s.color = '#656A6B';
  42712. snackbar.appendChild(snackbarText);
  42713. snackbar.appendChild(snackbarButton);
  42714. this.overlay = overlay;
  42715. this.text = text;
  42716. this.hide();
  42717. }
  42718. RotateInstructions.prototype.show = function (parent) {
  42719. if (!parent && !this.overlay.parentElement) {
  42720. document.body.appendChild(this.overlay);
  42721. } else if (parent) {
  42722. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  42723. parent.appendChild(this.overlay);
  42724. }
  42725. this.overlay.style.display = 'block';
  42726. var img = this.overlay.querySelector('img');
  42727. var s = img.style;
  42728. if (isLandscapeMode()) {
  42729. s.width = '20%';
  42730. s.marginLeft = '40%';
  42731. s.marginTop = '3%';
  42732. } else {
  42733. s.width = '50%';
  42734. s.marginLeft = '25%';
  42735. s.marginTop = '25%';
  42736. }
  42737. };
  42738. RotateInstructions.prototype.hide = function () {
  42739. this.overlay.style.display = 'none';
  42740. };
  42741. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  42742. this.show(parent);
  42743. this.timer = setTimeout(this.hide.bind(this), ms);
  42744. };
  42745. RotateInstructions.prototype.disableShowTemporarily = function () {
  42746. clearTimeout(this.timer);
  42747. };
  42748. RotateInstructions.prototype.update = function () {
  42749. this.disableShowTemporarily();
  42750. if (!isLandscapeMode() && isMobile()) {
  42751. this.show();
  42752. } else {
  42753. this.hide();
  42754. }
  42755. };
  42756. RotateInstructions.prototype.loadIcon_ = function () {
  42757. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  42758. };
  42759. var DEFAULT_VIEWER = 'CardboardV1';
  42760. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  42761. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  42762. function ViewerSelector(defaultViewer) {
  42763. try {
  42764. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  42765. } catch (error) {
  42766. console.error('Failed to load viewer profile: %s', error);
  42767. }
  42768. if (!this.selectedKey) {
  42769. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  42770. }
  42771. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  42772. this.root = null;
  42773. this.onChangeCallbacks_ = [];
  42774. }
  42775. ViewerSelector.prototype.show = function (root) {
  42776. this.root = root;
  42777. root.appendChild(this.dialog);
  42778. var selected = this.dialog.querySelector('#' + this.selectedKey);
  42779. selected.checked = true;
  42780. this.dialog.style.display = 'block';
  42781. };
  42782. ViewerSelector.prototype.hide = function () {
  42783. if (this.root && this.root.contains(this.dialog)) {
  42784. this.root.removeChild(this.dialog);
  42785. }
  42786. this.dialog.style.display = 'none';
  42787. };
  42788. ViewerSelector.prototype.getCurrentViewer = function () {
  42789. return DeviceInfo.Viewers[this.selectedKey];
  42790. };
  42791. ViewerSelector.prototype.getSelectedKey_ = function () {
  42792. var input = this.dialog.querySelector('input[name=field]:checked');
  42793. if (input) {
  42794. return input.id;
  42795. }
  42796. return null;
  42797. };
  42798. ViewerSelector.prototype.onChange = function (cb) {
  42799. this.onChangeCallbacks_.push(cb);
  42800. };
  42801. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  42802. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  42803. this.onChangeCallbacks_[i](viewer);
  42804. }
  42805. };
  42806. ViewerSelector.prototype.onSave_ = function () {
  42807. this.selectedKey = this.getSelectedKey_();
  42808. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42809. console.error('ViewerSelector.onSave_: this should never happen!');
  42810. return;
  42811. }
  42812. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  42813. try {
  42814. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42815. } catch (error) {
  42816. console.error('Failed to save viewer profile: %s', error);
  42817. }
  42818. this.hide();
  42819. };
  42820. ViewerSelector.prototype.createDialog_ = function (options) {
  42821. var container = document.createElement('div');
  42822. container.classList.add(CLASS_NAME);
  42823. container.style.display = 'none';
  42824. var overlay = document.createElement('div');
  42825. var s = overlay.style;
  42826. s.position = 'fixed';
  42827. s.left = 0;
  42828. s.top = 0;
  42829. s.width = '100%';
  42830. s.height = '100%';
  42831. s.background = 'rgba(0, 0, 0, 0.3)';
  42832. overlay.addEventListener('click', this.hide.bind(this));
  42833. var width = 280;
  42834. var dialog = document.createElement('div');
  42835. var s = dialog.style;
  42836. s.boxSizing = 'border-box';
  42837. s.position = 'fixed';
  42838. s.top = '24px';
  42839. s.left = '50%';
  42840. s.marginLeft = -width / 2 + 'px';
  42841. s.width = width + 'px';
  42842. s.padding = '24px';
  42843. s.overflow = 'hidden';
  42844. s.background = '#fafafa';
  42845. s.fontFamily = "'Roboto', sans-serif";
  42846. s.boxShadow = '0px 5px 20px #666';
  42847. dialog.appendChild(this.createH1_('Select your viewer'));
  42848. for (var id in options) {
  42849. dialog.appendChild(this.createChoice_(id, options[id].label));
  42850. }
  42851. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42852. container.appendChild(overlay);
  42853. container.appendChild(dialog);
  42854. return container;
  42855. };
  42856. ViewerSelector.prototype.createH1_ = function (name) {
  42857. var h1 = document.createElement('h1');
  42858. var s = h1.style;
  42859. s.color = 'black';
  42860. s.fontSize = '20px';
  42861. s.fontWeight = 'bold';
  42862. s.marginTop = 0;
  42863. s.marginBottom = '24px';
  42864. h1.innerHTML = name;
  42865. return h1;
  42866. };
  42867. ViewerSelector.prototype.createChoice_ = function (id, name) {
  42868. var div = document.createElement('div');
  42869. div.style.marginTop = '8px';
  42870. div.style.color = 'black';
  42871. var input = document.createElement('input');
  42872. input.style.fontSize = '30px';
  42873. input.setAttribute('id', id);
  42874. input.setAttribute('type', 'radio');
  42875. input.setAttribute('value', id);
  42876. input.setAttribute('name', 'field');
  42877. var label = document.createElement('label');
  42878. label.style.marginLeft = '4px';
  42879. label.setAttribute('for', id);
  42880. label.innerHTML = name;
  42881. div.appendChild(input);
  42882. div.appendChild(label);
  42883. return div;
  42884. };
  42885. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  42886. var button = document.createElement('button');
  42887. button.innerHTML = label;
  42888. var s = button.style;
  42889. s.float = 'right';
  42890. s.textTransform = 'uppercase';
  42891. s.color = '#1094f7';
  42892. s.fontSize = '14px';
  42893. s.letterSpacing = 0;
  42894. s.border = 0;
  42895. s.background = 'none';
  42896. s.marginTop = '16px';
  42897. button.addEventListener('click', onclick);
  42898. return button;
  42899. };
  42900. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  42901. function unwrapExports$$1 (x) {
  42902. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  42903. }
  42904. function createCommonjsModule$$1(fn, module) {
  42905. return module = { exports: {} }, fn(module, module.exports), module.exports;
  42906. }
  42907. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  42908. (function webpackUniversalModuleDefinition(root, factory) {
  42909. module.exports = factory();
  42910. })(commonjsGlobal$$1, function() {
  42911. return (function(modules) {
  42912. var installedModules = {};
  42913. function __webpack_require__(moduleId) {
  42914. if(installedModules[moduleId]) {
  42915. return installedModules[moduleId].exports;
  42916. }
  42917. var module = installedModules[moduleId] = {
  42918. i: moduleId,
  42919. l: false,
  42920. exports: {}
  42921. };
  42922. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  42923. module.l = true;
  42924. return module.exports;
  42925. }
  42926. __webpack_require__.m = modules;
  42927. __webpack_require__.c = installedModules;
  42928. __webpack_require__.d = function(exports, name, getter) {
  42929. if(!__webpack_require__.o(exports, name)) {
  42930. Object.defineProperty(exports, name, {
  42931. configurable: false,
  42932. enumerable: true,
  42933. get: getter
  42934. });
  42935. }
  42936. };
  42937. __webpack_require__.n = function(module) {
  42938. var getter = module && module.__esModule ?
  42939. function getDefault() { return module['default']; } :
  42940. function getModuleExports() { return module; };
  42941. __webpack_require__.d(getter, 'a', getter);
  42942. return getter;
  42943. };
  42944. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  42945. __webpack_require__.p = "";
  42946. return __webpack_require__(__webpack_require__.s = 0);
  42947. })
  42948. ([
  42949. (function(module, exports, __webpack_require__) {
  42950. 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; }; }();
  42951. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  42952. var mediaFile = __webpack_require__(1);
  42953. 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;
  42954. var NoSleep = function () {
  42955. function NoSleep() {
  42956. _classCallCheck(this, NoSleep);
  42957. if (oldIOS) {
  42958. this.noSleepTimer = null;
  42959. } else {
  42960. this.noSleepVideo = document.createElement('video');
  42961. this.noSleepVideo.setAttribute('playsinline', '');
  42962. this.noSleepVideo.setAttribute('src', mediaFile);
  42963. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  42964. if (this.noSleepVideo.currentTime > 0.5) {
  42965. this.noSleepVideo.currentTime = Math.random();
  42966. }
  42967. }.bind(this));
  42968. }
  42969. }
  42970. _createClass(NoSleep, [{
  42971. key: 'enable',
  42972. value: function enable() {
  42973. if (oldIOS) {
  42974. this.disable();
  42975. this.noSleepTimer = window.setInterval(function () {
  42976. window.location.href = '/';
  42977. window.setTimeout(window.stop, 0);
  42978. }, 15000);
  42979. } else {
  42980. this.noSleepVideo.play();
  42981. }
  42982. }
  42983. }, {
  42984. key: 'disable',
  42985. value: function disable() {
  42986. if (oldIOS) {
  42987. if (this.noSleepTimer) {
  42988. window.clearInterval(this.noSleepTimer);
  42989. this.noSleepTimer = null;
  42990. }
  42991. } else {
  42992. this.noSleepVideo.pause();
  42993. }
  42994. }
  42995. }]);
  42996. return NoSleep;
  42997. }();
  42998. module.exports = NoSleep;
  42999. }),
  43000. (function(module, exports, __webpack_require__) {
  43001. 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=';
  43002. })
  43003. ]);
  43004. });
  43005. });
  43006. var NoSleep$1 = unwrapExports$$1(NoSleep);
  43007. var nextDisplayId = 1000;
  43008. var defaultLeftBounds = [0, 0, 0.5, 1];
  43009. var defaultRightBounds = [0.5, 0, 0.5, 1];
  43010. var raf = window.requestAnimationFrame;
  43011. var caf = window.cancelAnimationFrame;
  43012. function VRFrameData() {
  43013. this.leftProjectionMatrix = new Float32Array(16);
  43014. this.leftViewMatrix = new Float32Array(16);
  43015. this.rightProjectionMatrix = new Float32Array(16);
  43016. this.rightViewMatrix = new Float32Array(16);
  43017. this.pose = null;
  43018. }
  43019. function VRDisplayCapabilities(config) {
  43020. Object.defineProperties(this, {
  43021. hasPosition: {
  43022. writable: false, enumerable: true, value: config.hasPosition
  43023. },
  43024. hasExternalDisplay: {
  43025. writable: false, enumerable: true, value: config.hasExternalDisplay
  43026. },
  43027. canPresent: {
  43028. writable: false, enumerable: true, value: config.canPresent
  43029. },
  43030. maxLayers: {
  43031. writable: false, enumerable: true, value: config.maxLayers
  43032. },
  43033. hasOrientation: {
  43034. enumerable: true, get: function get() {
  43035. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  43036. return config.hasOrientation;
  43037. }
  43038. }
  43039. });
  43040. }
  43041. function VRDisplay(config) {
  43042. config = config || {};
  43043. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  43044. this.isPolyfilled = true;
  43045. this.displayId = nextDisplayId++;
  43046. this.displayName = '';
  43047. this.depthNear = 0.01;
  43048. this.depthFar = 10000.0;
  43049. this.isPresenting = false;
  43050. Object.defineProperty(this, 'isConnected', {
  43051. get: function get() {
  43052. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  43053. return false;
  43054. }
  43055. });
  43056. this.capabilities = new VRDisplayCapabilities({
  43057. hasPosition: false,
  43058. hasOrientation: false,
  43059. hasExternalDisplay: false,
  43060. canPresent: false,
  43061. maxLayers: 1
  43062. });
  43063. this.stageParameters = null;
  43064. this.waitingForPresent_ = false;
  43065. this.layer_ = null;
  43066. this.originalParent_ = null;
  43067. this.fullscreenElement_ = null;
  43068. this.fullscreenWrapper_ = null;
  43069. this.fullscreenElementCachedStyle_ = null;
  43070. this.fullscreenEventTarget_ = null;
  43071. this.fullscreenChangeHandler_ = null;
  43072. this.fullscreenErrorHandler_ = null;
  43073. if (USE_WAKELOCK && isMobile()) {
  43074. this.wakelock_ = new NoSleep$1();
  43075. }
  43076. }
  43077. VRDisplay.prototype.getFrameData = function (frameData) {
  43078. return frameDataFromPose(frameData, this._getPose(), this);
  43079. };
  43080. VRDisplay.prototype.getPose = function () {
  43081. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  43082. return this._getPose();
  43083. };
  43084. VRDisplay.prototype.resetPose = function () {
  43085. deprecateWarning('VRDisplay.prototype.resetPose');
  43086. return this._resetPose();
  43087. };
  43088. VRDisplay.prototype.getImmediatePose = function () {
  43089. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  43090. return this._getPose();
  43091. };
  43092. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  43093. return raf(callback);
  43094. };
  43095. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  43096. return caf(id);
  43097. };
  43098. VRDisplay.prototype.wrapForFullscreen = function (element) {
  43099. if (isIOS()) {
  43100. return element;
  43101. }
  43102. if (!this.fullscreenWrapper_) {
  43103. this.fullscreenWrapper_ = document.createElement('div');
  43104. 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'];
  43105. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  43106. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  43107. }
  43108. if (this.fullscreenElement_ == element) {
  43109. return this.fullscreenWrapper_;
  43110. }
  43111. if (this.fullscreenElement_) {
  43112. if (this.originalParent_) {
  43113. this.originalParent_.appendChild(this.fullscreenElement_);
  43114. } else {
  43115. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  43116. }
  43117. }
  43118. this.fullscreenElement_ = element;
  43119. this.originalParent_ = element.parentElement;
  43120. if (!this.originalParent_) {
  43121. document.body.appendChild(element);
  43122. }
  43123. if (!this.fullscreenWrapper_.parentElement) {
  43124. var parent = this.fullscreenElement_.parentElement;
  43125. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  43126. parent.removeChild(this.fullscreenElement_);
  43127. }
  43128. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  43129. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  43130. var self = this;
  43131. function applyFullscreenElementStyle() {
  43132. if (!self.fullscreenElement_) {
  43133. return;
  43134. }
  43135. 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'];
  43136. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  43137. }
  43138. applyFullscreenElementStyle();
  43139. return this.fullscreenWrapper_;
  43140. };
  43141. VRDisplay.prototype.removeFullscreenWrapper = function () {
  43142. if (!this.fullscreenElement_) {
  43143. return;
  43144. }
  43145. var element = this.fullscreenElement_;
  43146. if (this.fullscreenElementCachedStyle_) {
  43147. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  43148. } else {
  43149. element.removeAttribute('style');
  43150. }
  43151. this.fullscreenElement_ = null;
  43152. this.fullscreenElementCachedStyle_ = null;
  43153. var parent = this.fullscreenWrapper_.parentElement;
  43154. this.fullscreenWrapper_.removeChild(element);
  43155. if (this.originalParent_ === parent) {
  43156. parent.insertBefore(element, this.fullscreenWrapper_);
  43157. }
  43158. else if (this.originalParent_) {
  43159. this.originalParent_.appendChild(element);
  43160. }
  43161. parent.removeChild(this.fullscreenWrapper_);
  43162. return element;
  43163. };
  43164. VRDisplay.prototype.requestPresent = function (layers) {
  43165. var wasPresenting = this.isPresenting;
  43166. var self = this;
  43167. if (!(layers instanceof Array)) {
  43168. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  43169. layers = [layers];
  43170. }
  43171. return new Promise(function (resolve, reject) {
  43172. if (!self.capabilities.canPresent) {
  43173. reject(new Error('VRDisplay is not capable of presenting.'));
  43174. return;
  43175. }
  43176. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  43177. reject(new Error('Invalid number of layers.'));
  43178. return;
  43179. }
  43180. var incomingLayer = layers[0];
  43181. if (!incomingLayer.source) {
  43182. resolve();
  43183. return;
  43184. }
  43185. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  43186. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  43187. if (wasPresenting) {
  43188. var layer = self.layer_;
  43189. if (layer.source !== incomingLayer.source) {
  43190. layer.source = incomingLayer.source;
  43191. }
  43192. for (var i = 0; i < 4; i++) {
  43193. layer.leftBounds[i] = leftBounds[i];
  43194. layer.rightBounds[i] = rightBounds[i];
  43195. }
  43196. self.wrapForFullscreen(self.layer_.source);
  43197. self.updatePresent_();
  43198. resolve();
  43199. return;
  43200. }
  43201. self.layer_ = {
  43202. predistorted: incomingLayer.predistorted,
  43203. source: incomingLayer.source,
  43204. leftBounds: leftBounds.slice(0),
  43205. rightBounds: rightBounds.slice(0)
  43206. };
  43207. self.waitingForPresent_ = false;
  43208. if (self.layer_ && self.layer_.source) {
  43209. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  43210. var onFullscreenChange = function onFullscreenChange() {
  43211. var actualFullscreenElement = getFullscreenElement();
  43212. self.isPresenting = fullscreenElement === actualFullscreenElement;
  43213. if (self.isPresenting) {
  43214. if (screen.orientation && screen.orientation.lock) {
  43215. screen.orientation.lock('landscape-primary').catch(function (error) {
  43216. console.error('screen.orientation.lock() failed due to', error.message);
  43217. });
  43218. }
  43219. self.waitingForPresent_ = false;
  43220. self.beginPresent_();
  43221. resolve();
  43222. } else {
  43223. if (screen.orientation && screen.orientation.unlock) {
  43224. screen.orientation.unlock();
  43225. }
  43226. self.removeFullscreenWrapper();
  43227. self.disableWakeLock();
  43228. self.endPresent_();
  43229. self.removeFullscreenListeners_();
  43230. }
  43231. self.fireVRDisplayPresentChange_();
  43232. };
  43233. var onFullscreenError = function onFullscreenError() {
  43234. if (!self.waitingForPresent_) {
  43235. return;
  43236. }
  43237. self.removeFullscreenWrapper();
  43238. self.removeFullscreenListeners_();
  43239. self.disableWakeLock();
  43240. self.waitingForPresent_ = false;
  43241. self.isPresenting = false;
  43242. reject(new Error('Unable to present.'));
  43243. };
  43244. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  43245. if (requestFullscreen(fullscreenElement)) {
  43246. self.enableWakeLock();
  43247. self.waitingForPresent_ = true;
  43248. } else if (isIOS() || isWebViewAndroid()) {
  43249. self.enableWakeLock();
  43250. self.isPresenting = true;
  43251. self.beginPresent_();
  43252. self.fireVRDisplayPresentChange_();
  43253. resolve();
  43254. }
  43255. }
  43256. if (!self.waitingForPresent_ && !isIOS()) {
  43257. exitFullscreen();
  43258. reject(new Error('Unable to present.'));
  43259. }
  43260. });
  43261. };
  43262. VRDisplay.prototype.exitPresent = function () {
  43263. var wasPresenting = this.isPresenting;
  43264. var self = this;
  43265. this.isPresenting = false;
  43266. this.layer_ = null;
  43267. this.disableWakeLock();
  43268. return new Promise(function (resolve, reject) {
  43269. if (wasPresenting) {
  43270. if (!exitFullscreen() && isIOS()) {
  43271. self.endPresent_();
  43272. self.fireVRDisplayPresentChange_();
  43273. }
  43274. if (isWebViewAndroid()) {
  43275. self.removeFullscreenWrapper();
  43276. self.removeFullscreenListeners_();
  43277. self.endPresent_();
  43278. self.fireVRDisplayPresentChange_();
  43279. }
  43280. resolve();
  43281. } else {
  43282. reject(new Error('Was not presenting to VRDisplay.'));
  43283. }
  43284. });
  43285. };
  43286. VRDisplay.prototype.getLayers = function () {
  43287. if (this.layer_) {
  43288. return [this.layer_];
  43289. }
  43290. return [];
  43291. };
  43292. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  43293. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  43294. window.dispatchEvent(event);
  43295. };
  43296. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  43297. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  43298. window.dispatchEvent(event);
  43299. };
  43300. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  43301. this.removeFullscreenListeners_();
  43302. this.fullscreenEventTarget_ = element;
  43303. this.fullscreenChangeHandler_ = changeHandler;
  43304. this.fullscreenErrorHandler_ = errorHandler;
  43305. if (changeHandler) {
  43306. if (document.fullscreenEnabled) {
  43307. element.addEventListener('fullscreenchange', changeHandler, false);
  43308. } else if (document.webkitFullscreenEnabled) {
  43309. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  43310. } else if (document.mozFullScreenEnabled) {
  43311. document.addEventListener('mozfullscreenchange', changeHandler, false);
  43312. } else if (document.msFullscreenEnabled) {
  43313. element.addEventListener('msfullscreenchange', changeHandler, false);
  43314. }
  43315. }
  43316. if (errorHandler) {
  43317. if (document.fullscreenEnabled) {
  43318. element.addEventListener('fullscreenerror', errorHandler, false);
  43319. } else if (document.webkitFullscreenEnabled) {
  43320. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  43321. } else if (document.mozFullScreenEnabled) {
  43322. document.addEventListener('mozfullscreenerror', errorHandler, false);
  43323. } else if (document.msFullscreenEnabled) {
  43324. element.addEventListener('msfullscreenerror', errorHandler, false);
  43325. }
  43326. }
  43327. };
  43328. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  43329. if (!this.fullscreenEventTarget_) return;
  43330. var element = this.fullscreenEventTarget_;
  43331. if (this.fullscreenChangeHandler_) {
  43332. var changeHandler = this.fullscreenChangeHandler_;
  43333. element.removeEventListener('fullscreenchange', changeHandler, false);
  43334. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  43335. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  43336. element.removeEventListener('msfullscreenchange', changeHandler, false);
  43337. }
  43338. if (this.fullscreenErrorHandler_) {
  43339. var errorHandler = this.fullscreenErrorHandler_;
  43340. element.removeEventListener('fullscreenerror', errorHandler, false);
  43341. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  43342. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  43343. element.removeEventListener('msfullscreenerror', errorHandler, false);
  43344. }
  43345. this.fullscreenEventTarget_ = null;
  43346. this.fullscreenChangeHandler_ = null;
  43347. this.fullscreenErrorHandler_ = null;
  43348. };
  43349. VRDisplay.prototype.enableWakeLock = function () {
  43350. if (this.wakelock_) {
  43351. this.wakelock_.enable();
  43352. }
  43353. };
  43354. VRDisplay.prototype.disableWakeLock = function () {
  43355. if (this.wakelock_) {
  43356. this.wakelock_.disable();
  43357. }
  43358. };
  43359. VRDisplay.prototype.beginPresent_ = function () {
  43360. };
  43361. VRDisplay.prototype.endPresent_ = function () {
  43362. };
  43363. VRDisplay.prototype.submitFrame = function (pose) {
  43364. };
  43365. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  43366. return null;
  43367. };
  43368. var config = {
  43369. ADDITIONAL_VIEWERS: [],
  43370. DEFAULT_VIEWER: '',
  43371. MOBILE_WAKE_LOCK: true,
  43372. DEBUG: false,
  43373. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43374. K_FILTER: 0.98,
  43375. PREDICTION_TIME_S: 0.040,
  43376. CARDBOARD_UI_DISABLED: false,
  43377. ROTATE_INSTRUCTIONS_DISABLED: false,
  43378. YAW_ONLY: false,
  43379. BUFFER_SCALE: 0.5,
  43380. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43381. };
  43382. var Eye = {
  43383. LEFT: 'left',
  43384. RIGHT: 'right'
  43385. };
  43386. function CardboardVRDisplay(config$$1) {
  43387. var defaults = extend({}, config);
  43388. config$$1 = extend(defaults, config$$1 || {});
  43389. VRDisplay.call(this, {
  43390. wakelock: config$$1.MOBILE_WAKE_LOCK
  43391. });
  43392. this.config = config$$1;
  43393. this.displayName = 'Cardboard VRDisplay';
  43394. this.capabilities = new VRDisplayCapabilities({
  43395. hasPosition: false,
  43396. hasOrientation: true,
  43397. hasExternalDisplay: false,
  43398. canPresent: true,
  43399. maxLayers: 1
  43400. });
  43401. this.stageParameters = null;
  43402. this.bufferScale_ = this.config.BUFFER_SCALE;
  43403. this.poseSensor_ = new PoseSensor(this.config);
  43404. this.distorter_ = null;
  43405. this.cardboardUI_ = null;
  43406. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  43407. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  43408. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  43409. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  43410. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  43411. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  43412. this.rotateInstructions_ = new RotateInstructions();
  43413. }
  43414. if (isIOS()) {
  43415. window.addEventListener('resize', this.onResize_.bind(this));
  43416. }
  43417. }
  43418. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  43419. CardboardVRDisplay.prototype._getPose = function () {
  43420. return {
  43421. position: null,
  43422. orientation: this.poseSensor_.getOrientation(),
  43423. linearVelocity: null,
  43424. linearAcceleration: null,
  43425. angularVelocity: null,
  43426. angularAcceleration: null
  43427. };
  43428. };
  43429. CardboardVRDisplay.prototype._resetPose = function () {
  43430. if (this.poseSensor_.resetPose) {
  43431. this.poseSensor_.resetPose();
  43432. }
  43433. };
  43434. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  43435. var fieldOfView;
  43436. if (whichEye == Eye.LEFT) {
  43437. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  43438. } else if (whichEye == Eye.RIGHT) {
  43439. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  43440. } else {
  43441. console.error('Invalid eye provided: %s', whichEye);
  43442. return null;
  43443. }
  43444. return fieldOfView;
  43445. };
  43446. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  43447. var offset;
  43448. if (whichEye == Eye.LEFT) {
  43449. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43450. } else if (whichEye == Eye.RIGHT) {
  43451. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43452. } else {
  43453. console.error('Invalid eye provided: %s', whichEye);
  43454. return null;
  43455. }
  43456. return offset;
  43457. };
  43458. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  43459. var offset = this._getEyeOffset(whichEye);
  43460. var fieldOfView = this._getFieldOfView(whichEye);
  43461. var eyeParams = {
  43462. offset: offset,
  43463. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  43464. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  43465. };
  43466. Object.defineProperty(eyeParams, 'fieldOfView', {
  43467. enumerable: true,
  43468. get: function get() {
  43469. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  43470. return fieldOfView;
  43471. }
  43472. });
  43473. return eyeParams;
  43474. };
  43475. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  43476. if (this.config.DEBUG) {
  43477. console.log('DPDB reported that device params were updated.');
  43478. }
  43479. this.deviceInfo_.updateDeviceParams(newParams);
  43480. if (this.distorter_) {
  43481. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43482. }
  43483. };
  43484. CardboardVRDisplay.prototype.updateBounds_ = function () {
  43485. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  43486. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  43487. }
  43488. };
  43489. CardboardVRDisplay.prototype.beginPresent_ = function () {
  43490. var gl = this.layer_.source.getContext('webgl');
  43491. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43492. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43493. if (!gl) return;
  43494. if (this.layer_.predistorted) {
  43495. if (!this.config.CARDBOARD_UI_DISABLED) {
  43496. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  43497. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  43498. this.cardboardUI_ = new CardboardUI(gl);
  43499. }
  43500. } else {
  43501. if (!this.config.CARDBOARD_UI_DISABLED) {
  43502. this.cardboardUI_ = new CardboardUI(gl);
  43503. }
  43504. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  43505. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43506. }
  43507. if (this.cardboardUI_) {
  43508. this.cardboardUI_.listen(function (e) {
  43509. this.viewerSelector_.show(this.layer_.source.parentElement);
  43510. e.stopPropagation();
  43511. e.preventDefault();
  43512. }.bind(this), function (e) {
  43513. this.exitPresent();
  43514. e.stopPropagation();
  43515. e.preventDefault();
  43516. }.bind(this));
  43517. }
  43518. if (this.rotateInstructions_) {
  43519. if (isLandscapeMode() && isMobile()) {
  43520. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  43521. } else {
  43522. this.rotateInstructions_.update();
  43523. }
  43524. }
  43525. this.orientationHandler = this.onOrientationChange_.bind(this);
  43526. window.addEventListener('orientationchange', this.orientationHandler);
  43527. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  43528. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43529. this.fireVRDisplayDeviceParamsChange_();
  43530. };
  43531. CardboardVRDisplay.prototype.endPresent_ = function () {
  43532. if (this.distorter_) {
  43533. this.distorter_.destroy();
  43534. this.distorter_ = null;
  43535. }
  43536. if (this.cardboardUI_) {
  43537. this.cardboardUI_.destroy();
  43538. this.cardboardUI_ = null;
  43539. }
  43540. if (this.rotateInstructions_) {
  43541. this.rotateInstructions_.hide();
  43542. }
  43543. this.viewerSelector_.hide();
  43544. window.removeEventListener('orientationchange', this.orientationHandler);
  43545. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43546. };
  43547. CardboardVRDisplay.prototype.updatePresent_ = function () {
  43548. this.endPresent_();
  43549. this.beginPresent_();
  43550. };
  43551. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  43552. if (this.distorter_) {
  43553. this.updateBounds_();
  43554. this.distorter_.submitFrame();
  43555. } else if (this.cardboardUI_ && this.layer_) {
  43556. var gl = this.layer_.source.getContext('webgl');
  43557. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43558. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43559. var canvas = gl.canvas;
  43560. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  43561. this.cardboardUI_.onResize();
  43562. }
  43563. this.lastWidth = canvas.width;
  43564. this.lastHeight = canvas.height;
  43565. this.cardboardUI_.render();
  43566. }
  43567. };
  43568. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  43569. this.viewerSelector_.hide();
  43570. if (this.rotateInstructions_) {
  43571. this.rotateInstructions_.update();
  43572. }
  43573. this.onResize_();
  43574. };
  43575. CardboardVRDisplay.prototype.onResize_ = function (e) {
  43576. if (this.layer_) {
  43577. var gl = this.layer_.source.getContext('webgl');
  43578. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43579. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43580. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  43581. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  43582. 'padding: 0px', 'box-sizing: content-box'];
  43583. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  43584. safariCssSizeWorkaround(gl.canvas);
  43585. }
  43586. };
  43587. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  43588. this.deviceInfo_.setViewer(viewer);
  43589. if (this.distorter_) {
  43590. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43591. }
  43592. this.fireVRDisplayDeviceParamsChange_();
  43593. };
  43594. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  43595. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  43596. detail: {
  43597. vrdisplay: this,
  43598. deviceInfo: this.deviceInfo_
  43599. }
  43600. });
  43601. window.dispatchEvent(event);
  43602. };
  43603. CardboardVRDisplay.VRFrameData = VRFrameData;
  43604. CardboardVRDisplay.VRDisplay = VRDisplay;
  43605. return CardboardVRDisplay;
  43606. })));
  43607. });
  43608. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  43609. var version = "0.10.12";
  43610. var DefaultConfig = {
  43611. ADDITIONAL_VIEWERS: [],
  43612. DEFAULT_VIEWER: '',
  43613. PROVIDE_MOBILE_VRDISPLAY: true,
  43614. MOBILE_WAKE_LOCK: true,
  43615. DEBUG: false,
  43616. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43617. K_FILTER: 0.98,
  43618. PREDICTION_TIME_S: 0.040,
  43619. CARDBOARD_UI_DISABLED: false,
  43620. ROTATE_INSTRUCTIONS_DISABLED: false,
  43621. YAW_ONLY: false,
  43622. BUFFER_SCALE: 0.5,
  43623. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43624. };
  43625. function WebVRPolyfill(config) {
  43626. this.config = extend(extend({}, DefaultConfig), config);
  43627. this.polyfillDisplays = [];
  43628. this.enabled = false;
  43629. this.hasNative = 'getVRDisplays' in navigator;
  43630. this.native = {};
  43631. this.native.getVRDisplays = navigator.getVRDisplays;
  43632. this.native.VRFrameData = window.VRFrameData;
  43633. this.native.VRDisplay = window.VRDisplay;
  43634. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  43635. this.enable();
  43636. this.getVRDisplays().then(function (displays) {
  43637. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  43638. displays[0].fireVRDisplayConnect_();
  43639. }
  43640. });
  43641. }
  43642. }
  43643. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  43644. if (this._polyfillDisplaysPopulated) {
  43645. return this.polyfillDisplays;
  43646. }
  43647. if (isMobile()) {
  43648. var vrDisplay = new CardboardVRDisplay({
  43649. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  43650. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  43651. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  43652. DEBUG: this.config.DEBUG,
  43653. DPDB_URL: this.config.DPDB_URL,
  43654. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  43655. K_FILTER: this.config.K_FILTER,
  43656. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  43657. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  43658. YAW_ONLY: this.config.YAW_ONLY,
  43659. BUFFER_SCALE: this.config.BUFFER_SCALE,
  43660. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  43661. });
  43662. this.polyfillDisplays.push(vrDisplay);
  43663. }
  43664. this._polyfillDisplaysPopulated = true;
  43665. return this.polyfillDisplays;
  43666. };
  43667. WebVRPolyfill.prototype.enable = function () {
  43668. this.enabled = true;
  43669. if (this.hasNative && this.native.VRFrameData) {
  43670. var NativeVRFrameData = this.native.VRFrameData;
  43671. var nativeFrameData = new this.native.VRFrameData();
  43672. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  43673. window.VRDisplay.prototype.getFrameData = function (frameData) {
  43674. if (frameData instanceof NativeVRFrameData) {
  43675. nativeGetFrameData.call(this, frameData);
  43676. return;
  43677. }
  43678. nativeGetFrameData.call(this, nativeFrameData);
  43679. frameData.pose = nativeFrameData.pose;
  43680. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  43681. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  43682. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  43683. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  43684. };
  43685. }
  43686. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  43687. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  43688. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  43689. };
  43690. WebVRPolyfill.prototype.getVRDisplays = function () {
  43691. var _this = this;
  43692. var config = this.config;
  43693. if (!this.hasNative) {
  43694. return Promise.resolve(this.getPolyfillDisplays());
  43695. }
  43696. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  43697. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  43698. });
  43699. };
  43700. WebVRPolyfill.version = version;
  43701. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  43702. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  43703. var webvrPolyfill = Object.freeze({
  43704. default: WebVRPolyfill
  43705. });
  43706. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  43707. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  43708. if (!commonjsGlobal.document) {
  43709. commonjsGlobal.document = commonjsGlobal.window.document;
  43710. }
  43711. if (!commonjsGlobal.navigator) {
  43712. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  43713. }
  43714. }
  43715. var src = require$$0;
  43716. return src;
  43717. })));
  43718. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43719. },{}],68:[function(_dereq_,module,exports){
  43720. var newline = /\n/
  43721. var newlineChar = '\n'
  43722. var whitespace = /\s/
  43723. module.exports = function(text, opt) {
  43724. var lines = module.exports.lines(text, opt)
  43725. return lines.map(function(line) {
  43726. return text.substring(line.start, line.end)
  43727. }).join('\n')
  43728. }
  43729. module.exports.lines = function wordwrap(text, opt) {
  43730. opt = opt||{}
  43731. //zero width results in nothing visible
  43732. if (opt.width === 0 && opt.mode !== 'nowrap')
  43733. return []
  43734. text = text||''
  43735. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  43736. var start = Math.max(0, opt.start||0)
  43737. var end = typeof opt.end === 'number' ? opt.end : text.length
  43738. var mode = opt.mode
  43739. var measure = opt.measure || monospace
  43740. if (mode === 'pre')
  43741. return pre(measure, text, start, end, width)
  43742. else
  43743. return greedy(measure, text, start, end, width, mode)
  43744. }
  43745. function idxOf(text, chr, start, end) {
  43746. var idx = text.indexOf(chr, start)
  43747. if (idx === -1 || idx > end)
  43748. return end
  43749. return idx
  43750. }
  43751. function isWhitespace(chr) {
  43752. return whitespace.test(chr)
  43753. }
  43754. function pre(measure, text, start, end, width) {
  43755. var lines = []
  43756. var lineStart = start
  43757. for (var i=start; i<end && i<text.length; i++) {
  43758. var chr = text.charAt(i)
  43759. var isNewline = newline.test(chr)
  43760. //If we've reached a newline, then step down a line
  43761. //Or if we've reached the EOF
  43762. if (isNewline || i===end-1) {
  43763. var lineEnd = isNewline ? i : i+1
  43764. var measured = measure(text, lineStart, lineEnd, width)
  43765. lines.push(measured)
  43766. lineStart = i+1
  43767. }
  43768. }
  43769. return lines
  43770. }
  43771. function greedy(measure, text, start, end, width, mode) {
  43772. //A greedy word wrapper based on LibGDX algorithm
  43773. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  43774. var lines = []
  43775. var testWidth = width
  43776. //if 'nowrap' is specified, we only wrap on newline chars
  43777. if (mode === 'nowrap')
  43778. testWidth = Number.MAX_VALUE
  43779. while (start < end && start < text.length) {
  43780. //get next newline position
  43781. var newLine = idxOf(text, newlineChar, start, end)
  43782. //eat whitespace at start of line
  43783. while (start < newLine) {
  43784. if (!isWhitespace( text.charAt(start) ))
  43785. break
  43786. start++
  43787. }
  43788. //determine visible # of glyphs for the available width
  43789. var measured = measure(text, start, newLine, testWidth)
  43790. var lineEnd = start + (measured.end-measured.start)
  43791. var nextStart = lineEnd + newlineChar.length
  43792. //if we had to cut the line before the next newline...
  43793. if (lineEnd < newLine) {
  43794. //find char to break on
  43795. while (lineEnd > start) {
  43796. if (isWhitespace(text.charAt(lineEnd)))
  43797. break
  43798. lineEnd--
  43799. }
  43800. if (lineEnd === start) {
  43801. if (nextStart > start + newlineChar.length) nextStart--
  43802. lineEnd = nextStart // If no characters to break, show all.
  43803. } else {
  43804. nextStart = lineEnd
  43805. //eat whitespace at end of line
  43806. while (lineEnd > start) {
  43807. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  43808. break
  43809. lineEnd--
  43810. }
  43811. }
  43812. }
  43813. if (lineEnd >= start) {
  43814. var result = measure(text, start, lineEnd, testWidth)
  43815. lines.push(result)
  43816. }
  43817. start = nextStart
  43818. }
  43819. return lines
  43820. }
  43821. //determines the visible number of glyphs within a given width
  43822. function monospace(text, start, end, width) {
  43823. var glyphs = Math.min(width, end-start)
  43824. return {
  43825. start: start,
  43826. end: start+glyphs
  43827. }
  43828. }
  43829. },{}],69:[function(_dereq_,module,exports){
  43830. "use strict";
  43831. var window = _dereq_("global/window")
  43832. var isFunction = _dereq_("is-function")
  43833. var parseHeaders = _dereq_("parse-headers")
  43834. var xtend = _dereq_("xtend")
  43835. module.exports = createXHR
  43836. // Allow use of default import syntax in TypeScript
  43837. module.exports.default = createXHR;
  43838. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  43839. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  43840. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  43841. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  43842. options = initParams(uri, options, callback)
  43843. options.method = method.toUpperCase()
  43844. return _createXHR(options)
  43845. }
  43846. })
  43847. function forEachArray(array, iterator) {
  43848. for (var i = 0; i < array.length; i++) {
  43849. iterator(array[i])
  43850. }
  43851. }
  43852. function isEmpty(obj){
  43853. for(var i in obj){
  43854. if(obj.hasOwnProperty(i)) return false
  43855. }
  43856. return true
  43857. }
  43858. function initParams(uri, options, callback) {
  43859. var params = uri
  43860. if (isFunction(options)) {
  43861. callback = options
  43862. if (typeof uri === "string") {
  43863. params = {uri:uri}
  43864. }
  43865. } else {
  43866. params = xtend(options, {uri: uri})
  43867. }
  43868. params.callback = callback
  43869. return params
  43870. }
  43871. function createXHR(uri, options, callback) {
  43872. options = initParams(uri, options, callback)
  43873. return _createXHR(options)
  43874. }
  43875. function _createXHR(options) {
  43876. if(typeof options.callback === "undefined"){
  43877. throw new Error("callback argument missing")
  43878. }
  43879. var called = false
  43880. var callback = function cbOnce(err, response, body){
  43881. if(!called){
  43882. called = true
  43883. options.callback(err, response, body)
  43884. }
  43885. }
  43886. function readystatechange() {
  43887. if (xhr.readyState === 4) {
  43888. setTimeout(loadFunc, 0)
  43889. }
  43890. }
  43891. function getBody() {
  43892. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  43893. var body = undefined
  43894. if (xhr.response) {
  43895. body = xhr.response
  43896. } else {
  43897. body = xhr.responseText || getXml(xhr)
  43898. }
  43899. if (isJson) {
  43900. try {
  43901. body = JSON.parse(body)
  43902. } catch (e) {}
  43903. }
  43904. return body
  43905. }
  43906. function errorFunc(evt) {
  43907. clearTimeout(timeoutTimer)
  43908. if(!(evt instanceof Error)){
  43909. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  43910. }
  43911. evt.statusCode = 0
  43912. return callback(evt, failureResponse)
  43913. }
  43914. // will load the data & process the response in a special response object
  43915. function loadFunc() {
  43916. if (aborted) return
  43917. var status
  43918. clearTimeout(timeoutTimer)
  43919. if(options.useXDR && xhr.status===undefined) {
  43920. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  43921. status = 200
  43922. } else {
  43923. status = (xhr.status === 1223 ? 204 : xhr.status)
  43924. }
  43925. var response = failureResponse
  43926. var err = null
  43927. if (status !== 0){
  43928. response = {
  43929. body: getBody(),
  43930. statusCode: status,
  43931. method: method,
  43932. headers: {},
  43933. url: uri,
  43934. rawRequest: xhr
  43935. }
  43936. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  43937. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  43938. }
  43939. } else {
  43940. err = new Error("Internal XMLHttpRequest Error")
  43941. }
  43942. return callback(err, response, response.body)
  43943. }
  43944. var xhr = options.xhr || null
  43945. if (!xhr) {
  43946. if (options.cors || options.useXDR) {
  43947. xhr = new createXHR.XDomainRequest()
  43948. }else{
  43949. xhr = new createXHR.XMLHttpRequest()
  43950. }
  43951. }
  43952. var key
  43953. var aborted
  43954. var uri = xhr.url = options.uri || options.url
  43955. var method = xhr.method = options.method || "GET"
  43956. var body = options.body || options.data
  43957. var headers = xhr.headers = options.headers || {}
  43958. var sync = !!options.sync
  43959. var isJson = false
  43960. var timeoutTimer
  43961. var failureResponse = {
  43962. body: undefined,
  43963. headers: {},
  43964. statusCode: 0,
  43965. method: method,
  43966. url: uri,
  43967. rawRequest: xhr
  43968. }
  43969. if ("json" in options && options.json !== false) {
  43970. isJson = true
  43971. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  43972. if (method !== "GET" && method !== "HEAD") {
  43973. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  43974. body = JSON.stringify(options.json === true ? body : options.json)
  43975. }
  43976. }
  43977. xhr.onreadystatechange = readystatechange
  43978. xhr.onload = loadFunc
  43979. xhr.onerror = errorFunc
  43980. // IE9 must have onprogress be set to a unique function.
  43981. xhr.onprogress = function () {
  43982. // IE must die
  43983. }
  43984. xhr.onabort = function(){
  43985. aborted = true;
  43986. }
  43987. xhr.ontimeout = errorFunc
  43988. xhr.open(method, uri, !sync, options.username, options.password)
  43989. //has to be after open
  43990. if(!sync) {
  43991. xhr.withCredentials = !!options.withCredentials
  43992. }
  43993. // Cannot set timeout with sync request
  43994. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  43995. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  43996. if (!sync && options.timeout > 0 ) {
  43997. timeoutTimer = setTimeout(function(){
  43998. if (aborted) return
  43999. aborted = true//IE9 may still call readystatechange
  44000. xhr.abort("timeout")
  44001. var e = new Error("XMLHttpRequest timeout")
  44002. e.code = "ETIMEDOUT"
  44003. errorFunc(e)
  44004. }, options.timeout )
  44005. }
  44006. if (xhr.setRequestHeader) {
  44007. for(key in headers){
  44008. if(headers.hasOwnProperty(key)){
  44009. xhr.setRequestHeader(key, headers[key])
  44010. }
  44011. }
  44012. } else if (options.headers && !isEmpty(options.headers)) {
  44013. throw new Error("Headers cannot be set on an XDomainRequest object")
  44014. }
  44015. if ("responseType" in options) {
  44016. xhr.responseType = options.responseType
  44017. }
  44018. if ("beforeSend" in options &&
  44019. typeof options.beforeSend === "function"
  44020. ) {
  44021. options.beforeSend(xhr)
  44022. }
  44023. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  44024. // XMLHttpRequest spec says to pass null as body to indicate no body
  44025. // See https://github.com/naugtur/xhr/issues/100.
  44026. xhr.send(body || null)
  44027. return xhr
  44028. }
  44029. function getXml(xhr) {
  44030. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  44031. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  44032. try {
  44033. if (xhr.responseType === "document") {
  44034. return xhr.responseXML
  44035. }
  44036. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  44037. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  44038. return xhr.responseXML
  44039. }
  44040. } catch (e) {}
  44041. return null
  44042. }
  44043. function noop() {}
  44044. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":71}],70:[function(_dereq_,module,exports){
  44045. module.exports = (function xmlparser() {
  44046. //common browsers
  44047. if (typeof self.DOMParser !== 'undefined') {
  44048. return function(str) {
  44049. var parser = new self.DOMParser()
  44050. return parser.parseFromString(str, 'application/xml')
  44051. }
  44052. }
  44053. //IE8 fallback
  44054. if (typeof self.ActiveXObject !== 'undefined'
  44055. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  44056. return function(str) {
  44057. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  44058. xmlDoc.async = "false"
  44059. xmlDoc.loadXML(str)
  44060. return xmlDoc
  44061. }
  44062. }
  44063. //last resort fallback
  44064. return function(str) {
  44065. var div = document.createElement('div')
  44066. div.innerHTML = str
  44067. return div
  44068. }
  44069. })()
  44070. },{}],71:[function(_dereq_,module,exports){
  44071. module.exports = extend
  44072. var hasOwnProperty = Object.prototype.hasOwnProperty;
  44073. function extend() {
  44074. var target = {}
  44075. for (var i = 0; i < arguments.length; i++) {
  44076. var source = arguments[i]
  44077. for (var key in source) {
  44078. if (hasOwnProperty.call(source, key)) {
  44079. target[key] = source[key]
  44080. }
  44081. }
  44082. }
  44083. return target
  44084. }
  44085. },{}],72:[function(_dereq_,module,exports){
  44086. module.exports={
  44087. "name": "aframe",
  44088. "version": "1.0.4",
  44089. "description": "A web framework for building virtual reality experiences.",
  44090. "homepage": "https://aframe.io/",
  44091. "main": "dist/aframe-master.js",
  44092. "scripts": {
  44093. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  44094. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  44095. "codecov": "codecov",
  44096. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  44097. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  44098. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  44099. "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",
  44100. "docs": "markserv --dir docs --port 9001",
  44101. "preghpages": "node ./scripts/preghpages.js",
  44102. "ghpages": "ghpages -p gh-pages/",
  44103. "lint": "semistandard -v | snazzy",
  44104. "lint:fix": "semistandard --fix",
  44105. "precommit": "npm run lint",
  44106. "prepush": "node scripts/testOnlyCheck.js",
  44107. "prerelease": "node scripts/release.js 1.0.3 1.0.4",
  44108. "start": "npm run dev",
  44109. "start:https": "cross-env SSL=true npm run dev",
  44110. "test": "karma start ./tests/karma.conf.js",
  44111. "test:docs": "node scripts/docsLint.js",
  44112. "test:firefox": "npm test -- --browsers Firefox",
  44113. "test:chrome": "npm test -- --browsers Chrome",
  44114. "test:nobrowser": "NO_BROWSER=true npm test",
  44115. "test:node": "mocha --ui tdd tests/node"
  44116. },
  44117. "repository": "aframevr/aframe",
  44118. "license": "MIT",
  44119. "files": [
  44120. "dist/*",
  44121. "docs/**/*",
  44122. "src/**/*",
  44123. "vendor/**/*"
  44124. ],
  44125. "dependencies": {
  44126. "custom-event-polyfill": "^1.0.6",
  44127. "debug": "ngokevin/debug#noTimestamp",
  44128. "deep-assign": "^2.0.0",
  44129. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  44130. "load-bmfont": "^1.2.3",
  44131. "object-assign": "^4.0.1",
  44132. "present": "0.0.6",
  44133. "promise-polyfill": "^3.1.0",
  44134. "super-animejs": "^3.1.0",
  44135. "super-three": "^0.119.0",
  44136. "three-bmfont-text": "dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e",
  44137. "webvr-polyfill": "^0.10.12"
  44138. },
  44139. "devDependencies": {
  44140. "browserify": "^13.1.0",
  44141. "browserify-css": "^0.8.4",
  44142. "browserify-derequire": "^0.9.4",
  44143. "browserify-istanbul": "^2.0.0",
  44144. "budo": "^9.2.0",
  44145. "chai": "^3.5.0",
  44146. "chai-shallow-deep-equal": "^1.4.0",
  44147. "chalk": "^1.1.3",
  44148. "codecov": "^1.0.1",
  44149. "cross-env": "^5.0.1",
  44150. "envify": "^3.4.1",
  44151. "exorcist": "^0.4.0",
  44152. "ghpages": "0.0.8",
  44153. "git-rev": "^0.2.1",
  44154. "glob": "^7.1.1",
  44155. "husky": "^0.11.7",
  44156. "istanbul": "^0.4.5",
  44157. "jsdom": "^9.11.0",
  44158. "karma": "1.4.1",
  44159. "karma-browserify": "^5.1.0",
  44160. "karma-chai-shallow-deep-equal": "0.0.4",
  44161. "karma-chrome-launcher": "^2.0.0",
  44162. "karma-coverage": "^1.1.1",
  44163. "karma-env-preprocessor": "^0.1.1",
  44164. "karma-firefox-launcher": "^1.2.0",
  44165. "karma-mocha": "^1.1.1",
  44166. "karma-mocha-reporter": "^2.1.0",
  44167. "karma-sinon-chai": "1.2.4",
  44168. "lolex": "^1.5.1",
  44169. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  44170. "minifyify": "^7.3.3",
  44171. "mocha": "^3.0.2",
  44172. "mozilla-download": "^1.1.1",
  44173. "replace-in-file": "^2.5.3",
  44174. "semistandard": "^9.0.0",
  44175. "shelljs": "^0.7.7",
  44176. "shx": "^0.2.2",
  44177. "sinon": "^1.17.5",
  44178. "sinon-chai": "2.8.0",
  44179. "snazzy": "^5.0.0",
  44180. "too-wordy": "ngokevin/too-wordy",
  44181. "uglifyjs": "^2.4.10",
  44182. "write-good": "^0.9.1"
  44183. },
  44184. "link": true,
  44185. "browserify": {
  44186. "transform": [
  44187. "browserify-css",
  44188. "envify"
  44189. ]
  44190. },
  44191. "semistandard": {
  44192. "ignore": [
  44193. "build/**",
  44194. "dist/**",
  44195. "examples/**/shaders/*.js",
  44196. "**/vendor/**"
  44197. ]
  44198. },
  44199. "keywords": [
  44200. "3d",
  44201. "aframe",
  44202. "cardboard",
  44203. "components",
  44204. "oculus",
  44205. "three",
  44206. "three.js",
  44207. "rift",
  44208. "vive",
  44209. "vr",
  44210. "web-components",
  44211. "webvr"
  44212. ],
  44213. "browserify-css": {
  44214. "minify": true
  44215. },
  44216. "engines": {
  44217. "node": ">= 4.6.0",
  44218. "npm": "^2.15.9"
  44219. }
  44220. }
  44221. },{}],73:[function(_dereq_,module,exports){
  44222. var anime = _dereq_('super-animejs');
  44223. var components = _dereq_('../core/component').components;
  44224. var registerComponent = _dereq_('../core/component').registerComponent;
  44225. var THREE = _dereq_('../lib/three');
  44226. var utils = _dereq_('../utils');
  44227. var colorHelperFrom = new THREE.Color();
  44228. var colorHelperTo = new THREE.Color();
  44229. var getComponentProperty = utils.entity.getComponentProperty;
  44230. var setComponentProperty = utils.entity.setComponentProperty;
  44231. var splitCache = {};
  44232. var TYPE_COLOR = 'color';
  44233. var PROP_POSITION = 'position';
  44234. var PROP_ROTATION = 'rotation';
  44235. var PROP_SCALE = 'scale';
  44236. var STRING_COMPONENTS = 'components';
  44237. var STRING_OBJECT3D = 'object3D';
  44238. /**
  44239. * Animation component for A-Frame using anime.js.
  44240. *
  44241. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  44242. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  44243. * boolean * flag * `isAnimationPlaying`.
  44244. *
  44245. * anime.js animation config for tweenining Javascript objects and values works as:
  44246. *
  44247. * config = {
  44248. * targets: {foo: 0.0, bar: '#000'},
  44249. * foo: 1.0,
  44250. * bar: '#FFF'
  44251. * }
  44252. *
  44253. * The above will tween each property in `targets`. The `to` values are set in the root of
  44254. * the config.
  44255. *
  44256. * @member {object} animation - anime.js instance.
  44257. * @member {boolean} animationIsPlaying - Control if animation is playing.
  44258. */
  44259. module.exports.Component = registerComponent('animation', {
  44260. schema: {
  44261. autoplay: {default: true},
  44262. delay: {default: 0},
  44263. dir: {default: ''},
  44264. dur: {default: 1000},
  44265. easing: {default: 'easeInQuad'},
  44266. elasticity: {default: 400},
  44267. enabled: {default: true},
  44268. from: {default: ''},
  44269. loop: {
  44270. default: 0,
  44271. parse: function (value) {
  44272. // Boolean or integer.
  44273. if (value === true || value === 'true') { return true; }
  44274. if (value === false || value === 'false') { return false; }
  44275. return parseInt(value, 10);
  44276. }
  44277. },
  44278. property: {default: ''},
  44279. startEvents: {type: 'array'},
  44280. pauseEvents: {type: 'array'},
  44281. resumeEvents: {type: 'array'},
  44282. round: {default: false},
  44283. to: {default: ''},
  44284. type: {default: ''},
  44285. isRawProperty: {default: false}
  44286. },
  44287. multiple: true,
  44288. init: function () {
  44289. var self = this;
  44290. this.eventDetail = {name: this.attrName};
  44291. this.time = 0;
  44292. this.animation = null;
  44293. this.animationIsPlaying = false;
  44294. this.onStartEvent = this.onStartEvent.bind(this);
  44295. this.beginAnimation = this.beginAnimation.bind(this);
  44296. this.pauseAnimation = this.pauseAnimation.bind(this);
  44297. this.resumeAnimation = this.resumeAnimation.bind(this);
  44298. this.fromColor = {};
  44299. this.toColor = {};
  44300. this.targets = {};
  44301. this.targetsArray = [];
  44302. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  44303. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  44304. this.config = {
  44305. complete: function () {
  44306. self.animationIsPlaying = false;
  44307. self.el.emit('animationcomplete', self.eventDetail, false);
  44308. if (self.id) {
  44309. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  44310. }
  44311. }
  44312. };
  44313. },
  44314. update: function (oldData) {
  44315. var config = this.config;
  44316. var data = this.data;
  44317. this.animationIsPlaying = false;
  44318. if (!this.data.enabled) { return; }
  44319. if (!data.property) { return; }
  44320. // Base config.
  44321. config.autoplay = false;
  44322. config.direction = data.dir;
  44323. config.duration = data.dur;
  44324. config.easing = data.easing;
  44325. config.elasticity = data.elasticity;
  44326. config.loop = data.loop;
  44327. config.round = data.round;
  44328. // Start new animation.
  44329. this.createAndStartAnimation();
  44330. },
  44331. tick: function (t, dt) {
  44332. if (!this.animationIsPlaying) { return; }
  44333. this.time += dt;
  44334. this.animation.tick(this.time);
  44335. },
  44336. remove: function () {
  44337. this.pauseAnimation();
  44338. this.removeEventListeners();
  44339. },
  44340. pause: function () {
  44341. this.paused = true;
  44342. this.pausedWasPlaying = this.animationIsPlaying;
  44343. this.pauseAnimation();
  44344. this.removeEventListeners();
  44345. },
  44346. /**
  44347. * `play` handler only for resuming scene.
  44348. */
  44349. play: function () {
  44350. if (!this.paused) { return; }
  44351. this.paused = false;
  44352. this.addEventListeners();
  44353. if (this.pausedWasPlaying) {
  44354. this.resumeAnimation();
  44355. this.pausedWasPlaying = false;
  44356. }
  44357. },
  44358. /**
  44359. * Start animation from scratch.
  44360. */
  44361. createAndStartAnimation: function () {
  44362. var data = this.data;
  44363. this.updateConfig();
  44364. this.animationIsPlaying = false;
  44365. this.animation = anime(this.config);
  44366. this.animation.began = true;
  44367. this.removeEventListeners();
  44368. this.addEventListeners();
  44369. // Wait for start events for animation.
  44370. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  44371. // Delay animation.
  44372. if (data.delay) {
  44373. setTimeout(this.beginAnimation, data.delay);
  44374. return;
  44375. }
  44376. // Play animation.
  44377. this.beginAnimation();
  44378. },
  44379. /**
  44380. * This is before animation start (including from startEvents).
  44381. * Set to initial state (config.from, time = 0, seekTime = 0).
  44382. */
  44383. beginAnimation: function () {
  44384. this.updateConfig();
  44385. this.animation.began = true;
  44386. this.time = 0;
  44387. this.animationIsPlaying = true;
  44388. this.stopRelatedAnimations();
  44389. this.el.emit('animationbegin', this.eventDetail, false);
  44390. },
  44391. pauseAnimation: function () {
  44392. this.animationIsPlaying = false;
  44393. },
  44394. resumeAnimation: function () {
  44395. this.animationIsPlaying = true;
  44396. },
  44397. /**
  44398. * startEvents callback.
  44399. */
  44400. onStartEvent: function () {
  44401. if (!this.data.enabled) { return; }
  44402. this.updateConfig();
  44403. if (this.animation) {
  44404. this.animation.pause();
  44405. }
  44406. this.animation = anime(this.config);
  44407. // Include the delay before each start event.
  44408. if (this.data.delay) {
  44409. setTimeout(this.beginAnimation, this.data.delay);
  44410. return;
  44411. }
  44412. this.beginAnimation();
  44413. },
  44414. /**
  44415. * rawProperty: true and type: color;
  44416. */
  44417. updateConfigForRawColor: function () {
  44418. var config = this.config;
  44419. var data = this.data;
  44420. var el = this.el;
  44421. var from;
  44422. var key;
  44423. var to;
  44424. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  44425. return;
  44426. }
  44427. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  44428. to = data.to;
  44429. // Use r/g/b vector for color type.
  44430. this.setColorConfig(from, to);
  44431. from = this.fromColor;
  44432. to = this.toColor;
  44433. this.targetsArray.length = 0;
  44434. this.targetsArray.push(from);
  44435. config.targets = this.targetsArray;
  44436. for (key in to) { config[key] = to[key]; }
  44437. config.update = (function () {
  44438. var lastValue = {};
  44439. return function (anim) {
  44440. var value;
  44441. value = anim.animatables[0].target;
  44442. // For animation timeline.
  44443. if (value.r === lastValue.r &&
  44444. value.g === lastValue.g &&
  44445. value.b === lastValue.b) { return; }
  44446. setRawProperty(el, data.property, value, data.type);
  44447. };
  44448. })();
  44449. },
  44450. /**
  44451. * Stuff property into generic `property` key.
  44452. */
  44453. updateConfigForDefault: function () {
  44454. var config = this.config;
  44455. var data = this.data;
  44456. var el = this.el;
  44457. var from;
  44458. var isBoolean;
  44459. var isNumber;
  44460. var to;
  44461. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  44462. return;
  44463. }
  44464. if (data.from === '') {
  44465. // Infer from.
  44466. from = isRawProperty(data)
  44467. ? getRawProperty(el, data.property)
  44468. : getComponentProperty(el, data.property);
  44469. } else {
  44470. // Explicit from.
  44471. from = data.from;
  44472. }
  44473. to = data.to;
  44474. isNumber = !isNaN(from || to);
  44475. if (isNumber) {
  44476. from = parseFloat(from);
  44477. to = parseFloat(to);
  44478. } else {
  44479. from = from ? from.toString() : from;
  44480. to = to ? to.toString() : to;
  44481. }
  44482. // Convert booleans to integer to allow boolean flipping.
  44483. isBoolean = data.to === 'true' || data.to === 'false' ||
  44484. data.to === true || data.to === false;
  44485. if (isBoolean) {
  44486. from = data.from === 'true' || data.from === true ? 1 : 0;
  44487. to = data.to === 'true' || data.to === true ? 1 : 0;
  44488. }
  44489. this.targets.aframeProperty = from;
  44490. config.targets = this.targets;
  44491. config.aframeProperty = to;
  44492. config.update = (function () {
  44493. var lastValue;
  44494. return function (anim) {
  44495. var value;
  44496. value = anim.animatables[0].target.aframeProperty;
  44497. // Need to do a last value check for animation timeline since all the tweening
  44498. // begins simultaenously even if the value has not changed. Also better for perf
  44499. // anyways.
  44500. if (value === lastValue) { return; }
  44501. lastValue = value;
  44502. if (isBoolean) { value = value >= 1; }
  44503. if (isRawProperty(data)) {
  44504. setRawProperty(el, data.property, value, data.type);
  44505. } else {
  44506. setComponentProperty(el, data.property, value);
  44507. }
  44508. };
  44509. })();
  44510. },
  44511. /**
  44512. * Extend x/y/z/w onto the config.
  44513. * Update vector by modifying object3D.
  44514. */
  44515. updateConfigForVector: function () {
  44516. var config = this.config;
  44517. var data = this.data;
  44518. var el = this.el;
  44519. var key;
  44520. var from;
  44521. var to;
  44522. // Parse coordinates.
  44523. from = data.from !== ''
  44524. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  44525. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  44526. to = utils.coordinates.parse(data.to);
  44527. if (data.property === PROP_ROTATION) {
  44528. toRadians(from);
  44529. toRadians(to);
  44530. }
  44531. // Set to and from.
  44532. this.targetsArray.length = 0;
  44533. this.targetsArray.push(from);
  44534. config.targets = this.targetsArray;
  44535. for (key in to) { config[key] = to[key]; }
  44536. // If animating object3D transformation, run more optimized updater.
  44537. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  44538. data.property === PROP_SCALE) {
  44539. config.update = (function () {
  44540. var lastValue = {};
  44541. return function (anim) {
  44542. var value = anim.animatables[0].target;
  44543. if (data.property === PROP_SCALE) {
  44544. value.x = Math.max(0.0001, value.x);
  44545. value.y = Math.max(0.0001, value.y);
  44546. value.z = Math.max(0.0001, value.z);
  44547. }
  44548. // For animation timeline.
  44549. if (value.x === lastValue.x &&
  44550. value.y === lastValue.y &&
  44551. value.z === lastValue.z) { return; }
  44552. lastValue.x = value.x;
  44553. lastValue.y = value.y;
  44554. lastValue.z = value.z;
  44555. el.object3D[data.property].set(value.x, value.y, value.z);
  44556. };
  44557. })();
  44558. return;
  44559. }
  44560. // Animating some vector.
  44561. config.update = (function () {
  44562. var lastValue = {};
  44563. return function (anim) {
  44564. var value = anim.animatables[0].target;
  44565. // Animate rotation through radians.
  44566. // For animation timeline.
  44567. if (value.x === lastValue.x &&
  44568. value.y === lastValue.y &&
  44569. value.z === lastValue.z) { return; }
  44570. lastValue.x = value.x;
  44571. lastValue.y = value.y;
  44572. lastValue.z = value.z;
  44573. setComponentProperty(el, data.property, value);
  44574. };
  44575. })();
  44576. },
  44577. /**
  44578. * Update the config before each run.
  44579. */
  44580. updateConfig: function () {
  44581. var propType;
  44582. // Route config type.
  44583. propType = getPropertyType(this.el, this.data.property);
  44584. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  44585. this.updateConfigForRawColor();
  44586. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  44587. this.updateConfigForVector();
  44588. } else {
  44589. this.updateConfigForDefault();
  44590. }
  44591. },
  44592. /**
  44593. * Wait for component to initialize.
  44594. */
  44595. waitComponentInitRawProperty: function (cb) {
  44596. var componentName;
  44597. var data = this.data;
  44598. var el = this.el;
  44599. var self = this;
  44600. if (data.from !== '') { return false; }
  44601. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  44602. componentName = splitDot(data.property)[1];
  44603. if (el.components[componentName]) { return false; }
  44604. el.addEventListener('componentinitialized', function wait (evt) {
  44605. if (evt.detail.name !== componentName) { return; }
  44606. cb();
  44607. // Since the config was created async, create the animation now since we missed it
  44608. // earlier.
  44609. self.animation = anime(self.config);
  44610. el.removeEventListener('componentinitialized', wait);
  44611. });
  44612. return true;
  44613. },
  44614. /**
  44615. * Make sure two animations on the same property don't fight each other.
  44616. * e.g., animation__mouseenter="property: material.opacity"
  44617. * animation__mouseleave="property: material.opacity"
  44618. */
  44619. stopRelatedAnimations: function () {
  44620. var component;
  44621. var componentName;
  44622. for (componentName in this.el.components) {
  44623. component = this.el.components[componentName];
  44624. if (componentName === this.attrName) { continue; }
  44625. if (component.name !== 'animation') { continue; }
  44626. if (!component.animationIsPlaying) { continue; }
  44627. if (component.data.property !== this.data.property) { continue; }
  44628. component.animationIsPlaying = false;
  44629. }
  44630. },
  44631. addEventListeners: function () {
  44632. var data = this.data;
  44633. var el = this.el;
  44634. addEventListeners(el, data.startEvents, this.onStartEvent);
  44635. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44636. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44637. },
  44638. removeEventListeners: function () {
  44639. var data = this.data;
  44640. var el = this.el;
  44641. removeEventListeners(el, data.startEvents, this.onStartEvent);
  44642. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44643. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44644. },
  44645. setColorConfig: function (from, to) {
  44646. colorHelperFrom.set(from);
  44647. colorHelperTo.set(to);
  44648. from = this.fromColor;
  44649. to = this.toColor;
  44650. from.r = colorHelperFrom.r;
  44651. from.g = colorHelperFrom.g;
  44652. from.b = colorHelperFrom.b;
  44653. to.r = colorHelperTo.r;
  44654. to.g = colorHelperTo.g;
  44655. to.b = colorHelperTo.b;
  44656. }
  44657. });
  44658. /**
  44659. * Given property name, check schema to see what type we are animating.
  44660. * We just care whether the property is a vector.
  44661. */
  44662. function getPropertyType (el, property) {
  44663. var component;
  44664. var componentName;
  44665. var split;
  44666. var propertyName;
  44667. split = property.split('.');
  44668. componentName = split[0];
  44669. propertyName = split[1];
  44670. component = el.components[componentName] || components[componentName];
  44671. // Primitives.
  44672. if (!component) { return null; }
  44673. // Dynamic schema. We only care about vectors anyways.
  44674. if (propertyName && !component.schema[propertyName]) { return null; }
  44675. // Multi-prop.
  44676. if (propertyName) { return component.schema[propertyName].type; }
  44677. // Single-prop.
  44678. return component.schema.type;
  44679. }
  44680. /**
  44681. * Convert object to radians.
  44682. */
  44683. function toRadians (obj) {
  44684. obj.x = THREE.Math.degToRad(obj.x);
  44685. obj.y = THREE.Math.degToRad(obj.y);
  44686. obj.z = THREE.Math.degToRad(obj.z);
  44687. }
  44688. function addEventListeners (el, eventNames, handler) {
  44689. var i;
  44690. for (i = 0; i < eventNames.length; i++) {
  44691. el.addEventListener(eventNames[i], handler);
  44692. }
  44693. }
  44694. function removeEventListeners (el, eventNames, handler) {
  44695. var i;
  44696. for (i = 0; i < eventNames.length; i++) {
  44697. el.removeEventListener(eventNames[i], handler);
  44698. }
  44699. }
  44700. function getRawProperty (el, path) {
  44701. var i;
  44702. var split;
  44703. var value;
  44704. split = splitDot(path);
  44705. value = el;
  44706. for (i = 0; i < split.length; i++) {
  44707. value = value[split[i]];
  44708. }
  44709. if (value === undefined) {
  44710. console.log(el);
  44711. throw new Error('[animation] property (' + path + ') could not be found');
  44712. }
  44713. return value;
  44714. }
  44715. function setRawProperty (el, path, value, type) {
  44716. var i;
  44717. var split;
  44718. var propertyName;
  44719. var targetValue;
  44720. if (path.startsWith('object3D.rotation')) {
  44721. value = THREE.Math.degToRad(value);
  44722. }
  44723. // Walk.
  44724. split = splitDot(path);
  44725. targetValue = el;
  44726. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  44727. propertyName = split[split.length - 1];
  44728. // Raw color.
  44729. if (type === TYPE_COLOR) {
  44730. if ('r' in targetValue[propertyName]) {
  44731. targetValue[propertyName].r = value.r;
  44732. targetValue[propertyName].g = value.g;
  44733. targetValue[propertyName].b = value.b;
  44734. } else {
  44735. targetValue[propertyName].x = value.r;
  44736. targetValue[propertyName].y = value.g;
  44737. targetValue[propertyName].z = value.b;
  44738. }
  44739. return;
  44740. }
  44741. targetValue[propertyName] = value;
  44742. }
  44743. function splitDot (path) {
  44744. if (path in splitCache) { return splitCache[path]; }
  44745. splitCache[path] = path.split('.');
  44746. return splitCache[path];
  44747. }
  44748. function isRawProperty (data) {
  44749. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  44750. data.property.startsWith(STRING_OBJECT3D);
  44751. }
  44752. },{"../core/component":129,"../lib/three":177,"../utils":203,"super-animejs":56}],74:[function(_dereq_,module,exports){
  44753. var registerComponent = _dereq_('../core/component').registerComponent;
  44754. var THREE = _dereq_('../lib/three');
  44755. /**
  44756. * Camera component.
  44757. * Pairs along with camera system to handle tracking the active camera.
  44758. */
  44759. module.exports.Component = registerComponent('camera', {
  44760. schema: {
  44761. active: {default: true},
  44762. far: {default: 10000},
  44763. fov: {default: 80, min: 0},
  44764. near: {default: 0.005, min: 0},
  44765. spectator: {default: false},
  44766. zoom: {default: 1, min: 0}
  44767. },
  44768. /**
  44769. * Initialize three.js camera and add it to the entity.
  44770. * Add reference from scene to this entity as the camera.
  44771. */
  44772. init: function () {
  44773. var camera;
  44774. var el = this.el;
  44775. // Create camera.
  44776. camera = this.camera = new THREE.PerspectiveCamera();
  44777. el.setObject3D('camera', camera);
  44778. },
  44779. /**
  44780. * Update three.js camera.
  44781. */
  44782. update: function (oldData) {
  44783. var data = this.data;
  44784. var camera = this.camera;
  44785. // Update properties.
  44786. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  44787. camera.far = data.far;
  44788. camera.fov = data.fov;
  44789. camera.near = data.near;
  44790. camera.zoom = data.zoom;
  44791. camera.updateProjectionMatrix();
  44792. this.updateActiveCamera(oldData);
  44793. this.updateSpectatorCamera(oldData);
  44794. },
  44795. updateActiveCamera: function (oldData) {
  44796. var data = this.data;
  44797. var el = this.el;
  44798. var system = this.system;
  44799. // Active property did not change.
  44800. if (oldData && oldData.active === data.active || data.spectator) { return; }
  44801. // If `active` property changes, or first update, handle active camera with system.
  44802. if (data.active && system.activeCameraEl !== el) {
  44803. // Camera enabled. Set camera to this camera.
  44804. system.setActiveCamera(el);
  44805. } else if (!data.active && system.activeCameraEl === el) {
  44806. // Camera disabled. Set camera to another camera.
  44807. system.disableActiveCamera();
  44808. }
  44809. },
  44810. updateSpectatorCamera: function (oldData) {
  44811. var data = this.data;
  44812. var el = this.el;
  44813. var system = this.system;
  44814. // spectator property did not change.
  44815. if (oldData && oldData.spectator === data.spectator) { return; }
  44816. // If `spectator` property changes, or first update, handle spectator camera with system.
  44817. if (data.spectator && system.spectatorCameraEl !== el) {
  44818. // Camera enabled. Set camera to this camera.
  44819. system.setSpectatorCamera(el);
  44820. } else if (!data.spectator && system.spectatorCameraEl === el) {
  44821. // Camera disabled. Set camera to another camera.
  44822. system.disableSpectatorCamera();
  44823. }
  44824. },
  44825. /**
  44826. * Remove camera on remove (callback).
  44827. */
  44828. remove: function () {
  44829. this.el.removeObject3D('camera');
  44830. }
  44831. });
  44832. },{"../core/component":129,"../lib/three":177}],75:[function(_dereq_,module,exports){
  44833. /* global THREE */
  44834. var registerComponent = _dereq_('../core/component').registerComponent;
  44835. var utils = _dereq_('../utils/');
  44836. var bind = utils.bind;
  44837. var EVENTS = {
  44838. CLICK: 'click',
  44839. FUSING: 'fusing',
  44840. MOUSEENTER: 'mouseenter',
  44841. MOUSEDOWN: 'mousedown',
  44842. MOUSELEAVE: 'mouseleave',
  44843. MOUSEUP: 'mouseup'
  44844. };
  44845. var STATES = {
  44846. FUSING: 'cursor-fusing',
  44847. HOVERING: 'cursor-hovering',
  44848. HOVERED: 'cursor-hovered'
  44849. };
  44850. var CANVAS_EVENTS = {
  44851. DOWN: ['mousedown', 'touchstart'],
  44852. UP: ['mouseup', 'touchend']
  44853. };
  44854. var WEBXR_EVENTS = {
  44855. DOWN: ['selectstart'],
  44856. UP: ['selectend']
  44857. };
  44858. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  44859. /**
  44860. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  44861. * from the camera and pointing from camera's facing direction, and then only returning the
  44862. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  44863. *
  44864. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  44865. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  44866. * @member {object} intersection - Attributes of the current intersection event, including
  44867. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  44868. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  44869. * emit events when unintersecting.
  44870. */
  44871. module.exports.Component = registerComponent('cursor', {
  44872. dependencies: ['raycaster'],
  44873. schema: {
  44874. downEvents: {default: []},
  44875. fuse: {default: utils.device.isMobile()},
  44876. fuseTimeout: {default: 1500, min: 0},
  44877. mouseCursorStylesEnabled: {default: true},
  44878. upEvents: {default: []},
  44879. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  44880. },
  44881. init: function () {
  44882. var self = this;
  44883. this.fuseTimeout = undefined;
  44884. this.cursorDownEl = null;
  44885. this.intersectedEl = null;
  44886. this.canvasBounds = document.body.getBoundingClientRect();
  44887. this.isCursorDown = false;
  44888. // Debounce.
  44889. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  44890. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  44891. }, 500);
  44892. this.eventDetail = {};
  44893. this.intersectedEventDetail = {cursorEl: this.el};
  44894. // Bind methods.
  44895. this.onCursorDown = bind(this.onCursorDown, this);
  44896. this.onCursorUp = bind(this.onCursorUp, this);
  44897. this.onIntersection = bind(this.onIntersection, this);
  44898. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  44899. this.onMouseMove = bind(this.onMouseMove, this);
  44900. this.onEnterVR = bind(this.onEnterVR, this);
  44901. },
  44902. update: function (oldData) {
  44903. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  44904. this.updateMouseEventListeners();
  44905. },
  44906. play: function () {
  44907. this.addEventListeners();
  44908. },
  44909. pause: function () {
  44910. this.removeEventListeners();
  44911. },
  44912. remove: function () {
  44913. var el = this.el;
  44914. el.removeState(STATES.HOVERING);
  44915. el.removeState(STATES.FUSING);
  44916. clearTimeout(this.fuseTimeout);
  44917. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  44918. this.removeEventListeners();
  44919. },
  44920. addEventListeners: function () {
  44921. var canvas;
  44922. var data = this.data;
  44923. var el = this.el;
  44924. var self = this;
  44925. function addCanvasListeners () {
  44926. canvas = el.sceneEl.canvas;
  44927. if (data.downEvents.length || data.upEvents.length) { return; }
  44928. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44929. canvas.addEventListener(downEvent, self.onCursorDown);
  44930. });
  44931. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44932. canvas.addEventListener(upEvent, self.onCursorUp);
  44933. });
  44934. }
  44935. canvas = el.sceneEl.canvas;
  44936. if (canvas) {
  44937. addCanvasListeners();
  44938. } else {
  44939. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  44940. }
  44941. data.downEvents.forEach(function (downEvent) {
  44942. el.addEventListener(downEvent, self.onCursorDown);
  44943. });
  44944. data.upEvents.forEach(function (upEvent) {
  44945. el.addEventListener(upEvent, self.onCursorUp);
  44946. });
  44947. el.addEventListener('raycaster-intersection', this.onIntersection);
  44948. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44949. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  44950. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44951. window.addEventListener('resize', this.updateCanvasBounds);
  44952. window.addEventListener('scroll', this.updateCanvasBounds);
  44953. this.updateMouseEventListeners();
  44954. },
  44955. removeEventListeners: function () {
  44956. var canvas;
  44957. var data = this.data;
  44958. var el = this.el;
  44959. var self = this;
  44960. canvas = el.sceneEl.canvas;
  44961. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  44962. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44963. canvas.removeEventListener(downEvent, self.onCursorDown);
  44964. });
  44965. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44966. canvas.removeEventListener(upEvent, self.onCursorUp);
  44967. });
  44968. }
  44969. data.downEvents.forEach(function (downEvent) {
  44970. el.removeEventListener(downEvent, self.onCursorDown);
  44971. });
  44972. data.upEvents.forEach(function (upEvent) {
  44973. el.removeEventListener(upEvent, self.onCursorUp);
  44974. });
  44975. el.removeEventListener('raycaster-intersection', this.onIntersection);
  44976. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44977. canvas.removeEventListener('mousemove', this.onMouseMove);
  44978. canvas.removeEventListener('touchstart', this.onMouseMove);
  44979. canvas.removeEventListener('touchmove', this.onMouseMove);
  44980. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  44981. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44982. window.removeEventListener('resize', this.updateCanvasBounds);
  44983. window.removeEventListener('scroll', this.updateCanvasBounds);
  44984. },
  44985. updateMouseEventListeners: function () {
  44986. var canvas;
  44987. var el = this.el;
  44988. canvas = el.sceneEl.canvas;
  44989. canvas.removeEventListener('mousemove', this.onMouseMove);
  44990. canvas.removeEventListener('touchmove', this.onMouseMove);
  44991. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  44992. if (this.data.rayOrigin !== 'mouse') { return; }
  44993. canvas.addEventListener('mousemove', this.onMouseMove, false);
  44994. canvas.addEventListener('touchmove', this.onMouseMove, false);
  44995. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  44996. this.updateCanvasBounds();
  44997. },
  44998. onMouseMove: (function () {
  44999. var direction = new THREE.Vector3();
  45000. var mouse = new THREE.Vector2();
  45001. var origin = new THREE.Vector3();
  45002. var rayCasterConfig = {origin: origin, direction: direction};
  45003. return function (evt) {
  45004. var bounds = this.canvasBounds;
  45005. var camera = this.el.sceneEl.camera;
  45006. var left;
  45007. var point;
  45008. var top;
  45009. camera.parent.updateMatrixWorld();
  45010. // Calculate mouse position based on the canvas element
  45011. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  45012. // Track the first touch for simplicity.
  45013. point = evt.touches.item(0);
  45014. } else {
  45015. point = evt;
  45016. }
  45017. left = point.clientX - bounds.left;
  45018. top = point.clientY - bounds.top;
  45019. mouse.x = (left / bounds.width) * 2 - 1;
  45020. mouse.y = -(top / bounds.height) * 2 + 1;
  45021. origin.setFromMatrixPosition(camera.matrixWorld);
  45022. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  45023. this.el.setAttribute('raycaster', rayCasterConfig);
  45024. if (evt.type === 'touchmove') { evt.preventDefault(); }
  45025. };
  45026. })(),
  45027. /**
  45028. * Trigger mousedown and keep track of the mousedowned entity.
  45029. */
  45030. onCursorDown: function (evt) {
  45031. this.isCursorDown = true;
  45032. // Raycast again for touch.
  45033. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  45034. this.onMouseMove(evt);
  45035. this.el.components.raycaster.checkIntersections();
  45036. evt.preventDefault();
  45037. }
  45038. this.twoWayEmit(EVENTS.MOUSEDOWN);
  45039. this.cursorDownEl = this.intersectedEl;
  45040. },
  45041. /**
  45042. * Trigger mouseup if:
  45043. * - Not fusing (mobile has no mouse).
  45044. * - Currently intersecting an entity.
  45045. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  45046. * in case user mousedowned one entity, dragged to another, and mouseupped.
  45047. */
  45048. onCursorUp: function (evt) {
  45049. if (!this.isCursorDown) { return; }
  45050. this.isCursorDown = false;
  45051. var data = this.data;
  45052. this.twoWayEmit(EVENTS.MOUSEUP);
  45053. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  45054. // previously cursorUp entity.
  45055. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  45056. this.intersectedEventDetail.intersection = null;
  45057. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  45058. }
  45059. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  45060. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  45061. this.twoWayEmit(EVENTS.CLICK);
  45062. }
  45063. this.cursorDownEl = null;
  45064. if (evt.type === 'touchend') { evt.preventDefault(); }
  45065. },
  45066. /**
  45067. * Handle intersection.
  45068. */
  45069. onIntersection: function (evt) {
  45070. var currentIntersection;
  45071. var cursorEl = this.el;
  45072. var index;
  45073. var intersectedEl;
  45074. var intersection;
  45075. // Select closest object, excluding the cursor.
  45076. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  45077. intersection = evt.detail.intersections[index];
  45078. intersectedEl = evt.detail.els[index];
  45079. // If cursor is the only intersected object, ignore the event.
  45080. if (!intersectedEl) { return; }
  45081. // Already intersecting this entity.
  45082. if (this.intersectedEl === intersectedEl) { return; }
  45083. // Ignore events further away than active intersection.
  45084. if (this.intersectedEl) {
  45085. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  45086. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  45087. }
  45088. // Unset current intersection.
  45089. this.clearCurrentIntersection(true);
  45090. this.setIntersection(intersectedEl, intersection);
  45091. },
  45092. /**
  45093. * Handle intersection cleared.
  45094. */
  45095. onIntersectionCleared: function (evt) {
  45096. var clearedEls = evt.detail.clearedEls;
  45097. // Check if the current intersection has ended
  45098. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  45099. this.clearCurrentIntersection();
  45100. },
  45101. onEnterVR: function () {
  45102. this.clearCurrentIntersection(true);
  45103. var xrSession = this.el.sceneEl.xrSession;
  45104. var self = this;
  45105. if (!xrSession) { return; }
  45106. if (this.data.rayOrigin === 'mouse') { return; }
  45107. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  45108. xrSession.addEventListener(downEvent, self.onCursorDown);
  45109. });
  45110. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  45111. xrSession.addEventListener(upEvent, self.onCursorUp);
  45112. });
  45113. },
  45114. setIntersection: function (intersectedEl, intersection) {
  45115. var cursorEl = this.el;
  45116. var data = this.data;
  45117. var self = this;
  45118. // Already intersecting.
  45119. if (this.intersectedEl === intersectedEl) { return; }
  45120. // Set new intersection.
  45121. this.intersectedEl = intersectedEl;
  45122. // Hovering.
  45123. cursorEl.addState(STATES.HOVERING);
  45124. intersectedEl.addState(STATES.HOVERED);
  45125. this.twoWayEmit(EVENTS.MOUSEENTER);
  45126. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  45127. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  45128. }
  45129. // Begin fuse if necessary.
  45130. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  45131. cursorEl.addState(STATES.FUSING);
  45132. this.twoWayEmit(EVENTS.FUSING);
  45133. this.fuseTimeout = setTimeout(function fuse () {
  45134. cursorEl.removeState(STATES.FUSING);
  45135. self.twoWayEmit(EVENTS.CLICK);
  45136. }, data.fuseTimeout);
  45137. },
  45138. clearCurrentIntersection: function (ignoreRemaining) {
  45139. var index;
  45140. var intersection;
  45141. var intersections;
  45142. var cursorEl = this.el;
  45143. // Nothing to be cleared.
  45144. if (!this.intersectedEl) { return; }
  45145. // No longer hovering (or fusing).
  45146. this.intersectedEl.removeState(STATES.HOVERED);
  45147. cursorEl.removeState(STATES.HOVERING);
  45148. cursorEl.removeState(STATES.FUSING);
  45149. this.twoWayEmit(EVENTS.MOUSELEAVE);
  45150. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  45151. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  45152. }
  45153. // Unset intersected entity (after emitting the event).
  45154. this.intersectedEl = null;
  45155. // Clear fuseTimeout.
  45156. clearTimeout(this.fuseTimeout);
  45157. // Set intersection to another raycasted element if any.
  45158. if (ignoreRemaining === true) { return; }
  45159. intersections = this.el.components.raycaster.intersections;
  45160. if (intersections.length === 0) { return; }
  45161. // Exclude the cursor.
  45162. index = intersections[0].object.el === cursorEl ? 1 : 0;
  45163. intersection = intersections[index];
  45164. if (!intersection) { return; }
  45165. this.setIntersection(intersection.object.el, intersection);
  45166. },
  45167. /**
  45168. * Helper to emit on both the cursor and the intersected entity (if exists).
  45169. */
  45170. twoWayEmit: function (evtName) {
  45171. var el = this.el;
  45172. var intersectedEl = this.intersectedEl;
  45173. var intersection;
  45174. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  45175. this.eventDetail.intersectedEl = intersectedEl;
  45176. this.eventDetail.intersection = intersection;
  45177. el.emit(evtName, this.eventDetail);
  45178. if (!intersectedEl) { return; }
  45179. this.intersectedEventDetail.intersection = intersection;
  45180. intersectedEl.emit(evtName, this.intersectedEventDetail);
  45181. }
  45182. });
  45183. },{"../core/component":129,"../utils/":203}],76:[function(_dereq_,module,exports){
  45184. var registerComponent = _dereq_('../core/component').registerComponent;
  45185. var bind = _dereq_('../utils/bind');
  45186. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45187. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45188. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45189. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45190. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  45191. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  45192. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  45193. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  45194. var GAMEPAD_ID_WEBXR = 'google-daydream';
  45195. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  45196. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  45197. /**
  45198. * Button indices:
  45199. * 0 - trackpad
  45200. * 1 - menu (never dispatched on this layer)
  45201. * 2 - system (never dispatched on this layer)
  45202. *
  45203. * Axis:
  45204. * 0 - trackpad x
  45205. * 1 - trackpad y
  45206. */
  45207. var INPUT_MAPPING_WEBVR = {
  45208. axes: {trackpad: [0, 1]},
  45209. buttons: ['trackpad', 'menu', 'system']
  45210. };
  45211. /**
  45212. * Button indices:
  45213. * 0 - none
  45214. * 1 - none
  45215. * 2 - touchpad
  45216. *
  45217. * Axis:
  45218. * 0 - touchpad x
  45219. * 1 - touchpad y
  45220. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/google/google-daydream.json
  45221. */
  45222. var INPUT_MAPPING_WEBXR = {
  45223. axes: {touchpad: [0, 1]},
  45224. buttons: ['none', 'none', 'touchpad', 'menu', 'system']
  45225. };
  45226. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  45227. /**
  45228. * Daydream controls.
  45229. * Interface with Daydream controller and map Gamepad events to
  45230. * controller buttons: trackpad, menu, system
  45231. * Load a controller model and highlight the pressed buttons.
  45232. */
  45233. module.exports.Component = registerComponent('daydream-controls', {
  45234. schema: {
  45235. hand: {default: ''}, // This informs the degenerate arm model.
  45236. buttonColor: {type: 'color', default: '#000000'},
  45237. buttonTouchedColor: {type: 'color', default: '#777777'},
  45238. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  45239. model: {default: true},
  45240. orientationOffset: {type: 'vec3'},
  45241. armModel: {default: true}
  45242. },
  45243. mapping: INPUT_MAPPING,
  45244. bindMethods: function () {
  45245. this.onModelLoaded = bind(this.onModelLoaded, this);
  45246. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45247. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45248. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45249. this.onAxisMoved = bind(this.onAxisMoved, this);
  45250. },
  45251. init: function () {
  45252. var self = this;
  45253. this.onButtonChanged = bind(this.onButtonChanged, this);
  45254. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45255. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45256. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45257. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45258. this.controllerPresent = false;
  45259. this.lastControllerCheck = 0;
  45260. this.bindMethods();
  45261. },
  45262. addEventListeners: function () {
  45263. var el = this.el;
  45264. el.addEventListener('buttonchanged', this.onButtonChanged);
  45265. el.addEventListener('buttondown', this.onButtonDown);
  45266. el.addEventListener('buttonup', this.onButtonUp);
  45267. el.addEventListener('touchstart', this.onButtonTouchStart);
  45268. el.addEventListener('touchend', this.onButtonTouchEnd);
  45269. el.addEventListener('model-loaded', this.onModelLoaded);
  45270. el.addEventListener('axismove', this.onAxisMoved);
  45271. this.controllerEventsActive = true;
  45272. },
  45273. removeEventListeners: function () {
  45274. var el = this.el;
  45275. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45276. el.removeEventListener('buttondown', this.onButtonDown);
  45277. el.removeEventListener('buttonup', this.onButtonUp);
  45278. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45279. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45280. el.removeEventListener('model-loaded', this.onModelLoaded);
  45281. el.removeEventListener('axismove', this.onAxisMoved);
  45282. this.controllerEventsActive = false;
  45283. },
  45284. checkIfControllerPresent: function () {
  45285. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45286. this.data.hand ? {hand: this.data.hand} : {});
  45287. },
  45288. play: function () {
  45289. this.checkIfControllerPresent();
  45290. this.addControllersUpdateListener();
  45291. },
  45292. pause: function () {
  45293. this.removeEventListeners();
  45294. this.removeControllersUpdateListener();
  45295. },
  45296. injectTrackedControls: function () {
  45297. var el = this.el;
  45298. var data = this.data;
  45299. el.setAttribute('tracked-controls', {
  45300. armModel: data.armModel,
  45301. hand: data.hand,
  45302. idPrefix: GAMEPAD_ID_PREFIX,
  45303. id: GAMEPAD_ID_PREFIX,
  45304. orientationOffset: data.orientationOffset
  45305. });
  45306. if (!this.data.model) { return; }
  45307. this.el.setAttribute('obj-model', {
  45308. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  45309. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  45310. });
  45311. },
  45312. addControllersUpdateListener: function () {
  45313. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45314. },
  45315. removeControllersUpdateListener: function () {
  45316. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45317. },
  45318. onControllersUpdate: function () {
  45319. this.checkIfControllerPresent();
  45320. },
  45321. onModelLoaded: function (evt) {
  45322. var controllerObject3D = evt.detail.model;
  45323. var buttonMeshes;
  45324. if (!this.data.model) { return; }
  45325. buttonMeshes = this.buttonMeshes = {};
  45326. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  45327. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  45328. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  45329. buttonMeshes.touchpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  45330. // Offset pivot point.
  45331. controllerObject3D.position.set(0, 0, -0.04);
  45332. },
  45333. onAxisMoved: function (evt) {
  45334. emitIfAxesChanged(this, this.mapping.axes, evt);
  45335. },
  45336. onButtonChanged: function (evt) {
  45337. var button = this.mapping.buttons[evt.detail.id];
  45338. if (!button) return;
  45339. // Pass along changed event with button state, using button mapping for convenience.
  45340. this.el.emit(button + 'changed', evt.detail.state);
  45341. },
  45342. updateModel: function (buttonName, evtName) {
  45343. if (!this.data.model) { return; }
  45344. this.updateButtonModel(buttonName, evtName);
  45345. },
  45346. updateButtonModel: function (buttonName, state) {
  45347. var buttonMeshes = this.buttonMeshes;
  45348. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45349. var color;
  45350. switch (state) {
  45351. case 'down':
  45352. color = this.data.buttonHighlightColor;
  45353. break;
  45354. case 'touchstart':
  45355. color = this.data.buttonTouchedColor;
  45356. break;
  45357. default:
  45358. color = this.data.buttonColor;
  45359. }
  45360. buttonMeshes[buttonName].material.color.set(color);
  45361. }
  45362. });
  45363. },{"../core/component":129,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],77:[function(_dereq_,module,exports){
  45364. var registerComponent = _dereq_('../core/component').registerComponent;
  45365. var bind = _dereq_('../utils/bind');
  45366. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45367. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45368. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45369. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45370. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  45371. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  45372. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  45373. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  45374. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  45375. var GAMEPAD_ID_WEBVR = 'Gear VR';
  45376. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  45377. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  45378. /**
  45379. * Button indices:
  45380. * 0 - trackpad
  45381. * 1 - trigger
  45382. *
  45383. * Axis:
  45384. * 0 - trackpad x
  45385. * 1 - trackpad y
  45386. */
  45387. var INPUT_MAPPING_WEBVR = {
  45388. axes: {trackpad: [0, 1]},
  45389. buttons: ['trackpad', 'trigger']
  45390. };
  45391. /**
  45392. * Button indices:
  45393. * 0 - trigger
  45394. * 1 - none
  45395. * 2 - touchpad
  45396. * 3 - menu
  45397. *
  45398. * Axis:
  45399. * 0 - touchpad x
  45400. * 1 - touchpad y
  45401. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/samsung/samsung-gearvr.json
  45402. */
  45403. var INPUT_MAPPING_WEBXR = {
  45404. axes: {touchpad: [0, 1]},
  45405. buttons: ['trigger', 'none', 'touchpad', 'none', 'menu']
  45406. };
  45407. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  45408. /**
  45409. * Gear VR controls.
  45410. * Interface with Gear VR controller and map Gamepad events to
  45411. * controller buttons: trackpad, trigger
  45412. * Load a controller model and highlight the pressed buttons.
  45413. */
  45414. module.exports.Component = registerComponent('gearvr-controls', {
  45415. schema: {
  45416. hand: {default: ''}, // This informs the degenerate arm model.
  45417. buttonColor: {type: 'color', default: '#000000'},
  45418. buttonTouchedColor: {type: 'color', default: '#777777'},
  45419. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  45420. model: {default: true},
  45421. orientationOffset: {type: 'vec3'},
  45422. armModel: {default: true}
  45423. },
  45424. mapping: INPUT_MAPPING,
  45425. bindMethods: function () {
  45426. this.onModelLoaded = bind(this.onModelLoaded, this);
  45427. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45428. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45429. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45430. this.onAxisMoved = bind(this.onAxisMoved, this);
  45431. },
  45432. init: function () {
  45433. var self = this;
  45434. this.onButtonChanged = bind(this.onButtonChanged, this);
  45435. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45436. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45437. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45438. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45439. this.controllerPresent = false;
  45440. this.lastControllerCheck = 0;
  45441. this.bindMethods();
  45442. },
  45443. addEventListeners: function () {
  45444. var el = this.el;
  45445. el.addEventListener('buttonchanged', this.onButtonChanged);
  45446. el.addEventListener('buttondown', this.onButtonDown);
  45447. el.addEventListener('buttonup', this.onButtonUp);
  45448. el.addEventListener('touchstart', this.onButtonTouchStart);
  45449. el.addEventListener('touchend', this.onButtonTouchEnd);
  45450. el.addEventListener('model-loaded', this.onModelLoaded);
  45451. el.addEventListener('axismove', this.onAxisMoved);
  45452. this.controllerEventsActive = true;
  45453. },
  45454. removeEventListeners: function () {
  45455. var el = this.el;
  45456. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45457. el.removeEventListener('buttondown', this.onButtonDown);
  45458. el.removeEventListener('buttonup', this.onButtonUp);
  45459. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45460. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45461. el.removeEventListener('model-loaded', this.onModelLoaded);
  45462. el.removeEventListener('axismove', this.onAxisMoved);
  45463. this.controllerEventsActive = false;
  45464. },
  45465. checkIfControllerPresent: function () {
  45466. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45467. this.data.hand ? {hand: this.data.hand} : {});
  45468. },
  45469. play: function () {
  45470. this.checkIfControllerPresent();
  45471. this.addControllersUpdateListener();
  45472. },
  45473. pause: function () {
  45474. this.removeEventListeners();
  45475. this.removeControllersUpdateListener();
  45476. },
  45477. injectTrackedControls: function () {
  45478. var el = this.el;
  45479. var data = this.data;
  45480. el.setAttribute('tracked-controls', {
  45481. armModel: data.armModel,
  45482. hand: data.hand,
  45483. idPrefix: GAMEPAD_ID_PREFIX,
  45484. id: GAMEPAD_ID_PREFIX,
  45485. orientationOffset: data.orientationOffset
  45486. });
  45487. if (!this.data.model) { return; }
  45488. this.el.setAttribute('obj-model', {
  45489. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  45490. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  45491. });
  45492. },
  45493. addControllersUpdateListener: function () {
  45494. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45495. },
  45496. removeControllersUpdateListener: function () {
  45497. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45498. },
  45499. onControllersUpdate: function () {
  45500. this.checkIfControllerPresent();
  45501. },
  45502. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  45503. onModelLoaded: function (evt) {
  45504. var controllerObject3D = evt.detail.model;
  45505. var buttonMeshes;
  45506. if (!this.data.model) { return; }
  45507. buttonMeshes = this.buttonMeshes = {};
  45508. buttonMeshes.trigger = controllerObject3D.children[2];
  45509. buttonMeshes.trackpad = controllerObject3D.children[1];
  45510. buttonMeshes.touchpad = controllerObject3D.children[1];
  45511. },
  45512. onButtonChanged: function (evt) {
  45513. var button = this.mapping.buttons[evt.detail.id];
  45514. if (!button) return;
  45515. // Pass along changed event with button state, using button mapping for convenience.
  45516. this.el.emit(button + 'changed', evt.detail.state);
  45517. },
  45518. onAxisMoved: function (evt) {
  45519. emitIfAxesChanged(this, this.mapping.axes, evt);
  45520. },
  45521. updateModel: function (buttonName, evtName) {
  45522. if (!this.data.model) { return; }
  45523. this.updateButtonModel(buttonName, evtName);
  45524. },
  45525. updateButtonModel: function (buttonName, state) {
  45526. var buttonMeshes = this.buttonMeshes;
  45527. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45528. var color;
  45529. switch (state) {
  45530. case 'down':
  45531. color = this.data.buttonHighlightColor;
  45532. break;
  45533. case 'touchstart':
  45534. color = this.data.buttonTouchedColor;
  45535. break;
  45536. default:
  45537. color = this.data.buttonColor;
  45538. }
  45539. buttonMeshes[buttonName].material.color.set(color);
  45540. }
  45541. });
  45542. },{"../core/component":129,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],78:[function(_dereq_,module,exports){
  45543. var registerComponent = _dereq_('../core/component').registerComponent;
  45544. var bind = _dereq_('../utils/bind');
  45545. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45546. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45547. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45548. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45549. var GAMEPAD_ID_PREFIX = 'generic';
  45550. /**
  45551. * Button indices:
  45552. * 0 - trigger
  45553. * 1 - squeeze
  45554. * 2 - touchpad
  45555. * 3 - thumbstick
  45556. *
  45557. * Axis:
  45558. * 0 - touchpad
  45559. * 1 - thumbstick
  45560. *
  45561. */
  45562. var INPUT_MAPPING = {
  45563. axes: {
  45564. touchpad: [0, 1],
  45565. thumbstick: [2, 3]
  45566. },
  45567. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  45568. };
  45569. /**
  45570. * Oculus Go controls.
  45571. * Interface with Oculus Go controller and map Gamepad events to
  45572. * controller buttons: trackpad, trigger
  45573. * Load a controller model and highlight the pressed buttons.
  45574. */
  45575. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  45576. schema: {
  45577. hand: {default: ''}, // This informs the degenerate arm model.
  45578. defaultModel: {default: true},
  45579. defaultModelColor: {default: 'gray'},
  45580. orientationOffset: {type: 'vec3'}
  45581. },
  45582. /**
  45583. * Button IDs:
  45584. * 0 - trackpad
  45585. * 1 - trigger
  45586. */
  45587. mapping: INPUT_MAPPING,
  45588. bindMethods: function () {
  45589. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45590. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45591. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45592. this.onAxisMoved = bind(this.onAxisMoved, this);
  45593. },
  45594. init: function () {
  45595. var self = this;
  45596. this.onButtonChanged = bind(this.onButtonChanged, this);
  45597. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45598. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45599. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45600. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45601. this.controllerPresent = false;
  45602. this.lastControllerCheck = 0;
  45603. this.rendererSystem = this.el.sceneEl.systems.renderer;
  45604. this.bindMethods();
  45605. },
  45606. addEventListeners: function () {
  45607. var el = this.el;
  45608. el.addEventListener('buttonchanged', this.onButtonChanged);
  45609. el.addEventListener('buttondown', this.onButtonDown);
  45610. el.addEventListener('buttonup', this.onButtonUp);
  45611. el.addEventListener('touchstart', this.onButtonTouchStart);
  45612. el.addEventListener('touchend', this.onButtonTouchEnd);
  45613. el.addEventListener('axismove', this.onAxisMoved);
  45614. this.controllerEventsActive = true;
  45615. },
  45616. removeEventListeners: function () {
  45617. var el = this.el;
  45618. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45619. el.removeEventListener('buttondown', this.onButtonDown);
  45620. el.removeEventListener('buttonup', this.onButtonUp);
  45621. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45622. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45623. el.removeEventListener('axismove', this.onAxisMoved);
  45624. this.controllerEventsActive = false;
  45625. },
  45626. checkIfControllerPresent: function () {
  45627. var data = this.data;
  45628. var hand = data.hand ? data.hand : undefined;
  45629. checkControllerPresentAndSetup(
  45630. this, GAMEPAD_ID_PREFIX,
  45631. {hand: hand, iterateControllerProfiles: true});
  45632. },
  45633. play: function () {
  45634. this.checkIfControllerPresent();
  45635. this.addControllersUpdateListener();
  45636. },
  45637. pause: function () {
  45638. this.removeEventListeners();
  45639. this.removeControllersUpdateListener();
  45640. },
  45641. injectTrackedControls: function () {
  45642. var el = this.el;
  45643. var data = this.data;
  45644. // Do nothing if tracked-controls already set.
  45645. // Generic controls have the lowest precedence.
  45646. if (this.el.components['tracked-controls']) { return; }
  45647. el.setAttribute('tracked-controls', {
  45648. hand: data.hand,
  45649. idPrefix: GAMEPAD_ID_PREFIX,
  45650. orientationOffset: data.orientationOffset,
  45651. iterateControllerProfiles: true
  45652. });
  45653. if (!this.data.defaultModel) { return; }
  45654. this.initDefaultModel();
  45655. },
  45656. addControllersUpdateListener: function () {
  45657. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45658. },
  45659. removeControllersUpdateListener: function () {
  45660. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45661. },
  45662. onControllersUpdate: function () {
  45663. this.checkIfControllerPresent();
  45664. },
  45665. onButtonChanged: function (evt) {
  45666. var button = this.mapping.buttons[evt.detail.id];
  45667. if (!button) return;
  45668. // Pass along changed event with button state, using button mapping for convenience.
  45669. this.el.emit(button + 'changed', evt.detail.state);
  45670. },
  45671. onAxisMoved: function (evt) {
  45672. emitIfAxesChanged(this, this.mapping.axes, evt);
  45673. },
  45674. initDefaultModel: function () {
  45675. var modelEl = this.modelEl = document.createElement('a-entity');
  45676. modelEl.setAttribute('geometry', {
  45677. primitive: 'sphere',
  45678. radius: 0.03
  45679. });
  45680. modelEl.setAttribute('material', {color: this.data.color});
  45681. this.el.appendChild(modelEl);
  45682. }
  45683. });
  45684. },{"../core/component":129,"../utils/bind":197,"../utils/tracked-controls":211}],79:[function(_dereq_,module,exports){
  45685. var geometries = _dereq_('../core/geometry').geometries;
  45686. var geometryNames = _dereq_('../core/geometry').geometryNames;
  45687. var registerComponent = _dereq_('../core/component').registerComponent;
  45688. var THREE = _dereq_('../lib/three');
  45689. var dummyGeometry = new THREE.Geometry();
  45690. /**
  45691. * Geometry component. Combined with material component to make a mesh in 3D object.
  45692. * Extended with registered geometries.
  45693. */
  45694. module.exports.Component = registerComponent('geometry', {
  45695. schema: {
  45696. buffer: {default: true},
  45697. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  45698. skipCache: {default: false}
  45699. },
  45700. init: function () {
  45701. this.geometry = null;
  45702. },
  45703. /**
  45704. * Talk to geometry system to get or create geometry.
  45705. */
  45706. update: function (previousData) {
  45707. var data = this.data;
  45708. var el = this.el;
  45709. var mesh;
  45710. var system = this.system;
  45711. // Dispose old geometry if we created one.
  45712. if (this.geometry) {
  45713. system.unuseGeometry(previousData);
  45714. this.geometry = null;
  45715. }
  45716. // Create new geometry.
  45717. this.geometry = system.getOrCreateGeometry(data);
  45718. // Set on mesh. If mesh does not exist, create it.
  45719. mesh = el.getObject3D('mesh');
  45720. if (mesh) {
  45721. mesh.geometry = this.geometry;
  45722. } else {
  45723. mesh = new THREE.Mesh();
  45724. mesh.geometry = this.geometry;
  45725. el.setObject3D('mesh', mesh);
  45726. }
  45727. },
  45728. /**
  45729. * Tell geometry system that entity is no longer using the geometry.
  45730. * Unset the geometry on the mesh
  45731. */
  45732. remove: function () {
  45733. this.system.unuseGeometry(this.data);
  45734. this.el.getObject3D('mesh').geometry = dummyGeometry;
  45735. this.geometry = null;
  45736. },
  45737. /**
  45738. * Update geometry component schema based on geometry type.
  45739. */
  45740. updateSchema: function (data) {
  45741. var currentGeometryType = this.oldData && this.oldData.primitive;
  45742. var newGeometryType = data.primitive;
  45743. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  45744. // Geometry has no schema.
  45745. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  45746. // Nothing has changed.
  45747. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  45748. this.extendSchema(schema);
  45749. }
  45750. });
  45751. },{"../core/component":129,"../core/geometry":130,"../lib/three":177}],80:[function(_dereq_,module,exports){
  45752. var registerComponent = _dereq_('../core/component').registerComponent;
  45753. var THREE = _dereq_('../lib/three');
  45754. var utils = _dereq_('../utils/');
  45755. var warn = utils.debug('components:gltf-model:warn');
  45756. /**
  45757. * glTF model loader.
  45758. */
  45759. module.exports.Component = registerComponent('gltf-model', {
  45760. schema: {type: 'model'},
  45761. init: function () {
  45762. var dracoLoader = this.system.getDRACOLoader();
  45763. this.model = null;
  45764. this.loader = new THREE.GLTFLoader();
  45765. if (dracoLoader) {
  45766. this.loader.setDRACOLoader(dracoLoader);
  45767. }
  45768. },
  45769. update: function () {
  45770. var self = this;
  45771. var el = this.el;
  45772. var src = this.data;
  45773. if (!src) { return; }
  45774. this.remove();
  45775. this.loader.load(src, function gltfLoaded (gltfModel) {
  45776. self.model = gltfModel.scene || gltfModel.scenes[0];
  45777. self.model.animations = gltfModel.animations;
  45778. el.setObject3D('mesh', self.model);
  45779. el.emit('model-loaded', {format: 'gltf', model: self.model});
  45780. }, undefined /* onProgress */, function gltfFailed (error) {
  45781. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  45782. warn(message);
  45783. el.emit('model-error', {format: 'gltf', src: src});
  45784. });
  45785. },
  45786. remove: function () {
  45787. if (!this.model) { return; }
  45788. this.el.removeObject3D('mesh');
  45789. }
  45790. });
  45791. },{"../core/component":129,"../lib/three":177,"../utils/":203}],81:[function(_dereq_,module,exports){
  45792. /* global THREE */
  45793. var registerComponent = _dereq_('../core/component').registerComponent;
  45794. // Found at https://github.com/aframevr/assets.
  45795. var MODEL_URLS = {
  45796. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  45797. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  45798. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  45799. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  45800. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  45801. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  45802. };
  45803. // Poses.
  45804. var ANIMATIONS = {
  45805. open: 'Open',
  45806. // point: grip active, trackpad surface active, trigger inactive.
  45807. point: 'Point',
  45808. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  45809. pointThumb: 'Point + Thumb',
  45810. // fist: grip active, trigger active, trackpad surface active.
  45811. fist: 'Fist',
  45812. // hold: trigger active, grip inactive.
  45813. hold: 'Hold',
  45814. // thumbUp: grip active, trigger active, trackpad surface inactive.
  45815. thumbUp: 'Thumb Up'
  45816. };
  45817. // Map animation to public events for the API.
  45818. var EVENTS = {};
  45819. EVENTS[ANIMATIONS.fist] = 'grip';
  45820. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  45821. EVENTS[ANIMATIONS.point] = 'pointing';
  45822. /**
  45823. * Hand controls component that abstracts 6DoF controls:
  45824. * oculus-touch-controls, vive-controls, windows-motion-controls.
  45825. *
  45826. * Originally meant to be a sample implementation of applications-specific controls that
  45827. * abstracts multiple types of controllers.
  45828. *
  45829. * Auto-detect appropriate controller.
  45830. * Handle common events coming from the detected vendor-specific controls.
  45831. * Translate button events to semantic hand-related event names:
  45832. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  45833. * Load hand model with gestures that are applied based on the button pressed.
  45834. *
  45835. * @property {string} Hand mapping (`left`, `right`).
  45836. */
  45837. module.exports.Component = registerComponent('hand-controls', {
  45838. schema: {
  45839. color: {default: 'white', type: 'color'},
  45840. hand: { default: 'left' },
  45841. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  45842. },
  45843. init: function () {
  45844. var self = this;
  45845. var el = this.el;
  45846. // Current pose.
  45847. this.gesture = ANIMATIONS.open;
  45848. // Active buttons populated by events provided by the attached controls.
  45849. this.pressedButtons = {};
  45850. this.touchedButtons = {};
  45851. this.loader = new THREE.GLTFLoader();
  45852. this.loader.setCrossOrigin('anonymous');
  45853. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  45854. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  45855. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  45856. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  45857. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  45858. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  45859. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  45860. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  45861. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  45862. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  45863. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  45864. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  45865. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  45866. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  45867. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  45868. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  45869. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  45870. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  45871. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  45872. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  45873. this.onControllerConnected = this.onControllerConnected.bind(this);
  45874. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  45875. el.addEventListener('controllerconnected', this.onControllerConnected);
  45876. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  45877. // Hidden by default.
  45878. el.object3D.visible = false;
  45879. },
  45880. play: function () {
  45881. this.addEventListeners();
  45882. },
  45883. pause: function () {
  45884. this.removeEventListeners();
  45885. },
  45886. tick: function (time, delta) {
  45887. var mesh = this.el.getObject3D('mesh');
  45888. if (!mesh || !mesh.mixer) { return; }
  45889. mesh.mixer.update(delta / 1000);
  45890. },
  45891. onControllerConnected: function () {
  45892. this.el.object3D.visible = true;
  45893. },
  45894. onControllerDisconnected: function () {
  45895. this.el.object3D.visible = false;
  45896. },
  45897. addEventListeners: function () {
  45898. var el = this.el;
  45899. el.addEventListener('gripdown', this.onGripDown);
  45900. el.addEventListener('gripup', this.onGripUp);
  45901. el.addEventListener('trackpaddown', this.onTrackpadDown);
  45902. el.addEventListener('trackpadup', this.onTrackpadUp);
  45903. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45904. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45905. el.addEventListener('triggerdown', this.onTriggerDown);
  45906. el.addEventListener('triggerup', this.onTriggerUp);
  45907. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  45908. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  45909. el.addEventListener('griptouchstart', this.onGripTouchStart);
  45910. el.addEventListener('griptouchend', this.onGripTouchEnd);
  45911. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  45912. el.addEventListener('thumbstickup', this.onThumbstickUp);
  45913. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  45914. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  45915. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45916. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45917. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45918. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45919. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45920. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45921. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45922. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45923. },
  45924. removeEventListeners: function () {
  45925. var el = this.el;
  45926. el.removeEventListener('gripdown', this.onGripDown);
  45927. el.removeEventListener('gripup', this.onGripUp);
  45928. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  45929. el.removeEventListener('trackpadup', this.onTrackpadUp);
  45930. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45931. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45932. el.removeEventListener('triggerdown', this.onTriggerDown);
  45933. el.removeEventListener('triggerup', this.onTriggerUp);
  45934. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  45935. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  45936. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  45937. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  45938. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  45939. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  45940. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  45941. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  45942. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45943. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45944. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45945. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45946. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45947. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45948. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45949. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45950. },
  45951. /**
  45952. * Update handler. More like the `init` handler since the only property is the hand, and
  45953. * that won't be changing much.
  45954. */
  45955. update: function (previousHand) {
  45956. var controlConfiguration;
  45957. var el = this.el;
  45958. var hand = this.data.hand;
  45959. var handModelStyle = this.data.handModelStyle;
  45960. var handColor = this.data.color;
  45961. var self = this;
  45962. // Get common configuration to abstract different vendor controls.
  45963. controlConfiguration = {
  45964. hand: hand,
  45965. model: false
  45966. };
  45967. // Set model.
  45968. if (hand !== previousHand) {
  45969. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  45970. this.loader.load(handmodelUrl, function (gltf) {
  45971. var mesh = gltf.scene.children[0];
  45972. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  45973. mesh.mixer = new THREE.AnimationMixer(mesh);
  45974. self.clips = gltf.animations;
  45975. el.setObject3D('mesh', mesh);
  45976. var handMaterial = mesh.children[1].material;
  45977. handMaterial.color = new THREE.Color(handColor);
  45978. mesh.position.set(0, 0, 0);
  45979. mesh.rotation.set(0, 0, handModelOrientation);
  45980. el.setAttribute('magicleap-controls', controlConfiguration);
  45981. el.setAttribute('vive-controls', controlConfiguration);
  45982. el.setAttribute('oculus-touch-controls', controlConfiguration);
  45983. el.setAttribute('windows-motion-controls', controlConfiguration);
  45984. });
  45985. }
  45986. },
  45987. remove: function () {
  45988. this.el.removeObject3D('mesh');
  45989. },
  45990. /**
  45991. * Play model animation, based on which button was pressed and which kind of event.
  45992. *
  45993. * 1. Process buttons.
  45994. * 2. Determine gesture (this.determineGesture()).
  45995. * 3. Animation gesture (this.animationGesture()).
  45996. * 4. Emit gesture events (this.emitGestureEvents()).
  45997. *
  45998. * @param {string} button - Name of the button.
  45999. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  46000. */
  46001. handleButton: function (button, evt) {
  46002. var lastGesture;
  46003. var isPressed = evt === 'down';
  46004. var isTouched = evt === 'touchstart';
  46005. // Update objects.
  46006. if (evt.indexOf('touch') === 0) {
  46007. // Update touch object.
  46008. if (isTouched === this.touchedButtons[button]) { return; }
  46009. this.touchedButtons[button] = isTouched;
  46010. } else {
  46011. // Update button object.
  46012. if (isPressed === this.pressedButtons[button]) { return; }
  46013. this.pressedButtons[button] = isPressed;
  46014. }
  46015. // Determine the gesture.
  46016. lastGesture = this.gesture;
  46017. this.gesture = this.determineGesture();
  46018. // Same gesture.
  46019. if (this.gesture === lastGesture) { return; }
  46020. // Animate gesture.
  46021. this.animateGesture(this.gesture, lastGesture);
  46022. // Emit events.
  46023. this.emitGestureEvents(this.gesture, lastGesture);
  46024. },
  46025. /**
  46026. * Determine which pose hand should be in considering active and touched buttons.
  46027. */
  46028. determineGesture: function () {
  46029. var gesture;
  46030. var isGripActive = this.pressedButtons.grip;
  46031. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  46032. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  46033. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  46034. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  46035. var isVive = isViveController(this.el.components['tracked-controls']);
  46036. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  46037. if (isVive) {
  46038. if (isGripActive || isTriggerActive) {
  46039. gesture = ANIMATIONS.fist;
  46040. } else if (isTrackpadActive) {
  46041. gesture = ANIMATIONS.point;
  46042. }
  46043. } else {
  46044. if (isGripActive) {
  46045. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  46046. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  46047. } else {
  46048. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  46049. }
  46050. } else if (isTriggerActive) {
  46051. gesture = ANIMATIONS.hold;
  46052. }
  46053. }
  46054. return gesture;
  46055. },
  46056. /**
  46057. * Play corresponding clip to a gesture
  46058. */
  46059. getClip: function (gesture) {
  46060. var clip;
  46061. var i;
  46062. for (i = 0; i < this.clips.length; i++) {
  46063. clip = this.clips[i];
  46064. if (clip.name !== gesture) { continue; }
  46065. return clip;
  46066. }
  46067. },
  46068. /**
  46069. * Play gesture animation.
  46070. *
  46071. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  46072. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  46073. */
  46074. animateGesture: function (gesture, lastGesture) {
  46075. if (gesture) {
  46076. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  46077. return;
  46078. }
  46079. // If no gesture, then reverse the current gesture back to open pose.
  46080. this.playAnimation(lastGesture, lastGesture, true);
  46081. },
  46082. /**
  46083. * Emit `hand-controls`-specific events.
  46084. */
  46085. emitGestureEvents: function (gesture, lastGesture) {
  46086. var el = this.el;
  46087. var eventName;
  46088. if (lastGesture === gesture) { return; }
  46089. // Emit event for lastGesture not inactive.
  46090. eventName = getGestureEventName(lastGesture, false);
  46091. if (eventName) { el.emit(eventName); }
  46092. // Emit event for current gesture now active.
  46093. eventName = getGestureEventName(gesture, true);
  46094. if (eventName) { el.emit(eventName); }
  46095. },
  46096. /**
  46097. * Play hand animation based on button state.
  46098. *
  46099. * @param {string} gesture - Name of the animation as specified by the model.
  46100. * @param {string} lastGesture - Previous pose.
  46101. * @param {boolean} reverse - Whether animation should play in reverse.
  46102. */
  46103. playAnimation: function (gesture, lastGesture, reverse) {
  46104. var clip;
  46105. var fromAction;
  46106. var mesh = this.el.getObject3D('mesh');
  46107. var toAction;
  46108. if (!mesh) { return; }
  46109. // Stop all current animations.
  46110. mesh.mixer.stopAllAction();
  46111. // Grab clip action.
  46112. clip = this.getClip(gesture);
  46113. toAction = mesh.mixer.clipAction(clip);
  46114. toAction.clampWhenFinished = true;
  46115. toAction.loop = THREE.LoopRepeat;
  46116. toAction.repetitions = 0;
  46117. toAction.timeScale = reverse ? -1 : 1;
  46118. toAction.time = reverse ? clip.duration : 0;
  46119. toAction.weight = 1;
  46120. // No gesture to gesture or gesture to no gesture.
  46121. if (!lastGesture || gesture === lastGesture) {
  46122. // Stop all current animations.
  46123. mesh.mixer.stopAllAction();
  46124. // Play animation.
  46125. toAction.play();
  46126. return;
  46127. }
  46128. // Animate or crossfade from gesture to gesture.
  46129. clip = this.getClip(lastGesture);
  46130. fromAction = mesh.mixer.clipAction(clip);
  46131. fromAction.weight = 0.15;
  46132. fromAction.play();
  46133. toAction.play();
  46134. fromAction.crossFadeTo(toAction, 0.15, true);
  46135. }
  46136. });
  46137. /**
  46138. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  46139. *
  46140. * @param {string} gesture
  46141. * @param {boolean} active
  46142. */
  46143. function getGestureEventName (gesture, active) {
  46144. var eventName;
  46145. if (!gesture) { return; }
  46146. eventName = EVENTS[gesture];
  46147. if (eventName === 'grip') {
  46148. return eventName + (active ? 'close' : 'open');
  46149. }
  46150. if (eventName === 'point') {
  46151. return eventName + (active ? 'up' : 'down');
  46152. }
  46153. if (eventName === 'pointing' || eventName === 'pistol') {
  46154. return eventName + (active ? 'start' : 'end');
  46155. }
  46156. }
  46157. function isViveController (trackedControls) {
  46158. var controller = trackedControls && trackedControls.controller;
  46159. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  46160. (controller.profiles &&
  46161. controller.profiles[0] &&
  46162. controller.profiles[0] === 'htc-vive-controller-mv'));
  46163. return isVive;
  46164. }
  46165. },{"../core/component":129}],82:[function(_dereq_,module,exports){
  46166. /* global THREE, XRRigidTransform, XRHand */
  46167. var registerComponent = _dereq_('../core/component').registerComponent;
  46168. var bind = _dereq_('../utils/bind');
  46169. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46170. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46171. var JOINTS_NUMBER = 25;
  46172. var LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/left.glb';
  46173. var RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/right.glb';
  46174. var BONE_PREFIX = {
  46175. left: 'b_l_',
  46176. right: 'b_r_'
  46177. };
  46178. var BONE_MAPPING = [
  46179. 'wrist',
  46180. 'thumb1',
  46181. 'thumb2',
  46182. 'thumb3',
  46183. 'thumb_null',
  46184. null,
  46185. 'index1',
  46186. 'index2',
  46187. 'index3',
  46188. 'index_null',
  46189. null,
  46190. 'middle1',
  46191. 'middle2',
  46192. 'middle3',
  46193. 'middle_null',
  46194. null,
  46195. 'ring1',
  46196. 'ring2',
  46197. 'ring3',
  46198. 'ring_null',
  46199. 'pinky0',
  46200. 'pinky1',
  46201. 'pinky2',
  46202. 'pinky3',
  46203. 'pinky_null'
  46204. ];
  46205. var PINCH_START_DISTANCE = 0.015;
  46206. var PINCH_END_DISTANCE = 0.03;
  46207. var PINCH_POSITION_INTERPOLATION = 0.5;
  46208. /**
  46209. * Controls for hand tracking
  46210. */
  46211. module.exports.Component = registerComponent('hand-tracking-controls', {
  46212. schema: {
  46213. hand: {default: 'right', oneOf: ['left', 'right']},
  46214. modelStyle: {default: 'mesh', oneOf: ['dots', 'mesh']},
  46215. modelColor: {default: 'white'}
  46216. },
  46217. bindMethods: function () {
  46218. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46219. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46220. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46221. },
  46222. addEventListeners: function () {
  46223. this.el.addEventListener('model-loaded', this.onModelLoaded);
  46224. for (var i = 0; i < this.jointEls.length; ++i) {
  46225. this.jointEls[i].object3D.visible = true;
  46226. }
  46227. },
  46228. removeEventListeners: function () {
  46229. this.el.removeEventListener('model-loaded', this.onModelLoaded);
  46230. for (var i = 0; i < this.jointEls.length; ++i) {
  46231. this.jointEls[i].object3D.visible = false;
  46232. }
  46233. },
  46234. init: function () {
  46235. var sceneEl = this.el.sceneEl;
  46236. var webXROptionalAttributes = sceneEl.getAttribute('webxr').optionalFeatures;
  46237. webXROptionalAttributes.push('hand-tracking');
  46238. sceneEl.setAttribute('webxr', {optionalFeatures: webXROptionalAttributes});
  46239. this.onModelLoaded = this.onModelLoaded.bind(this);
  46240. this.jointEls = [];
  46241. this.controllerPresent = false;
  46242. this.isPinched = false;
  46243. this.pinchEventDetail = {position: new THREE.Vector3()};
  46244. this.indexTipPosition = new THREE.Vector3();
  46245. this.bindMethods();
  46246. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  46247. this.el.sceneEl.addEventListener('enter-vr', this.updateReferenceSpace);
  46248. this.el.sceneEl.addEventListener('exit-vr', this.updateReferenceSpace);
  46249. },
  46250. updateReferenceSpace: function () {
  46251. var self = this;
  46252. var xrSession = this.el.sceneEl.xrSession;
  46253. this.referenceSpace = undefined;
  46254. if (!xrSession) { return; }
  46255. var referenceSpaceType = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  46256. xrSession.requestReferenceSpace(referenceSpaceType).then(function (referenceSpace) {
  46257. self.referenceSpace = referenceSpace.getOffsetReferenceSpace(new XRRigidTransform({x: 0, y: 1.5, z: 0}));
  46258. }).catch(function (error) {
  46259. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(referenceSpaceType, 'tracked-controls-webxr uses reference space ' + referenceSpaceType);
  46260. throw error;
  46261. });
  46262. },
  46263. checkIfControllerPresent: function () {
  46264. var data = this.data;
  46265. var hand = data.hand ? data.hand : undefined;
  46266. checkControllerPresentAndSetup(
  46267. this, '',
  46268. {hand: hand, iterateControllerProfiles: true, handTracking: true});
  46269. },
  46270. play: function () {
  46271. this.checkIfControllerPresent();
  46272. this.addControllersUpdateListener();
  46273. },
  46274. tick: function () {
  46275. var sceneEl = this.el.sceneEl;
  46276. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46277. var frame = sceneEl.frame;
  46278. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46279. if (!controller || !frame || !trackedControlsWebXR) { return; }
  46280. if (controller.hand) {
  46281. this.el.object3D.position.set(0, 0, 0);
  46282. this.el.object3D.rotation.set(0, 0, 0);
  46283. if (frame.getJointPose) { this.updateHandModel(); }
  46284. this.detectGesture();
  46285. }
  46286. },
  46287. updateHandModel: function () {
  46288. if (this.data.modelStyle === 'dots') {
  46289. this.updateHandDotsModel();
  46290. }
  46291. if (this.data.modelStyle === 'mesh') {
  46292. this.updateHandMeshModel();
  46293. }
  46294. },
  46295. updateHandMeshModel: function () {
  46296. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46297. var referenceSpace = this.referenceSpace;
  46298. if (!controller || !this.mesh || !referenceSpace) { return; }
  46299. this.mesh.visible = false;
  46300. for (var i = 0; i < controller.hand.length; i++) {
  46301. var bone;
  46302. var jointPose;
  46303. var jointTransform;
  46304. if (!controller.hand[i]) { continue; }
  46305. jointPose = this.el.sceneEl.frame.getJointPose(controller.hand[i], referenceSpace);
  46306. if (BONE_MAPPING[i] == null) { continue; }
  46307. bone = this.getBone(BONE_PREFIX[this.data.hand] + BONE_MAPPING[i]);
  46308. if (bone != null && jointPose) {
  46309. jointTransform = jointPose.transform;
  46310. this.mesh.visible = true;
  46311. bone.position.copy(jointTransform.position).multiplyScalar(100);
  46312. bone.quaternion.set(jointTransform.orientation.x, jointTransform.orientation.y, jointTransform.orientation.z, jointTransform.orientation.w);
  46313. }
  46314. }
  46315. },
  46316. getBone: function (name) {
  46317. var bones = this.bones;
  46318. for (var i = 0; i < bones.length; i++) {
  46319. if (bones[i].name === name) { return bones[i]; }
  46320. }
  46321. return null;
  46322. },
  46323. updateHandDotsModel: function () {
  46324. var frame = this.el.sceneEl.frame;
  46325. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46326. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46327. var referenceSpace = trackedControlsWebXR.system.referenceSpace;
  46328. for (var i = 0; i < this.jointEls.length; ++i) {
  46329. var jointEl = this.jointEls[i];
  46330. jointEl.object3D.visible = !!controller.hand[i];
  46331. if (controller.hand[i]) {
  46332. var object3D = jointEl.object3D;
  46333. var pose = frame.getJointPose(controller.hand[i], referenceSpace);
  46334. jointEl.object3D.visible = !!pose;
  46335. if (!pose) { continue; }
  46336. object3D.matrix.elements = pose.transform.matrix;
  46337. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  46338. jointEl.setAttribute('scale', {x: pose.radius, y: pose.radius, z: pose.radius});
  46339. }
  46340. }
  46341. },
  46342. detectGesture: function () {
  46343. this.detectPinch();
  46344. },
  46345. detectPinch: (function () {
  46346. var thumbTipPosition = new THREE.Vector3();
  46347. return function () {
  46348. var frame = this.el.sceneEl.frame;
  46349. var indexTipPosition = this.indexTipPosition;
  46350. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46351. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46352. var referenceSpace = this.referenceSpace || trackedControlsWebXR.system.referenceSpace;
  46353. if (!controller.hand[XRHand.INDEX_PHALANX_TIP] ||
  46354. !controller.hand[XRHand.THUMB_PHALANX_TIP]) { return; }
  46355. var indexTipPose = frame.getJointPose(controller.hand[XRHand.INDEX_PHALANX_TIP], referenceSpace);
  46356. var thumbTipPose = frame.getJointPose(controller.hand[XRHand.THUMB_PHALANX_TIP], referenceSpace);
  46357. if (!indexTipPose || !thumbTipPose) { return; }
  46358. thumbTipPosition.copy(thumbTipPose.transform.position);
  46359. indexTipPosition.copy(indexTipPose.transform.position);
  46360. var distance = indexTipPosition.distanceTo(thumbTipPosition);
  46361. if (distance < PINCH_START_DISTANCE && this.isPinched === false) {
  46362. this.isPinched = true;
  46363. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46364. this.pinchEventDetail.position.y += 1.5;
  46365. this.el.emit('pinchstarted', this.pinchEventDetail);
  46366. }
  46367. if (distance > PINCH_END_DISTANCE && this.isPinched === true) {
  46368. this.isPinched = false;
  46369. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46370. this.pinchEventDetail.position.y += 1.5;
  46371. this.el.emit('pinchended', this.pinchEventDetail);
  46372. }
  46373. if (this.isPinched) {
  46374. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46375. this.pinchEventDetail.position.y += 1.5;
  46376. this.el.emit('pinchmoved', this.pinchEventDetail);
  46377. }
  46378. indexTipPosition.y += 1.5;
  46379. };
  46380. })(),
  46381. pause: function () {
  46382. this.removeEventListeners();
  46383. this.removeControllersUpdateListener();
  46384. },
  46385. injectTrackedControls: function () {
  46386. var el = this.el;
  46387. var data = this.data;
  46388. el.setAttribute('tracked-controls', {
  46389. hand: data.hand,
  46390. iterateControllerProfiles: true,
  46391. handTrackingEnabled: true
  46392. });
  46393. this.initDefaultModel();
  46394. },
  46395. addControllersUpdateListener: function () {
  46396. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46397. },
  46398. removeControllersUpdateListener: function () {
  46399. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46400. },
  46401. onControllersUpdate: function () {
  46402. var controller;
  46403. this.checkIfControllerPresent();
  46404. controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46405. if (!this.el.getObject3D('mesh')) { return; }
  46406. if (!controller || !controller.hand || !controller.hand[0]) {
  46407. this.el.removeObject3D('mesh');
  46408. }
  46409. },
  46410. initDefaultModel: function () {
  46411. if (this.data.modelStyle === 'dots') {
  46412. this.initDotsModel();
  46413. }
  46414. if (this.data.modelStyle === 'mesh') {
  46415. this.initMeshHandModel();
  46416. }
  46417. },
  46418. initDotsModel: function () {
  46419. // Add models just once.
  46420. if (this.jointEls.length !== 0) { return; }
  46421. for (var i = 0; i < JOINTS_NUMBER; ++i) {
  46422. var jointEl = this.jointEl = document.createElement('a-entity');
  46423. jointEl.setAttribute('geometry', {
  46424. primitive: 'sphere',
  46425. radius: 1.0
  46426. });
  46427. jointEl.setAttribute('material', {color: this.data.modelColor});
  46428. jointEl.object3D.visible = false;
  46429. this.el.appendChild(jointEl);
  46430. this.jointEls.push(jointEl);
  46431. }
  46432. },
  46433. initMeshHandModel: function () {
  46434. var modelURL = this.data.hand === 'left' ? LEFT_HAND_MODEL_URL : RIGHT_HAND_MODEL_URL;
  46435. this.el.setAttribute('gltf-model', modelURL);
  46436. },
  46437. onModelLoaded: function () {
  46438. var mesh = this.mesh = this.el.getObject3D('mesh').children[0];
  46439. var skinnedMesh = this.skinnedMesh = mesh.children[24];
  46440. if (!this.skinnedMesh) { return; }
  46441. this.bones = skinnedMesh.skeleton.bones;
  46442. this.el.removeObject3D('mesh');
  46443. mesh.position.set(0, 1.5, 0);
  46444. mesh.rotation.set(0, 0, 0);
  46445. skinnedMesh.frustumCulled = false;
  46446. skinnedMesh.material = new THREE.MeshStandardMaterial({skinning: true, color: this.data.modelColor});
  46447. this.el.setObject3D('mesh', mesh);
  46448. }
  46449. });
  46450. },{"../core/component":129,"../utils/bind":197,"../utils/tracked-controls":211}],83:[function(_dereq_,module,exports){
  46451. _dereq_('./animation');
  46452. _dereq_('./camera');
  46453. _dereq_('./cursor');
  46454. _dereq_('./daydream-controls');
  46455. _dereq_('./gearvr-controls');
  46456. _dereq_('./geometry');
  46457. _dereq_('./generic-tracked-controller-controls');
  46458. _dereq_('./gltf-model');
  46459. _dereq_('./hand-tracking-controls');
  46460. _dereq_('./hand-controls');
  46461. _dereq_('./laser-controls');
  46462. _dereq_('./light');
  46463. _dereq_('./line');
  46464. _dereq_('./link');
  46465. _dereq_('./look-controls');
  46466. _dereq_('./magicleap-controls');
  46467. _dereq_('./material');
  46468. _dereq_('./obj-model');
  46469. _dereq_('./oculus-go-controls');
  46470. _dereq_('./oculus-touch-controls');
  46471. _dereq_('./position');
  46472. _dereq_('./raycaster');
  46473. _dereq_('./rotation');
  46474. _dereq_('./scale');
  46475. _dereq_('./shadow');
  46476. _dereq_('./sound');
  46477. _dereq_('./text');
  46478. _dereq_('./tracked-controls');
  46479. _dereq_('./tracked-controls-webvr');
  46480. _dereq_('./tracked-controls-webxr');
  46481. _dereq_('./visible');
  46482. _dereq_('./valve-index-controls');
  46483. _dereq_('./vive-controls');
  46484. _dereq_('./vive-focus-controls');
  46485. _dereq_('./wasd-controls');
  46486. _dereq_('./windows-motion-controls');
  46487. _dereq_('./scene/background');
  46488. _dereq_('./scene/debug');
  46489. _dereq_('./scene/device-orientation-permission-ui');
  46490. _dereq_('./scene/embedded');
  46491. _dereq_('./scene/inspector');
  46492. _dereq_('./scene/fog');
  46493. _dereq_('./scene/keyboard-shortcuts');
  46494. _dereq_('./scene/pool');
  46495. _dereq_('./scene/screenshot');
  46496. _dereq_('./scene/stats');
  46497. _dereq_('./scene/vr-mode-ui');
  46498. },{"./animation":73,"./camera":74,"./cursor":75,"./daydream-controls":76,"./gearvr-controls":77,"./generic-tracked-controller-controls":78,"./geometry":79,"./gltf-model":80,"./hand-controls":81,"./hand-tracking-controls":82,"./laser-controls":84,"./light":85,"./line":86,"./link":87,"./look-controls":88,"./magicleap-controls":89,"./material":90,"./obj-model":91,"./oculus-go-controls":92,"./oculus-touch-controls":93,"./position":94,"./raycaster":95,"./rotation":96,"./scale":97,"./scene/background":98,"./scene/debug":99,"./scene/device-orientation-permission-ui":100,"./scene/embedded":101,"./scene/fog":102,"./scene/inspector":103,"./scene/keyboard-shortcuts":104,"./scene/pool":105,"./scene/screenshot":106,"./scene/stats":107,"./scene/vr-mode-ui":108,"./shadow":109,"./sound":110,"./text":111,"./tracked-controls":114,"./tracked-controls-webvr":112,"./tracked-controls-webxr":113,"./valve-index-controls":115,"./visible":116,"./vive-controls":117,"./vive-focus-controls":118,"./wasd-controls":119,"./windows-motion-controls":120}],84:[function(_dereq_,module,exports){
  46499. var registerComponent = _dereq_('../core/component').registerComponent;
  46500. var utils = _dereq_('../utils/');
  46501. registerComponent('laser-controls', {
  46502. schema: {
  46503. hand: {default: 'right'},
  46504. model: {default: true},
  46505. defaultModelColor: {type: 'color', default: 'grey'}
  46506. },
  46507. init: function () {
  46508. var config = this.config;
  46509. var data = this.data;
  46510. var el = this.el;
  46511. var self = this;
  46512. var controlsConfiguration = {hand: data.hand, model: data.model};
  46513. // Set all controller models.
  46514. el.setAttribute('daydream-controls', controlsConfiguration);
  46515. el.setAttribute('gearvr-controls', controlsConfiguration);
  46516. el.setAttribute('magicleap-controls', controlsConfiguration);
  46517. el.setAttribute('oculus-go-controls', controlsConfiguration);
  46518. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  46519. el.setAttribute('valve-index-controls', controlsConfiguration);
  46520. el.setAttribute('vive-controls', controlsConfiguration);
  46521. el.setAttribute('vive-focus-controls', controlsConfiguration);
  46522. el.setAttribute('windows-motion-controls', controlsConfiguration);
  46523. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  46524. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  46525. el.addEventListener('controllerconnected', createRay);
  46526. el.addEventListener('controllerdisconnected', hideRay);
  46527. el.addEventListener('controllermodelready', function (evt) {
  46528. createRay(evt);
  46529. self.modelReady = true;
  46530. });
  46531. function createRay (evt) {
  46532. var controllerConfig = config[evt.detail.name];
  46533. if (!controllerConfig) { return; }
  46534. // Show the line unless a particular config opts to hide it, until a controllermodelready
  46535. // event comes through.
  46536. var raycasterConfig = utils.extend({
  46537. showLine: true
  46538. }, controllerConfig.raycaster || {});
  46539. // The controllermodelready event contains a rayOrigin that takes into account
  46540. // offsets specific to the loaded model.
  46541. if (evt.detail.rayOrigin) {
  46542. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  46543. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  46544. raycasterConfig.showLine = true;
  46545. }
  46546. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  46547. // config applied from a controllermodelready event.
  46548. if (evt.detail.rayOrigin || !self.modelReady) {
  46549. el.setAttribute('raycaster', raycasterConfig);
  46550. } else {
  46551. el.setAttribute('raycaster', 'showLine', true);
  46552. }
  46553. el.setAttribute('cursor', utils.extend({
  46554. fuse: false
  46555. }, controllerConfig.cursor));
  46556. }
  46557. function hideRay () {
  46558. el.setAttribute('raycaster', 'showLine', false);
  46559. }
  46560. },
  46561. config: {
  46562. 'daydream-controls': {
  46563. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46564. },
  46565. 'gearvr-controls': {
  46566. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46567. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  46568. },
  46569. 'generic-tracked-controller-controls': {
  46570. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46571. },
  46572. 'magicleap-controls': {
  46573. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46574. },
  46575. 'oculus-go-controls': {
  46576. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46577. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  46578. },
  46579. 'oculus-touch-controls': {
  46580. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46581. raycaster: {origin: {x: 0, y: 0, z: 0}}
  46582. },
  46583. 'valve-index-controls': {
  46584. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46585. },
  46586. 'vive-controls': {
  46587. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46588. },
  46589. 'vive-focus-controls': {
  46590. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46591. },
  46592. 'windows-motion-controls': {
  46593. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46594. raycaster: {showLine: false}
  46595. }
  46596. }
  46597. });
  46598. },{"../core/component":129,"../utils/":203}],85:[function(_dereq_,module,exports){
  46599. var bind = _dereq_('../utils/bind');
  46600. var diff = _dereq_('../utils').diff;
  46601. var debug = _dereq_('../utils/debug');
  46602. var registerComponent = _dereq_('../core/component').registerComponent;
  46603. var THREE = _dereq_('../lib/three');
  46604. var degToRad = THREE.Math.degToRad;
  46605. var warn = debug('components:light:warn');
  46606. /**
  46607. * Light component.
  46608. */
  46609. module.exports.Component = registerComponent('light', {
  46610. schema: {
  46611. angle: {default: 60, if: {type: ['spot']}},
  46612. color: {type: 'color'},
  46613. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  46614. decay: {default: 1, if: {type: ['point', 'spot']}},
  46615. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  46616. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  46617. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  46618. type: {
  46619. default: 'directional',
  46620. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  46621. schemaChange: true
  46622. },
  46623. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  46624. // Shadows.
  46625. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  46626. shadowBias: {default: 0, if: {castShadow: true}},
  46627. shadowCameraFar: {default: 500, if: {castShadow: true}},
  46628. shadowCameraFov: {default: 90, if: {castShadow: true}},
  46629. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  46630. shadowCameraTop: {default: 5, if: {castShadow: true}},
  46631. shadowCameraRight: {default: 5, if: {castShadow: true}},
  46632. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  46633. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  46634. shadowCameraVisible: {default: false, if: {castShadow: true}},
  46635. shadowMapHeight: {default: 512, if: {castShadow: true}},
  46636. shadowMapWidth: {default: 512, if: {castShadow: true}},
  46637. shadowRadius: {default: 1, if: {castShadow: true}}
  46638. },
  46639. /**
  46640. * Notifies scene a light has been added to remove default lighting.
  46641. */
  46642. init: function () {
  46643. var el = this.el;
  46644. this.light = null;
  46645. this.defaultTarget = null;
  46646. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46647. this.system.registerLight(el);
  46648. },
  46649. /**
  46650. * (Re)create or update light.
  46651. */
  46652. update: function (oldData) {
  46653. var data = this.data;
  46654. var diffData = diff(data, oldData);
  46655. var light = this.light;
  46656. var rendererSystem = this.rendererSystem;
  46657. var self = this;
  46658. // Existing light.
  46659. if (light && !('type' in diffData)) {
  46660. var shadowsLoaded = false;
  46661. // Light type has not changed. Update light.
  46662. Object.keys(diffData).forEach(function (key) {
  46663. var value = data[key];
  46664. switch (key) {
  46665. case 'color': {
  46666. light.color.set(value);
  46667. rendererSystem.applyColorCorrection(light.color);
  46668. break;
  46669. }
  46670. case 'groundColor': {
  46671. light.groundColor.set(value);
  46672. rendererSystem.applyColorCorrection(light.groundColor);
  46673. break;
  46674. }
  46675. case 'angle': {
  46676. light.angle = degToRad(value);
  46677. break;
  46678. }
  46679. case 'target': {
  46680. // Reset target if selector is null.
  46681. if (value === null) {
  46682. if (data.type === 'spot' || data.type === 'directional') {
  46683. light.target = self.defaultTarget;
  46684. }
  46685. } else {
  46686. // Target specified, set target to entity's `object3D` when it is loaded.
  46687. if (value.hasLoaded) {
  46688. self.onSetTarget(value, light);
  46689. } else {
  46690. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  46691. }
  46692. }
  46693. break;
  46694. }
  46695. case 'castShadow':
  46696. case 'shadowBias':
  46697. case 'shadowCameraFar':
  46698. case 'shadowCameraFov':
  46699. case 'shadowCameraNear':
  46700. case 'shadowCameraTop':
  46701. case 'shadowCameraRight':
  46702. case 'shadowCameraBottom':
  46703. case 'shadowCameraLeft':
  46704. case 'shadowCameraVisible':
  46705. case 'shadowMapHeight':
  46706. case 'shadowMapWidth':
  46707. case 'shadowRadius':
  46708. if (!shadowsLoaded) {
  46709. self.updateShadow();
  46710. shadowsLoaded = true;
  46711. }
  46712. break;
  46713. default: {
  46714. light[key] = value;
  46715. }
  46716. }
  46717. });
  46718. return;
  46719. }
  46720. // No light yet or light type has changed. Create and add light.
  46721. this.setLight(this.data);
  46722. this.updateShadow();
  46723. },
  46724. setLight: function (data) {
  46725. var el = this.el;
  46726. var newLight = this.getLight(data);
  46727. if (newLight) {
  46728. if (this.light) {
  46729. el.removeObject3D('light');
  46730. }
  46731. this.light = newLight;
  46732. this.light.el = el;
  46733. el.setObject3D('light', this.light);
  46734. // HACK solution for issue #1624
  46735. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  46736. el.getObject3D('light').translateY(-1);
  46737. }
  46738. // set and position default lighttarget as a child to enable spotlight orientation
  46739. if (data.type === 'spot') {
  46740. el.setObject3D('light-target', this.defaultTarget);
  46741. el.getObject3D('light-target').position.set(0, 0, -1);
  46742. }
  46743. }
  46744. },
  46745. /**
  46746. * Updates shadow-related properties on the current light.
  46747. */
  46748. updateShadow: function () {
  46749. var el = this.el;
  46750. var data = this.data;
  46751. var light = this.light;
  46752. light.castShadow = data.castShadow;
  46753. // Shadow camera helper.
  46754. var cameraHelper = el.getObject3D('cameraHelper');
  46755. if (data.shadowCameraVisible && !cameraHelper) {
  46756. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  46757. } else if (!data.shadowCameraVisible && cameraHelper) {
  46758. el.removeObject3D('cameraHelper');
  46759. }
  46760. if (!data.castShadow) { return light; }
  46761. // Shadow appearance.
  46762. light.shadow.bias = data.shadowBias;
  46763. light.shadow.radius = data.shadowRadius;
  46764. light.shadow.mapSize.height = data.shadowMapHeight;
  46765. light.shadow.mapSize.width = data.shadowMapWidth;
  46766. // Shadow camera.
  46767. light.shadow.camera.near = data.shadowCameraNear;
  46768. light.shadow.camera.far = data.shadowCameraFar;
  46769. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  46770. light.shadow.camera.top = data.shadowCameraTop;
  46771. light.shadow.camera.right = data.shadowCameraRight;
  46772. light.shadow.camera.bottom = data.shadowCameraBottom;
  46773. light.shadow.camera.left = data.shadowCameraLeft;
  46774. } else {
  46775. light.shadow.camera.fov = data.shadowCameraFov;
  46776. }
  46777. light.shadow.camera.updateProjectionMatrix();
  46778. if (cameraHelper) { cameraHelper.update(); }
  46779. },
  46780. /**
  46781. * Creates a new three.js light object given data object defining the light.
  46782. *
  46783. * @param {object} data
  46784. */
  46785. getLight: function (data) {
  46786. var angle = data.angle;
  46787. var color = new THREE.Color(data.color);
  46788. this.rendererSystem.applyColorCorrection(color);
  46789. color = color.getHex();
  46790. var decay = data.decay;
  46791. var distance = data.distance;
  46792. var groundColor = new THREE.Color(data.groundColor);
  46793. this.rendererSystem.applyColorCorrection(groundColor);
  46794. groundColor = groundColor.getHex();
  46795. var intensity = data.intensity;
  46796. var type = data.type;
  46797. var target = data.target;
  46798. var light = null;
  46799. switch (type.toLowerCase()) {
  46800. case 'ambient': {
  46801. return new THREE.AmbientLight(color, intensity);
  46802. }
  46803. case 'directional': {
  46804. light = new THREE.DirectionalLight(color, intensity);
  46805. this.defaultTarget = light.target;
  46806. if (target) {
  46807. if (target.hasLoaded) {
  46808. this.onSetTarget(target, light);
  46809. } else {
  46810. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  46811. }
  46812. }
  46813. return light;
  46814. }
  46815. case 'hemisphere': {
  46816. return new THREE.HemisphereLight(color, groundColor, intensity);
  46817. }
  46818. case 'point': {
  46819. return new THREE.PointLight(color, intensity, distance, decay);
  46820. }
  46821. case 'spot': {
  46822. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  46823. this.defaultTarget = light.target;
  46824. if (target) {
  46825. if (target.hasLoaded) {
  46826. this.onSetTarget(target, light);
  46827. } else {
  46828. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  46829. }
  46830. }
  46831. return light;
  46832. }
  46833. default: {
  46834. warn('%s is not a valid light type. ' +
  46835. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  46836. }
  46837. }
  46838. },
  46839. onSetTarget: function (targetEl, light) {
  46840. light.target = targetEl.object3D;
  46841. },
  46842. /**
  46843. * Remove light on remove (callback).
  46844. */
  46845. remove: function () {
  46846. var el = this.el;
  46847. el.removeObject3D('light');
  46848. if (el.getObject3D('cameraHelper')) {
  46849. el.removeObject3D('cameraHelper');
  46850. }
  46851. }
  46852. });
  46853. },{"../core/component":129,"../lib/three":177,"../utils":203,"../utils/bind":197,"../utils/debug":199}],86:[function(_dereq_,module,exports){
  46854. /* global THREE */
  46855. var registerComponent = _dereq_('../core/component').registerComponent;
  46856. module.exports.Component = registerComponent('line', {
  46857. schema: {
  46858. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  46859. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  46860. color: {type: 'color', default: '#74BEC1'},
  46861. opacity: {type: 'number', default: 1},
  46862. visible: {default: true}
  46863. },
  46864. multiple: true,
  46865. init: function () {
  46866. var data = this.data;
  46867. var geometry;
  46868. var material;
  46869. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46870. material = this.material = new THREE.LineBasicMaterial({
  46871. color: data.color,
  46872. opacity: data.opacity,
  46873. transparent: data.opacity < 1,
  46874. visible: data.visible
  46875. });
  46876. geometry = this.geometry = new THREE.BufferGeometry();
  46877. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  46878. this.rendererSystem.applyColorCorrection(material.color);
  46879. this.line = new THREE.Line(geometry, material);
  46880. this.el.setObject3D(this.attrName, this.line);
  46881. },
  46882. update: function (oldData) {
  46883. var data = this.data;
  46884. var geometry = this.geometry;
  46885. var geoNeedsUpdate = false;
  46886. var material = this.material;
  46887. var positionArray = geometry.attributes.position.array;
  46888. // Update geometry.
  46889. if (!isEqualVec3(data.start, oldData.start)) {
  46890. positionArray[0] = data.start.x;
  46891. positionArray[1] = data.start.y;
  46892. positionArray[2] = data.start.z;
  46893. geoNeedsUpdate = true;
  46894. }
  46895. if (!isEqualVec3(data.end, oldData.end)) {
  46896. positionArray[3] = data.end.x;
  46897. positionArray[4] = data.end.y;
  46898. positionArray[5] = data.end.z;
  46899. geoNeedsUpdate = true;
  46900. }
  46901. if (geoNeedsUpdate) {
  46902. geometry.attributes.position.needsUpdate = true;
  46903. geometry.computeBoundingSphere();
  46904. }
  46905. material.color.setStyle(data.color);
  46906. this.rendererSystem.applyColorCorrection(material.color);
  46907. material.opacity = data.opacity;
  46908. material.transparent = data.opacity < 1;
  46909. material.visible = data.visible;
  46910. },
  46911. remove: function () {
  46912. this.el.removeObject3D('line', this.line);
  46913. }
  46914. });
  46915. function isEqualVec3 (a, b) {
  46916. if (!a || !b) { return false; }
  46917. return (a.x === b.x && a.y === b.y && a.z === b.z);
  46918. }
  46919. },{"../core/component":129}],87:[function(_dereq_,module,exports){
  46920. var registerComponent = _dereq_('../core/component').registerComponent;
  46921. var registerShader = _dereq_('../core/shader').registerShader;
  46922. var THREE = _dereq_('../lib/three');
  46923. /**
  46924. * Link component. Connect experiences and traverse between them in VR
  46925. *
  46926. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  46927. */
  46928. module.exports.Component = registerComponent('link', {
  46929. schema: {
  46930. backgroundColor: {default: 'red', type: 'color'},
  46931. borderColor: {default: 'white', type: 'color'},
  46932. highlighted: {default: false},
  46933. highlightedColor: {default: '#24CAFF', type: 'color'},
  46934. href: {default: ''},
  46935. image: {type: 'asset'},
  46936. on: {default: 'click'},
  46937. peekMode: {default: false},
  46938. title: {default: ''},
  46939. titleColor: {default: 'white', type: 'color'},
  46940. visualAspectEnabled: {default: false}
  46941. },
  46942. init: function () {
  46943. this.navigate = this.navigate.bind(this);
  46944. this.previousQuaternion = undefined;
  46945. this.quaternionClone = new THREE.Quaternion();
  46946. // Store hidden elements during peek mode so we can show them again later.
  46947. this.hiddenEls = [];
  46948. },
  46949. update: function (oldData) {
  46950. var data = this.data;
  46951. var el = this.el;
  46952. var backgroundColor;
  46953. var strokeColor;
  46954. if (!data.visualAspectEnabled) { return; }
  46955. this.initVisualAspect();
  46956. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  46957. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  46958. el.setAttribute('material', 'backgroundColor', backgroundColor);
  46959. el.setAttribute('material', 'strokeColor', strokeColor);
  46960. if (data.on !== oldData.on) { this.updateEventListener(); }
  46961. if (oldData.peekMode !== undefined &&
  46962. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  46963. if (!data.image || oldData.image === data.image) { return; }
  46964. el.setAttribute('material', 'pano',
  46965. typeof data.image === 'string' ? data.image : data.image.src);
  46966. },
  46967. /*
  46968. * Toggle all elements and full 360 preview of the linked page.
  46969. */
  46970. updatePeekMode: function () {
  46971. var el = this.el;
  46972. var sphereEl = this.sphereEl;
  46973. if (this.data.peekMode) {
  46974. this.hideAll();
  46975. el.getObject3D('mesh').visible = false;
  46976. sphereEl.setAttribute('visible', true);
  46977. } else {
  46978. this.showAll();
  46979. el.getObject3D('mesh').visible = true;
  46980. sphereEl.setAttribute('visible', false);
  46981. }
  46982. },
  46983. play: function () {
  46984. this.updateEventListener();
  46985. },
  46986. pause: function () {
  46987. this.removeEventListener();
  46988. },
  46989. updateEventListener: function () {
  46990. var el = this.el;
  46991. if (!el.isPlaying) { return; }
  46992. this.removeEventListener();
  46993. el.addEventListener(this.data.on, this.navigate);
  46994. },
  46995. removeEventListener: function () {
  46996. var on = this.data.on;
  46997. if (!on) { return; }
  46998. this.el.removeEventListener(on, this.navigate);
  46999. },
  47000. initVisualAspect: function () {
  47001. var el = this.el;
  47002. var semiSphereEl;
  47003. var sphereEl;
  47004. var textEl;
  47005. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  47006. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  47007. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  47008. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  47009. // Set portal.
  47010. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  47011. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  47012. // Set text that displays the link title and URL.
  47013. textEl.setAttribute('text', {
  47014. color: this.data.titleColor,
  47015. align: 'center',
  47016. font: 'kelsonsans',
  47017. value: this.data.title || this.data.href,
  47018. width: 4
  47019. });
  47020. textEl.setAttribute('position', '0 1.5 0');
  47021. el.appendChild(textEl);
  47022. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  47023. semiSphereEl.setAttribute('geometry', {
  47024. primitive: 'sphere',
  47025. radius: 1.0,
  47026. phiStart: 0,
  47027. segmentsWidth: 64,
  47028. segmentsHeight: 64,
  47029. phiLength: 180,
  47030. thetaStart: 0,
  47031. thetaLength: 360
  47032. });
  47033. semiSphereEl.setAttribute('material', {
  47034. shader: 'portal',
  47035. borderEnabled: 0.0,
  47036. pano: this.data.image,
  47037. side: 'back'
  47038. });
  47039. semiSphereEl.setAttribute('rotation', '0 180 0');
  47040. semiSphereEl.setAttribute('position', '0 0 0');
  47041. semiSphereEl.setAttribute('visible', false);
  47042. el.appendChild(semiSphereEl);
  47043. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  47044. sphereEl.setAttribute('geometry', {
  47045. primitive: 'sphere',
  47046. radius: 10,
  47047. segmentsWidth: 64,
  47048. segmentsHeight: 64
  47049. });
  47050. sphereEl.setAttribute('material', {
  47051. shader: 'portal',
  47052. borderEnabled: 0.0,
  47053. pano: this.data.image,
  47054. side: 'back'
  47055. });
  47056. sphereEl.setAttribute('visible', false);
  47057. el.appendChild(sphereEl);
  47058. this.visualAspectInitialized = true;
  47059. },
  47060. navigate: function () {
  47061. window.location = this.data.href;
  47062. },
  47063. /**
  47064. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  47065. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  47066. * from where user enters.
  47067. * 2. Place the url/title above or inside portal depending on distance to camera.
  47068. * 3. Face portal to camera when far away from user.
  47069. */
  47070. tick: (function () {
  47071. var cameraWorldPosition = new THREE.Vector3();
  47072. var elWorldPosition = new THREE.Vector3();
  47073. var quaternion = new THREE.Quaternion();
  47074. var scale = new THREE.Vector3();
  47075. return function () {
  47076. var el = this.el;
  47077. var object3D = el.object3D;
  47078. var camera = el.sceneEl.camera;
  47079. var cameraPortalOrientation;
  47080. var distance;
  47081. var textEl = this.textEl;
  47082. if (!this.data.visualAspectEnabled) { return; }
  47083. // Update matrices
  47084. object3D.updateMatrixWorld();
  47085. camera.parent.updateMatrixWorld();
  47086. camera.updateMatrixWorld();
  47087. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  47088. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  47089. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  47090. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  47091. if (distance > 20) {
  47092. // Store original orientation to be restored when the portal stops facing the camera.
  47093. if (!this.previousQuaternion) {
  47094. this.quaternionClone.copy(quaternion);
  47095. this.previousQuaternion = this.quaternionClone;
  47096. }
  47097. // If the portal is far away from the user, face portal to camera.
  47098. object3D.lookAt(cameraWorldPosition);
  47099. } else {
  47100. // When portal is close to the user/camera.
  47101. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  47102. // If user gets very close to portal, replace with holed sphere they can peek in.
  47103. if (distance < 0.5) {
  47104. // Configure text size and sphere orientation depending side user approaches portal.
  47105. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  47106. textEl.setAttribute('text', 'width', 1.5);
  47107. if (cameraPortalOrientation <= 0.0) {
  47108. textEl.setAttribute('position', '0 0 0.75');
  47109. textEl.setAttribute('rotation', '0 180 0');
  47110. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  47111. } else {
  47112. textEl.setAttribute('position', '0 0 -0.75');
  47113. textEl.setAttribute('rotation', '0 0 0');
  47114. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  47115. }
  47116. el.getObject3D('mesh').visible = false;
  47117. this.semiSphereEl.setAttribute('visible', true);
  47118. this.peekCameraPortalOrientation = cameraPortalOrientation;
  47119. } else {
  47120. // Calculate wich side the camera is approaching the camera (back / front).
  47121. // Adjust text orientation based on camera position.
  47122. if (cameraPortalOrientation <= 0.0) {
  47123. textEl.setAttribute('rotation', '0 180 0');
  47124. } else {
  47125. textEl.setAttribute('rotation', '0 0 0');
  47126. }
  47127. textEl.setAttribute('text', 'width', 5);
  47128. textEl.setAttribute('position', '0 1.5 0');
  47129. el.getObject3D('mesh').visible = true;
  47130. this.semiSphereEl.setAttribute('visible', false);
  47131. this.peekCameraPortalOrientation = undefined;
  47132. }
  47133. if (this.previousQuaternion) {
  47134. object3D.quaternion.copy(this.previousQuaternion);
  47135. this.previousQuaternion = undefined;
  47136. }
  47137. }
  47138. };
  47139. })(),
  47140. hideAll: function () {
  47141. var el = this.el;
  47142. var hiddenEls = this.hiddenEls;
  47143. var self = this;
  47144. if (hiddenEls.length > 0) { return; }
  47145. el.sceneEl.object3D.traverse(function (object) {
  47146. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  47147. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  47148. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  47149. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  47150. object.el === self.semiSphereEl) {
  47151. return;
  47152. }
  47153. object.el.setAttribute('visible', false);
  47154. hiddenEls.push(object.el);
  47155. });
  47156. },
  47157. showAll: function () {
  47158. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  47159. this.hiddenEls = [];
  47160. },
  47161. /**
  47162. * Calculate whether the camera faces the front or back face of the portal.
  47163. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  47164. */
  47165. calculateCameraPortalOrientation: (function () {
  47166. var mat4 = new THREE.Matrix4();
  47167. var cameraPosition = new THREE.Vector3();
  47168. var portalNormal = new THREE.Vector3(0, 0, 1);
  47169. var portalPosition = new THREE.Vector3(0, 0, 0);
  47170. return function () {
  47171. var el = this.el;
  47172. var camera = el.sceneEl.camera;
  47173. // Reset tmp variables.
  47174. cameraPosition.set(0, 0, 0);
  47175. portalNormal.set(0, 0, 1);
  47176. portalPosition.set(0, 0, 0);
  47177. // Apply portal orientation to the normal.
  47178. el.object3D.matrixWorld.extractRotation(mat4);
  47179. portalNormal.applyMatrix4(mat4);
  47180. // Calculate portal world position.
  47181. el.object3D.updateMatrixWorld();
  47182. el.object3D.localToWorld(portalPosition);
  47183. // Calculate camera world position.
  47184. camera.parent.parent.updateMatrixWorld();
  47185. camera.parent.updateMatrixWorld();
  47186. camera.updateMatrixWorld();
  47187. camera.localToWorld(cameraPosition);
  47188. // Calculate vector from portal to camera.
  47189. // (portal) -------> (camera)
  47190. cameraPosition.sub(portalPosition).normalize();
  47191. portalNormal.normalize();
  47192. // Side where camera approaches portal is given by sign of dot product of portal normal
  47193. // and portal to camera vectors.
  47194. return Math.sign(portalNormal.dot(cameraPosition));
  47195. };
  47196. })(),
  47197. remove: function () {
  47198. this.removeEventListener();
  47199. }
  47200. });
  47201. /* eslint-disable */
  47202. registerShader('portal', {
  47203. schema: {
  47204. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  47205. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  47206. pano: {type: 'map', is: 'uniform'},
  47207. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  47208. },
  47209. vertexShader: [
  47210. 'vec3 portalPosition;',
  47211. 'varying vec3 vWorldPosition;',
  47212. 'varying float vDistanceToCenter;',
  47213. 'varying float vDistance;',
  47214. 'void main() {',
  47215. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  47216. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  47217. 'vDistance = length(portalPosition - cameraPosition);',
  47218. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  47219. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  47220. '}'
  47221. ].join('\n'),
  47222. fragmentShader: [
  47223. '#define RECIPROCAL_PI2 0.15915494',
  47224. 'uniform sampler2D pano;',
  47225. 'uniform vec3 strokeColor;',
  47226. 'uniform vec3 backgroundColor;',
  47227. 'uniform float borderEnabled;',
  47228. 'varying float vDistanceToCenter;',
  47229. 'varying float vDistance;',
  47230. 'varying vec3 vWorldPosition;',
  47231. 'void main() {',
  47232. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  47233. 'vec2 sampleUV;',
  47234. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  47235. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  47236. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  47237. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  47238. 'gl_FragColor = vec4(strokeColor, 1.0);',
  47239. '} else {',
  47240. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  47241. '}',
  47242. '}'
  47243. ].join('\n')
  47244. });
  47245. /* eslint-enable */
  47246. },{"../core/component":129,"../core/shader":139,"../lib/three":177}],88:[function(_dereq_,module,exports){
  47247. /* global DeviceOrientationEvent */
  47248. var registerComponent = _dereq_('../core/component').registerComponent;
  47249. var THREE = _dereq_('../lib/three');
  47250. var utils = _dereq_('../utils/');
  47251. var bind = utils.bind;
  47252. // To avoid recalculation at every mouse movement tick
  47253. var PI_2 = Math.PI / 2;
  47254. /**
  47255. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  47256. */
  47257. module.exports.Component = registerComponent('look-controls', {
  47258. dependencies: ['position', 'rotation'],
  47259. schema: {
  47260. enabled: {default: true},
  47261. magicWindowTrackingEnabled: {default: true},
  47262. pointerLockEnabled: {default: false},
  47263. reverseMouseDrag: {default: false},
  47264. reverseTouchDrag: {default: false},
  47265. touchEnabled: {default: true}
  47266. },
  47267. init: function () {
  47268. this.deltaYaw = 0;
  47269. this.previousHMDPosition = new THREE.Vector3();
  47270. this.hmdQuaternion = new THREE.Quaternion();
  47271. this.magicWindowAbsoluteEuler = new THREE.Euler();
  47272. this.magicWindowDeltaEuler = new THREE.Euler();
  47273. this.position = new THREE.Vector3();
  47274. this.magicWindowObject = new THREE.Object3D();
  47275. this.rotation = {};
  47276. this.deltaRotation = {};
  47277. this.savedPose = null;
  47278. this.pointerLocked = false;
  47279. this.setupMouseControls();
  47280. this.bindMethods();
  47281. this.previousMouseEvent = {};
  47282. this.setupMagicWindowControls();
  47283. // To save / restore camera pose
  47284. this.savedPose = {
  47285. position: new THREE.Vector3(),
  47286. rotation: new THREE.Euler()
  47287. };
  47288. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  47289. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  47290. },
  47291. setupMagicWindowControls: function () {
  47292. var magicWindowControls;
  47293. var data = this.data;
  47294. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  47295. if (utils.device.isMobile()) {
  47296. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  47297. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  47298. magicWindowControls.enabled = false;
  47299. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  47300. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47301. } else {
  47302. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  47303. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47304. });
  47305. }
  47306. }
  47307. }
  47308. },
  47309. update: function (oldData) {
  47310. var data = this.data;
  47311. // Disable grab cursor classes if no longer enabled.
  47312. if (data.enabled !== oldData.enabled) {
  47313. this.updateGrabCursor(data.enabled);
  47314. }
  47315. // Reset magic window eulers if tracking is disabled.
  47316. if (oldData && !data.magicWindowTrackingEnabled && oldData.magicWindowTrackingEnabled) {
  47317. this.magicWindowAbsoluteEuler.set(0, 0, 0);
  47318. this.magicWindowDeltaEuler.set(0, 0, 0);
  47319. }
  47320. // Pass on magic window tracking setting to magicWindowControls.
  47321. if (this.magicWindowControls) {
  47322. this.magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47323. }
  47324. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  47325. this.removeEventListeners();
  47326. this.addEventListeners();
  47327. if (this.pointerLocked) { this.exitPointerLock(); }
  47328. }
  47329. },
  47330. tick: function (t) {
  47331. var data = this.data;
  47332. if (!data.enabled) { return; }
  47333. this.updateOrientation();
  47334. },
  47335. play: function () {
  47336. this.addEventListeners();
  47337. },
  47338. pause: function () {
  47339. this.removeEventListeners();
  47340. if (this.pointerLocked) { this.exitPointerLock(); }
  47341. },
  47342. remove: function () {
  47343. this.removeEventListeners();
  47344. if (this.pointerLocked) { this.exitPointerLock(); }
  47345. },
  47346. bindMethods: function () {
  47347. this.onMouseDown = bind(this.onMouseDown, this);
  47348. this.onMouseMove = bind(this.onMouseMove, this);
  47349. this.onMouseUp = bind(this.onMouseUp, this);
  47350. this.onTouchStart = bind(this.onTouchStart, this);
  47351. this.onTouchMove = bind(this.onTouchMove, this);
  47352. this.onTouchEnd = bind(this.onTouchEnd, this);
  47353. this.onEnterVR = bind(this.onEnterVR, this);
  47354. this.onExitVR = bind(this.onExitVR, this);
  47355. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  47356. this.onPointerLockError = bind(this.onPointerLockError, this);
  47357. },
  47358. /**
  47359. * Set up states and Object3Ds needed to store rotation data.
  47360. */
  47361. setupMouseControls: function () {
  47362. this.mouseDown = false;
  47363. this.pitchObject = new THREE.Object3D();
  47364. this.yawObject = new THREE.Object3D();
  47365. this.yawObject.position.y = 10;
  47366. this.yawObject.add(this.pitchObject);
  47367. },
  47368. /**
  47369. * Add mouse and touch event listeners to canvas.
  47370. */
  47371. addEventListeners: function () {
  47372. var sceneEl = this.el.sceneEl;
  47373. var canvasEl = sceneEl.canvas;
  47374. // Wait for canvas to load.
  47375. if (!canvasEl) {
  47376. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  47377. return;
  47378. }
  47379. // Mouse events.
  47380. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  47381. window.addEventListener('mousemove', this.onMouseMove, false);
  47382. window.addEventListener('mouseup', this.onMouseUp, false);
  47383. // Touch events.
  47384. canvasEl.addEventListener('touchstart', this.onTouchStart);
  47385. window.addEventListener('touchmove', this.onTouchMove);
  47386. window.addEventListener('touchend', this.onTouchEnd);
  47387. // sceneEl events.
  47388. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  47389. sceneEl.addEventListener('exit-vr', this.onExitVR);
  47390. // Pointer Lock events.
  47391. if (this.data.pointerLockEnabled) {
  47392. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  47393. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  47394. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  47395. }
  47396. },
  47397. /**
  47398. * Remove mouse and touch event listeners from canvas.
  47399. */
  47400. removeEventListeners: function () {
  47401. var sceneEl = this.el.sceneEl;
  47402. var canvasEl = sceneEl && sceneEl.canvas;
  47403. if (!canvasEl) { return; }
  47404. // Mouse events.
  47405. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  47406. window.removeEventListener('mousemove', this.onMouseMove);
  47407. window.removeEventListener('mouseup', this.onMouseUp);
  47408. // Touch events.
  47409. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  47410. window.removeEventListener('touchmove', this.onTouchMove);
  47411. window.removeEventListener('touchend', this.onTouchEnd);
  47412. // sceneEl events.
  47413. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  47414. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  47415. // Pointer Lock events.
  47416. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  47417. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  47418. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  47419. },
  47420. /**
  47421. * Update orientation for mobile, mouse drag, and headset.
  47422. * Mouse-drag only enabled if HMD is not active.
  47423. */
  47424. updateOrientation: (function () {
  47425. var poseMatrix = new THREE.Matrix4();
  47426. return function () {
  47427. var object3D = this.el.object3D;
  47428. var pitchObject = this.pitchObject;
  47429. var yawObject = this.yawObject;
  47430. var pose;
  47431. var sceneEl = this.el.sceneEl;
  47432. // In VR mode, THREE is in charge of updating the camera pose.
  47433. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) {
  47434. // With WebXR THREE applies headset pose to the object3D matrixWorld internally.
  47435. // Reflect values back on position, rotation, scale for getAttribute to return the expected values.
  47436. if (sceneEl.hasWebXR) {
  47437. pose = sceneEl.renderer.xr.getCameraPose();
  47438. if (pose) {
  47439. poseMatrix.elements = pose.transform.matrix;
  47440. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47441. }
  47442. }
  47443. return;
  47444. }
  47445. this.updateMagicWindowOrientation();
  47446. // On mobile, do camera rotation with touch events and sensors.
  47447. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  47448. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  47449. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  47450. };
  47451. })(),
  47452. updateMagicWindowOrientation: function () {
  47453. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  47454. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  47455. // Calculate magic window HMD quaternion.
  47456. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  47457. this.magicWindowControls.update();
  47458. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  47459. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  47460. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  47461. }
  47462. if (this.previousMagicWindowYaw) {
  47463. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  47464. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  47465. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  47466. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  47467. }
  47468. }
  47469. },
  47470. /**
  47471. * Translate mouse drag into rotation.
  47472. *
  47473. * Dragging up and down rotates the camera around the X-axis (yaw).
  47474. * Dragging left and right rotates the camera around the Y-axis (pitch).
  47475. */
  47476. onMouseMove: function (evt) {
  47477. var direction;
  47478. var movementX;
  47479. var movementY;
  47480. var pitchObject = this.pitchObject;
  47481. var previousMouseEvent = this.previousMouseEvent;
  47482. var yawObject = this.yawObject;
  47483. // Not dragging or not enabled.
  47484. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  47485. // Calculate delta.
  47486. if (this.pointerLocked) {
  47487. movementX = evt.movementX || evt.mozMovementX || 0;
  47488. movementY = evt.movementY || evt.mozMovementY || 0;
  47489. } else {
  47490. movementX = evt.screenX - previousMouseEvent.screenX;
  47491. movementY = evt.screenY - previousMouseEvent.screenY;
  47492. }
  47493. this.previousMouseEvent.screenX = evt.screenX;
  47494. this.previousMouseEvent.screenY = evt.screenY;
  47495. // Calculate rotation.
  47496. direction = this.data.reverseMouseDrag ? 1 : -1;
  47497. yawObject.rotation.y += movementX * 0.002 * direction;
  47498. pitchObject.rotation.x += movementY * 0.002 * direction;
  47499. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  47500. },
  47501. /**
  47502. * Register mouse down to detect mouse drag.
  47503. */
  47504. onMouseDown: function (evt) {
  47505. var sceneEl = this.el.sceneEl;
  47506. if (!this.data.enabled || (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected())) { return; }
  47507. // Handle only primary button.
  47508. if (evt.button !== 0) { return; }
  47509. var canvasEl = sceneEl && sceneEl.canvas;
  47510. this.mouseDown = true;
  47511. this.previousMouseEvent.screenX = evt.screenX;
  47512. this.previousMouseEvent.screenY = evt.screenY;
  47513. this.showGrabbingCursor();
  47514. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  47515. if (canvasEl.requestPointerLock) {
  47516. canvasEl.requestPointerLock();
  47517. } else if (canvasEl.mozRequestPointerLock) {
  47518. canvasEl.mozRequestPointerLock();
  47519. }
  47520. }
  47521. },
  47522. /**
  47523. * Shows grabbing cursor on scene
  47524. */
  47525. showGrabbingCursor: function () {
  47526. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  47527. },
  47528. /**
  47529. * Hides grabbing cursor on scene
  47530. */
  47531. hideGrabbingCursor: function () {
  47532. this.el.sceneEl.canvas.style.cursor = '';
  47533. },
  47534. /**
  47535. * Register mouse up to detect release of mouse drag.
  47536. */
  47537. onMouseUp: function () {
  47538. this.mouseDown = false;
  47539. this.hideGrabbingCursor();
  47540. },
  47541. /**
  47542. * Register touch down to detect touch drag.
  47543. */
  47544. onTouchStart: function (evt) {
  47545. if (evt.touches.length !== 1 ||
  47546. !this.data.touchEnabled ||
  47547. this.el.sceneEl.is('vr-mode')) { return; }
  47548. this.touchStart = {
  47549. x: evt.touches[0].pageX,
  47550. y: evt.touches[0].pageY
  47551. };
  47552. this.touchStarted = true;
  47553. },
  47554. /**
  47555. * Translate touch move to Y-axis rotation.
  47556. */
  47557. onTouchMove: function (evt) {
  47558. var direction;
  47559. var canvas = this.el.sceneEl.canvas;
  47560. var deltaY;
  47561. var yawObject = this.yawObject;
  47562. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  47563. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  47564. direction = this.data.reverseTouchDrag ? 1 : -1;
  47565. // Limit touch orientaion to to yaw (y axis).
  47566. yawObject.rotation.y -= deltaY * 0.5 * direction;
  47567. this.touchStart = {
  47568. x: evt.touches[0].pageX,
  47569. y: evt.touches[0].pageY
  47570. };
  47571. },
  47572. /**
  47573. * Register touch end to detect release of touch drag.
  47574. */
  47575. onTouchEnd: function () {
  47576. this.touchStarted = false;
  47577. },
  47578. /**
  47579. * Save pose.
  47580. */
  47581. onEnterVR: function () {
  47582. var sceneEl = this.el.sceneEl;
  47583. if (!sceneEl.checkHeadsetConnected()) { return; }
  47584. this.saveCameraPose();
  47585. this.el.object3D.position.set(0, 0, 0);
  47586. this.el.object3D.rotation.set(0, 0, 0);
  47587. if (sceneEl.hasWebXR) {
  47588. this.el.object3D.matrixAutoUpdate = false;
  47589. this.el.object3D.updateMatrix();
  47590. }
  47591. },
  47592. /**
  47593. * Restore the pose.
  47594. */
  47595. onExitVR: function () {
  47596. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  47597. this.restoreCameraPose();
  47598. this.previousHMDPosition.set(0, 0, 0);
  47599. this.el.object3D.matrixAutoUpdate = true;
  47600. },
  47601. /**
  47602. * Update Pointer Lock state.
  47603. */
  47604. onPointerLockChange: function () {
  47605. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  47606. },
  47607. /**
  47608. * Recover from Pointer Lock error.
  47609. */
  47610. onPointerLockError: function () {
  47611. this.pointerLocked = false;
  47612. },
  47613. // Exits pointer-locked mode.
  47614. exitPointerLock: function () {
  47615. document.exitPointerLock();
  47616. this.pointerLocked = false;
  47617. },
  47618. /**
  47619. * Toggle the feature of showing/hiding the grab cursor.
  47620. */
  47621. updateGrabCursor: function (enabled) {
  47622. var sceneEl = this.el.sceneEl;
  47623. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  47624. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  47625. if (!sceneEl.canvas) {
  47626. if (enabled) {
  47627. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  47628. } else {
  47629. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  47630. }
  47631. return;
  47632. }
  47633. if (enabled) {
  47634. enableGrabCursor();
  47635. return;
  47636. }
  47637. disableGrabCursor();
  47638. },
  47639. /**
  47640. * Save camera pose before entering VR to restore later if exiting.
  47641. */
  47642. saveCameraPose: function () {
  47643. var el = this.el;
  47644. this.savedPose.position.copy(el.object3D.position);
  47645. this.savedPose.rotation.copy(el.object3D.rotation);
  47646. this.hasSavedPose = true;
  47647. },
  47648. /**
  47649. * Reset camera pose to before entering VR.
  47650. */
  47651. restoreCameraPose: function () {
  47652. var el = this.el;
  47653. var savedPose = this.savedPose;
  47654. if (!this.hasSavedPose) { return; }
  47655. // Reset camera orientation.
  47656. el.object3D.position.copy(savedPose.position);
  47657. el.object3D.rotation.copy(savedPose.rotation);
  47658. this.hasSavedPose = false;
  47659. }
  47660. });
  47661. },{"../core/component":129,"../lib/three":177,"../utils/":203}],89:[function(_dereq_,module,exports){
  47662. var bind = _dereq_('../utils/bind');
  47663. var registerComponent = _dereq_('../core/component').registerComponent;
  47664. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47665. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47666. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47667. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47668. // See Profiles Registry:
  47669. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  47670. // TODO: Add a more robust system for deriving gamepad name.
  47671. var GAMEPAD_ID_PREFIX = 'magicleap';
  47672. var GAMEPAD_ID_SUFFIX = '-one';
  47673. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  47674. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  47675. /**
  47676. * Button IDs:
  47677. * 0 - trigger
  47678. * 1 - grip
  47679. * 2 - touchpad
  47680. * 3 - menu (never dispatched on this layer)
  47681. *
  47682. * Axis:
  47683. * 0 - touchpad x axis
  47684. * 1 - touchpad y axis
  47685. */
  47686. var INPUT_MAPPING_WEBXR = {
  47687. axes: {touchpad: [0, 1]},
  47688. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  47689. };
  47690. /**
  47691. * Magic Leap Controls
  47692. * Interface with Magic Leap control and map Gamepad events to controller
  47693. * buttons: trigger, grip, touchpad, and menu.
  47694. * Load a controller model.
  47695. */
  47696. module.exports.Component = registerComponent('magicleap-controls', {
  47697. schema: {
  47698. hand: {default: 'none'},
  47699. model: {default: true},
  47700. orientationOffset: {type: 'vec3'}
  47701. },
  47702. mapping: INPUT_MAPPING_WEBXR,
  47703. init: function () {
  47704. var self = this;
  47705. this.controllerPresent = false;
  47706. this.lastControllerCheck = 0;
  47707. this.onButtonChanged = bind(this.onButtonChanged, this);
  47708. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47709. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47710. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47711. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47712. this.previousButtonValues = {};
  47713. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47714. this.bindMethods();
  47715. },
  47716. update: function () {
  47717. var data = this.data;
  47718. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47719. },
  47720. play: function () {
  47721. this.checkIfControllerPresent();
  47722. this.addControllersUpdateListener();
  47723. },
  47724. pause: function () {
  47725. this.removeEventListeners();
  47726. this.removeControllersUpdateListener();
  47727. },
  47728. bindMethods: function () {
  47729. this.onModelLoaded = bind(this.onModelLoaded, this);
  47730. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47731. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47732. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47733. this.onAxisMoved = bind(this.onAxisMoved, this);
  47734. },
  47735. addEventListeners: function () {
  47736. var el = this.el;
  47737. el.addEventListener('buttonchanged', this.onButtonChanged);
  47738. el.addEventListener('buttondown', this.onButtonDown);
  47739. el.addEventListener('buttonup', this.onButtonUp);
  47740. el.addEventListener('touchstart', this.onButtonTouchStart);
  47741. el.addEventListener('touchend', this.onButtonTouchEnd);
  47742. el.addEventListener('axismove', this.onAxisMoved);
  47743. el.addEventListener('model-loaded', this.onModelLoaded);
  47744. this.controllerEventsActive = true;
  47745. },
  47746. removeEventListeners: function () {
  47747. var el = this.el;
  47748. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47749. el.removeEventListener('buttondown', this.onButtonDown);
  47750. el.removeEventListener('buttonup', this.onButtonUp);
  47751. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47752. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47753. el.removeEventListener('axismove', this.onAxisMoved);
  47754. el.removeEventListener('model-loaded', this.onModelLoaded);
  47755. this.controllerEventsActive = false;
  47756. },
  47757. checkIfControllerPresent: function () {
  47758. var data = this.data;
  47759. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  47760. {index: this.controllerIndex, hand: data.hand});
  47761. },
  47762. injectTrackedControls: function () {
  47763. var el = this.el;
  47764. var data = this.data;
  47765. el.setAttribute('tracked-controls', {
  47766. // TODO: verify expected behavior between reserved prefixes.
  47767. idPrefix: GAMEPAD_ID_COMPOSITE,
  47768. hand: data.hand,
  47769. controller: this.controllerIndex,
  47770. orientationOffset: data.orientationOffset
  47771. });
  47772. // Load model.
  47773. if (!this.data.model) { return; }
  47774. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  47775. },
  47776. addControllersUpdateListener: function () {
  47777. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47778. },
  47779. removeControllersUpdateListener: function () {
  47780. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47781. },
  47782. onControllersUpdate: function () {
  47783. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47784. this.checkIfControllerPresent();
  47785. },
  47786. /**
  47787. * Rotate the trigger button based on how hard the trigger is pressed.
  47788. */
  47789. onButtonChanged: function (evt) {
  47790. var button = this.mapping.buttons[evt.detail.id];
  47791. var analogValue;
  47792. if (!button) { return; }
  47793. if (button === 'trigger') {
  47794. analogValue = evt.detail.state.value;
  47795. console.log('analog value of trigger press: ' + analogValue);
  47796. }
  47797. // Pass along changed event with button state, using button mapping for convenience.
  47798. this.el.emit(button + 'changed', evt.detail.state);
  47799. },
  47800. onModelLoaded: function (evt) {
  47801. var controllerObject3D = evt.detail.model;
  47802. // our glb scale is too large.
  47803. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  47804. },
  47805. onAxisMoved: function (evt) {
  47806. emitIfAxesChanged(this, this.mapping.axes, evt);
  47807. },
  47808. updateModel: function (buttonName, evtName) {},
  47809. setButtonColor: function (buttonName, color) {}
  47810. });
  47811. },{"../core/component":129,"../utils/bind":197,"../utils/tracked-controls":211}],90:[function(_dereq_,module,exports){
  47812. /* global Promise */
  47813. var utils = _dereq_('../utils/');
  47814. var component = _dereq_('../core/component');
  47815. var THREE = _dereq_('../lib/three');
  47816. var shader = _dereq_('../core/shader');
  47817. var error = utils.debug('components:material:error');
  47818. var registerComponent = component.registerComponent;
  47819. var shaders = shader.shaders;
  47820. var shaderNames = shader.shaderNames;
  47821. /**
  47822. * Material component.
  47823. *
  47824. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  47825. * three.js's implementation of PBR. Another standard shading model is `flat` which
  47826. * uses MeshBasicMaterial.
  47827. */
  47828. module.exports.Component = registerComponent('material', {
  47829. schema: {
  47830. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  47831. depthTest: {default: true},
  47832. depthWrite: {default: true},
  47833. flatShading: {default: false},
  47834. npot: {default: false},
  47835. offset: {type: 'vec2', default: {x: 0, y: 0}},
  47836. opacity: {default: 1.0, min: 0.0, max: 1.0},
  47837. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  47838. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  47839. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  47840. transparent: {default: false},
  47841. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  47842. visible: {default: true},
  47843. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  47844. dithering: {default: true}
  47845. },
  47846. init: function () {
  47847. this.material = null;
  47848. },
  47849. /**
  47850. * Update or create material.
  47851. *
  47852. * @param {object|null} oldData
  47853. */
  47854. update: function (oldData) {
  47855. var data = this.data;
  47856. if (!this.shader || data.shader !== oldData.shader) {
  47857. this.updateShader(data.shader);
  47858. }
  47859. this.shader.update(this.data);
  47860. this.updateMaterial(oldData);
  47861. },
  47862. updateSchema: function (data) {
  47863. var currentShader;
  47864. var newShader;
  47865. var schema;
  47866. var shader;
  47867. newShader = data && data.shader;
  47868. currentShader = this.oldData && this.oldData.shader;
  47869. shader = newShader || currentShader;
  47870. schema = shaders[shader] && shaders[shader].schema;
  47871. if (!schema) { error('Unknown shader schema ' + shader); }
  47872. if (currentShader && newShader === currentShader) { return; }
  47873. this.extendSchema(schema);
  47874. this.updateBehavior();
  47875. },
  47876. updateBehavior: function () {
  47877. var key;
  47878. var sceneEl = this.el.sceneEl;
  47879. var schema = this.schema;
  47880. var self = this;
  47881. var tickProperties;
  47882. function tickTime (time, delta) {
  47883. var key;
  47884. for (key in tickProperties) {
  47885. tickProperties[key] = time;
  47886. }
  47887. self.shader.update(tickProperties);
  47888. }
  47889. this.tick = undefined;
  47890. tickProperties = {};
  47891. for (key in schema) {
  47892. if (schema[key].type === 'time') {
  47893. this.tick = tickTime;
  47894. tickProperties[key] = true;
  47895. }
  47896. }
  47897. if (!sceneEl) { return; }
  47898. if (this.tick) {
  47899. sceneEl.addBehavior(this);
  47900. } else {
  47901. sceneEl.removeBehavior(this);
  47902. }
  47903. },
  47904. updateShader: function (shaderName) {
  47905. var data = this.data;
  47906. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  47907. var shaderInstance;
  47908. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  47909. // Get material from A-Frame shader.
  47910. shaderInstance = this.shader = new Shader();
  47911. shaderInstance.el = this.el;
  47912. shaderInstance.init(data);
  47913. this.setMaterial(shaderInstance.material);
  47914. this.updateSchema(data);
  47915. },
  47916. /**
  47917. * Set and update base material properties.
  47918. * Set `needsUpdate` when needed.
  47919. */
  47920. updateMaterial: function (oldData) {
  47921. var data = this.data;
  47922. var material = this.material;
  47923. var oldDataHasKeys;
  47924. // Base material properties.
  47925. material.alphaTest = data.alphaTest;
  47926. material.depthTest = data.depthTest !== false;
  47927. material.depthWrite = data.depthWrite !== false;
  47928. material.opacity = data.opacity;
  47929. material.flatShading = data.flatShading;
  47930. material.side = parseSide(data.side);
  47931. material.transparent = data.transparent !== false || data.opacity < 1.0;
  47932. material.vertexColors = parseVertexColors(data.vertexColors);
  47933. material.visible = data.visible;
  47934. material.blending = parseBlending(data.blending);
  47935. material.dithering = data.dithering;
  47936. // Check if material needs update.
  47937. for (oldDataHasKeys in oldData) { break; }
  47938. if (oldDataHasKeys &&
  47939. (oldData.alphaTest !== data.alphaTest ||
  47940. oldData.side !== data.side ||
  47941. oldData.vertexColors !== data.vertexColors)) {
  47942. material.needsUpdate = true;
  47943. }
  47944. },
  47945. /**
  47946. * Remove material on remove (callback).
  47947. * Dispose of it from memory and unsubscribe from scene updates.
  47948. */
  47949. remove: function () {
  47950. var defaultMaterial = new THREE.MeshBasicMaterial();
  47951. var material = this.material;
  47952. var object3D = this.el.getObject3D('mesh');
  47953. if (object3D) { object3D.material = defaultMaterial; }
  47954. disposeMaterial(material, this.system);
  47955. },
  47956. /**
  47957. * (Re)create new material. Has side-effects of setting `this.material` and updating
  47958. * material registration in scene.
  47959. *
  47960. * @param {object} data - Material component data.
  47961. * @param {object} type - Material type to create.
  47962. * @returns {object} Material.
  47963. */
  47964. setMaterial: function (material) {
  47965. var el = this.el;
  47966. var mesh;
  47967. var system = this.system;
  47968. if (this.material) { disposeMaterial(this.material, system); }
  47969. this.material = material;
  47970. system.registerMaterial(material);
  47971. // Set on mesh. If mesh does not exist, wait for it.
  47972. mesh = el.getObject3D('mesh');
  47973. if (mesh) {
  47974. mesh.material = material;
  47975. } else {
  47976. el.addEventListener('object3dset', function waitForMesh (evt) {
  47977. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  47978. el.getObject3D('mesh').material = material;
  47979. el.removeEventListener('object3dset', waitForMesh);
  47980. });
  47981. }
  47982. }
  47983. });
  47984. /**
  47985. * Return a three.js constant determining which material face sides to render
  47986. * based on the side parameter (passed as a component property).
  47987. *
  47988. * @param {string} [side=front] - `front`, `back`, or `double`.
  47989. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  47990. */
  47991. function parseSide (side) {
  47992. switch (side) {
  47993. case 'back': {
  47994. return THREE.BackSide;
  47995. }
  47996. case 'double': {
  47997. return THREE.DoubleSide;
  47998. }
  47999. default: {
  48000. // Including case `front`.
  48001. return THREE.FrontSide;
  48002. }
  48003. }
  48004. }
  48005. /**
  48006. * Return a three.js constant determining vertex coloring.
  48007. */
  48008. function parseVertexColors (coloring) {
  48009. switch (coloring) {
  48010. case 'face': {
  48011. return THREE.FaceColors;
  48012. }
  48013. case 'vertex': {
  48014. return THREE.VertexColors;
  48015. }
  48016. default: {
  48017. return THREE.NoColors;
  48018. }
  48019. }
  48020. }
  48021. /**
  48022. * Return a three.js constant determining blending
  48023. *
  48024. * @param {string} [blending=normal]
  48025. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  48026. * @returns {number}
  48027. */
  48028. function parseBlending (blending) {
  48029. switch (blending) {
  48030. case 'none': {
  48031. return THREE.NoBlending;
  48032. }
  48033. case 'additive': {
  48034. return THREE.AdditiveBlending;
  48035. }
  48036. case 'subtractive': {
  48037. return THREE.SubtractiveBlending;
  48038. }
  48039. case 'multiply': {
  48040. return THREE.MultiplyBlending;
  48041. }
  48042. default: {
  48043. return THREE.NormalBlending;
  48044. }
  48045. }
  48046. }
  48047. /**
  48048. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  48049. */
  48050. function disposeMaterial (material, system) {
  48051. material.dispose();
  48052. system.unregisterMaterial(material);
  48053. }
  48054. },{"../core/component":129,"../core/shader":139,"../lib/three":177,"../utils/":203}],91:[function(_dereq_,module,exports){
  48055. var debug = _dereq_('../utils/debug');
  48056. var registerComponent = _dereq_('../core/component').registerComponent;
  48057. var THREE = _dereq_('../lib/three');
  48058. var warn = debug('components:obj-model:warn');
  48059. module.exports.Component = registerComponent('obj-model', {
  48060. schema: {
  48061. mtl: {type: 'model'},
  48062. obj: {type: 'model'}
  48063. },
  48064. init: function () {
  48065. var self = this;
  48066. this.model = null;
  48067. this.objLoader = new THREE.OBJLoader();
  48068. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  48069. // Allow cross-origin images to be loaded.
  48070. this.mtlLoader.crossOrigin = '';
  48071. this.el.addEventListener('componentinitialized', function (evt) {
  48072. if (!self.model) { return; }
  48073. if (evt.detail.name !== 'material') { return; }
  48074. self.applyMaterial();
  48075. });
  48076. },
  48077. update: function () {
  48078. var data = this.data;
  48079. if (!data.obj) { return; }
  48080. this.resetMesh();
  48081. this.loadObj(data.obj, data.mtl);
  48082. },
  48083. remove: function () {
  48084. if (!this.model) { return; }
  48085. this.resetMesh();
  48086. },
  48087. resetMesh: function () {
  48088. this.el.removeObject3D('mesh');
  48089. },
  48090. loadObj: function (objUrl, mtlUrl) {
  48091. var self = this;
  48092. var el = this.el;
  48093. var mtlLoader = this.mtlLoader;
  48094. var objLoader = this.objLoader;
  48095. var rendererSystem = this.el.sceneEl.systems.renderer;
  48096. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  48097. if (mtlUrl) {
  48098. // .OBJ with an .MTL.
  48099. if (el.hasAttribute('material')) {
  48100. warn('Material component properties are ignored when a .MTL is provided');
  48101. }
  48102. mtlLoader.setResourcePath(BASE_PATH);
  48103. mtlLoader.load(mtlUrl, function (materials) {
  48104. materials.preload();
  48105. objLoader.setMaterials(materials);
  48106. objLoader.load(objUrl, function (objModel) {
  48107. self.model = objModel;
  48108. self.model.traverse(function (object) {
  48109. if (object.isMesh) {
  48110. var material = object.material;
  48111. if (material.color) rendererSystem.applyColorCorrection(material.color);
  48112. if (material.map) rendererSystem.applyColorCorrection(material.map);
  48113. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  48114. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  48115. }
  48116. });
  48117. el.setObject3D('mesh', objModel);
  48118. el.emit('model-loaded', {format: 'obj', model: objModel});
  48119. });
  48120. });
  48121. return;
  48122. }
  48123. // .OBJ only.
  48124. objLoader.load(objUrl, function loadObjOnly (objModel) {
  48125. self.model = objModel;
  48126. self.applyMaterial();
  48127. el.setObject3D('mesh', objModel);
  48128. el.emit('model-loaded', {format: 'obj', model: objModel});
  48129. });
  48130. },
  48131. /**
  48132. * Apply material from material component recursively.
  48133. */
  48134. applyMaterial: function () {
  48135. var material = this.el.components.material;
  48136. if (!material) { return; }
  48137. this.model.traverse(function (child) {
  48138. if (child instanceof THREE.Mesh) {
  48139. child.material = material.material;
  48140. }
  48141. });
  48142. }
  48143. });
  48144. },{"../core/component":129,"../lib/three":177,"../utils/debug":199}],92:[function(_dereq_,module,exports){
  48145. var registerComponent = _dereq_('../core/component').registerComponent;
  48146. var bind = _dereq_('../utils/bind');
  48147. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48148. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48149. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48150. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48151. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  48152. var GAMEPAD_ID_WEBXR = 'oculus-go';
  48153. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  48154. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  48155. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  48156. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  48157. /**
  48158. * Button indices:
  48159. * 0 - trackpad
  48160. * 1 - trigger
  48161. *
  48162. * Axis:
  48163. * 0 - trackpad x
  48164. * 1 - trackpad y
  48165. */
  48166. var INPUT_MAPPING_WEBVR = {
  48167. axes: {trackpad: [0, 1]},
  48168. buttons: ['trackpad', 'trigger']
  48169. };
  48170. /**
  48171. * Button indices:
  48172. * 0 - trigger
  48173. * 1 - none
  48174. * 2 - touchpad
  48175. *
  48176. * Axis:
  48177. * 0 - touchpad x
  48178. * 1 - touchpad y
  48179. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  48180. */
  48181. var INPUT_MAPPING_WEBXR = {
  48182. axes: {touchpad: [0, 1]},
  48183. buttons: ['trigger', 'none', 'touchpad']
  48184. };
  48185. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  48186. /**
  48187. * Oculus Go controls.
  48188. * Interface with Oculus Go controller and map Gamepad events to
  48189. * controller buttons: trackpad, trigger
  48190. * Load a controller model and highlight the pressed buttons.
  48191. */
  48192. module.exports.Component = registerComponent('oculus-go-controls', {
  48193. schema: {
  48194. hand: {default: ''}, // This informs the degenerate arm model.
  48195. buttonColor: {type: 'color', default: '#FFFFFF'},
  48196. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  48197. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  48198. model: {default: true},
  48199. orientationOffset: {type: 'vec3'},
  48200. armModel: {default: true}
  48201. },
  48202. mapping: INPUT_MAPPING,
  48203. bindMethods: function () {
  48204. this.onModelLoaded = bind(this.onModelLoaded, this);
  48205. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48206. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48207. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48208. this.onAxisMoved = bind(this.onAxisMoved, this);
  48209. },
  48210. init: function () {
  48211. var self = this;
  48212. this.onButtonChanged = bind(this.onButtonChanged, this);
  48213. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48214. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48215. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48216. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48217. this.controllerPresent = false;
  48218. this.lastControllerCheck = 0;
  48219. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48220. this.bindMethods();
  48221. },
  48222. addEventListeners: function () {
  48223. var el = this.el;
  48224. el.addEventListener('buttonchanged', this.onButtonChanged);
  48225. el.addEventListener('buttondown', this.onButtonDown);
  48226. el.addEventListener('buttonup', this.onButtonUp);
  48227. el.addEventListener('touchstart', this.onButtonTouchStart);
  48228. el.addEventListener('touchend', this.onButtonTouchEnd);
  48229. el.addEventListener('model-loaded', this.onModelLoaded);
  48230. el.addEventListener('axismove', this.onAxisMoved);
  48231. this.controllerEventsActive = true;
  48232. },
  48233. removeEventListeners: function () {
  48234. var el = this.el;
  48235. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48236. el.removeEventListener('buttondown', this.onButtonDown);
  48237. el.removeEventListener('buttonup', this.onButtonUp);
  48238. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48239. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48240. el.removeEventListener('model-loaded', this.onModelLoaded);
  48241. el.removeEventListener('axismove', this.onAxisMoved);
  48242. this.controllerEventsActive = false;
  48243. },
  48244. checkIfControllerPresent: function () {
  48245. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  48246. this.data.hand ? {hand: this.data.hand} : {});
  48247. },
  48248. play: function () {
  48249. this.checkIfControllerPresent();
  48250. this.addControllersUpdateListener();
  48251. },
  48252. pause: function () {
  48253. this.removeEventListeners();
  48254. this.removeControllersUpdateListener();
  48255. },
  48256. injectTrackedControls: function () {
  48257. var el = this.el;
  48258. var data = this.data;
  48259. el.setAttribute('tracked-controls', {
  48260. armModel: data.armModel,
  48261. hand: data.hand,
  48262. idPrefix: GAMEPAD_ID_PREFIX,
  48263. orientationOffset: data.orientationOffset
  48264. });
  48265. if (!this.data.model) { return; }
  48266. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  48267. },
  48268. addControllersUpdateListener: function () {
  48269. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48270. },
  48271. removeControllersUpdateListener: function () {
  48272. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48273. },
  48274. onControllersUpdate: function () {
  48275. this.checkIfControllerPresent();
  48276. },
  48277. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  48278. onModelLoaded: function (evt) {
  48279. var controllerObject3D = evt.detail.model;
  48280. var buttonMeshes;
  48281. if (!this.data.model) { return; }
  48282. buttonMeshes = this.buttonMeshes = {};
  48283. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  48284. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  48285. buttonMeshes.touchpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  48286. },
  48287. onButtonChanged: function (evt) {
  48288. var button = this.mapping.buttons[evt.detail.id];
  48289. if (!button) return;
  48290. // Pass along changed event with button state, using button mapping for convenience.
  48291. this.el.emit(button + 'changed', evt.detail.state);
  48292. },
  48293. onAxisMoved: function (evt) {
  48294. emitIfAxesChanged(this, this.mapping.axes, evt);
  48295. },
  48296. updateModel: function (buttonName, evtName) {
  48297. if (!this.data.model) { return; }
  48298. this.updateButtonModel(buttonName, evtName);
  48299. },
  48300. updateButtonModel: function (buttonName, state) {
  48301. var buttonMeshes = this.buttonMeshes;
  48302. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  48303. var color;
  48304. var button;
  48305. switch (state) {
  48306. case 'down':
  48307. color = this.data.buttonHighlightColor;
  48308. break;
  48309. case 'touchstart':
  48310. color = this.data.buttonTouchedColor;
  48311. break;
  48312. default:
  48313. color = this.data.buttonColor;
  48314. }
  48315. button = buttonMeshes[buttonName];
  48316. button.material.color.set(color);
  48317. this.rendererSystem.applyColorCorrection(button.material.color);
  48318. }
  48319. });
  48320. },{"../core/component":129,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],93:[function(_dereq_,module,exports){
  48321. var bind = _dereq_('../utils/bind');
  48322. var registerComponent = _dereq_('../core/component').registerComponent;
  48323. var THREE = _dereq_('../lib/three');
  48324. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48325. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48326. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48327. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48328. var isOculusBrowser = _dereq_('../utils/').device.isOculusBrowser();
  48329. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  48330. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  48331. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  48332. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  48333. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  48334. // First generation model URL.
  48335. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  48336. // For now the generation 2 model is the same as the original until a new one is prepared for upload.
  48337. var TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL = TOUCH_CONTROLLER_MODEL_BASE_URL;
  48338. var OCULUS_TOUCH_WEBVR = {
  48339. left: {
  48340. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  48341. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  48342. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  48343. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48344. },
  48345. right: {
  48346. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  48347. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  48348. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  48349. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48350. }
  48351. };
  48352. var OCULUS_TOUCH_WEBXR = {
  48353. left: {
  48354. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  48355. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  48356. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  48357. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  48358. },
  48359. right: {
  48360. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  48361. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  48362. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  48363. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  48364. }
  48365. };
  48366. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  48367. var CONTROLLER_DEFAULT = 'oculus-touch';
  48368. var CONTROLLER_PROPERTIES = {
  48369. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  48370. 'oculus-touch-v2': {
  48371. left: {
  48372. modelUrl: TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  48373. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  48374. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  48375. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48376. },
  48377. right: {
  48378. modelUrl: TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  48379. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  48380. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  48381. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48382. }
  48383. }
  48384. };
  48385. /**
  48386. * Button indices:
  48387. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  48388. * 1 - trigger (with analog value, which goes up to 1)
  48389. * 2 - grip (with analog value, which goes up to 1)
  48390. * 3 - X (left) or A (right)
  48391. * 4 - Y (left) or B (right)
  48392. * 5 - surface (touch only)
  48393. */
  48394. var INPUT_MAPPING_WEBVR = {
  48395. left: {
  48396. axes: {thumbstick: [0, 1]},
  48397. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  48398. },
  48399. right: {
  48400. axes: {thumbstick: [0, 1]},
  48401. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  48402. }
  48403. };
  48404. /**
  48405. * Button indices:
  48406. * 0 - trigger
  48407. * 1 - grip
  48408. * 2 - none
  48409. * 3 - thumbstick
  48410. * 4 - X or A button
  48411. * 5 - Y or B button
  48412. * 6 - surface
  48413. *
  48414. * Axis:
  48415. * 0 - none
  48416. * 1 - none
  48417. * 2 - thumbstick
  48418. * 3 - thumbstick
  48419. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  48420. */
  48421. var INPUT_MAPPING_WEBXR = {
  48422. left: {
  48423. axes: {thumbstick: [2, 3]},
  48424. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  48425. },
  48426. right: {
  48427. axes: {thumbstick: [2, 3]},
  48428. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  48429. }
  48430. };
  48431. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  48432. /**
  48433. * Oculus Touch controls.
  48434. * Interface with Oculus Touch controllers and map Gamepad events to
  48435. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  48436. * Load a controller model and highlight the pressed buttons.
  48437. */
  48438. module.exports.Component = registerComponent('oculus-touch-controls', {
  48439. schema: {
  48440. hand: {default: 'left'},
  48441. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  48442. buttonTouchColor: {type: 'color', default: '#8AB'},
  48443. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  48444. model: {default: true},
  48445. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2']},
  48446. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  48447. },
  48448. mapping: INPUT_MAPPING,
  48449. bindMethods: function () {
  48450. this.onModelLoaded = bind(this.onModelLoaded, this);
  48451. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48452. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48453. this.onAxisMoved = bind(this.onAxisMoved, this);
  48454. },
  48455. init: function () {
  48456. var self = this;
  48457. this.onButtonChanged = bind(this.onButtonChanged, this);
  48458. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  48459. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  48460. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  48461. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  48462. this.controllerPresent = false;
  48463. this.lastControllerCheck = 0;
  48464. this.previousButtonValues = {};
  48465. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48466. this.bindMethods();
  48467. },
  48468. addEventListeners: function () {
  48469. var el = this.el;
  48470. el.addEventListener('buttonchanged', this.onButtonChanged);
  48471. el.addEventListener('buttondown', this.onButtonDown);
  48472. el.addEventListener('buttonup', this.onButtonUp);
  48473. el.addEventListener('touchstart', this.onButtonTouchStart);
  48474. el.addEventListener('touchend', this.onButtonTouchEnd);
  48475. el.addEventListener('axismove', this.onAxisMoved);
  48476. el.addEventListener('model-loaded', this.onModelLoaded);
  48477. this.controllerEventsActive = true;
  48478. },
  48479. removeEventListeners: function () {
  48480. var el = this.el;
  48481. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48482. el.removeEventListener('buttondown', this.onButtonDown);
  48483. el.removeEventListener('buttonup', this.onButtonUp);
  48484. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48485. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48486. el.removeEventListener('axismove', this.onAxisMoved);
  48487. el.removeEventListener('model-loaded', this.onModelLoaded);
  48488. this.controllerEventsActive = false;
  48489. },
  48490. checkIfControllerPresent: function () {
  48491. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  48492. hand: this.data.hand
  48493. });
  48494. },
  48495. play: function () {
  48496. this.checkIfControllerPresent();
  48497. this.addControllersUpdateListener();
  48498. },
  48499. pause: function () {
  48500. this.removeEventListeners();
  48501. this.removeControllersUpdateListener();
  48502. },
  48503. loadModel: function () {
  48504. var data = this.data;
  48505. if (!data.model) { return; }
  48506. // Set the controller display model based on the data passed in.
  48507. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  48508. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  48509. // This only works for WebVR currently.
  48510. if (data.controllerType === 'auto') {
  48511. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  48512. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  48513. var displayName = trackedControlsSystem.vrDisplay.displayName;
  48514. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  48515. if (/^Oculus Quest$/.test(displayName)) {
  48516. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  48517. }
  48518. }
  48519. if (isOculusBrowser) { this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2']; }
  48520. }
  48521. var modelUrl = this.displayModel[data.hand].modelUrl;
  48522. this.el.setAttribute('gltf-model', modelUrl);
  48523. },
  48524. injectTrackedControls: function () {
  48525. var data = this.data;
  48526. var webXRId = GAMEPAD_ID_WEBXR;
  48527. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  48528. var id = isWebXRAvailable ? webXRId : webVRId;
  48529. this.el.setAttribute('tracked-controls', {
  48530. id: id,
  48531. hand: data.hand,
  48532. orientationOffset: data.orientationOffset,
  48533. handTrackingEnabled: false
  48534. });
  48535. this.loadModel();
  48536. },
  48537. addControllersUpdateListener: function () {
  48538. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48539. },
  48540. removeControllersUpdateListener: function () {
  48541. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48542. },
  48543. onControllersUpdate: function () {
  48544. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  48545. this.checkIfControllerPresent();
  48546. },
  48547. onButtonChanged: function (evt) {
  48548. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  48549. var buttonMeshes = this.buttonMeshes;
  48550. var analogValue;
  48551. if (!button) { return; }
  48552. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  48553. // Update trigger and/or grip meshes, if any.
  48554. if (buttonMeshes) {
  48555. if (button === 'trigger' && buttonMeshes.trigger) {
  48556. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  48557. }
  48558. if (button === 'grip' && buttonMeshes.grip) {
  48559. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  48560. }
  48561. }
  48562. // Pass along changed event with button state, using the buttom mapping for convenience.
  48563. this.el.emit(button + 'changed', evt.detail.state);
  48564. },
  48565. onModelLoaded: function (evt) {
  48566. var controllerObject3D = evt.detail.model;
  48567. var buttonMeshes;
  48568. if (!this.data.model) { return; }
  48569. buttonMeshes = this.buttonMeshes = {};
  48570. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  48571. this.originalXPositionGrip = buttonMeshes.grip.position.x;
  48572. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  48573. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  48574. this.originalXRotationTrigger = buttonMeshes.trigger.rotation.x;
  48575. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  48576. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  48577. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  48578. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  48579. // Offset pivot point
  48580. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  48581. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  48582. this.el.emit('controllermodelready', {
  48583. name: 'oculus-touch-controls',
  48584. model: this.data.model,
  48585. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  48586. });
  48587. },
  48588. onAxisMoved: function (evt) {
  48589. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  48590. },
  48591. updateModel: function (buttonName, evtName) {
  48592. if (!this.data.model) { return; }
  48593. this.updateButtonModel(buttonName, evtName);
  48594. },
  48595. updateButtonModel: function (buttonName, state) {
  48596. var button;
  48597. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  48598. var buttonMeshes = this.buttonMeshes;
  48599. if (!this.data.model) { return; }
  48600. if (buttonMeshes && buttonMeshes[buttonName]) {
  48601. button = buttonMeshes[buttonName];
  48602. button.material.color.set(color);
  48603. this.rendererSystem.applyColorCorrection(button.material.color);
  48604. }
  48605. }
  48606. });
  48607. },{"../core/component":129,"../lib/three":177,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],94:[function(_dereq_,module,exports){
  48608. var registerComponent = _dereq_('../core/component').registerComponent;
  48609. module.exports.Component = registerComponent('position', {
  48610. schema: {type: 'vec3'},
  48611. update: function () {
  48612. var object3D = this.el.object3D;
  48613. var data = this.data;
  48614. object3D.position.set(data.x, data.y, data.z);
  48615. },
  48616. remove: function () {
  48617. // Pretty much for mixins.
  48618. this.el.object3D.position.set(0, 0, 0);
  48619. }
  48620. });
  48621. },{"../core/component":129}],95:[function(_dereq_,module,exports){
  48622. /* global MutationObserver */
  48623. var registerComponent = _dereq_('../core/component').registerComponent;
  48624. var THREE = _dereq_('../lib/three');
  48625. var utils = _dereq_('../utils/');
  48626. var warn = utils.debug('components:raycaster:warn');
  48627. // Defines selectors that should be 'safe' for the MutationObserver used to
  48628. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  48629. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  48630. // reliably detected and are therefore disallowed.
  48631. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  48632. // Configuration for the MutationObserver used to refresh the whitelist.
  48633. // Listens for addition/removal of elements and attributes within the scene.
  48634. var OBSERVER_CONFIG = {
  48635. childList: true,
  48636. attributes: true,
  48637. subtree: true
  48638. };
  48639. var EVENTS = {
  48640. INTERSECT: 'raycaster-intersected',
  48641. INTERSECTION: 'raycaster-intersection',
  48642. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  48643. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  48644. };
  48645. /**
  48646. * Raycaster component.
  48647. *
  48648. * Pass options to three.js Raycaster including which objects to test.
  48649. * Poll for intersections.
  48650. * Emit event on origin entity and on target entity on intersect.
  48651. *
  48652. * @member {array} intersectedEls - List of currently intersected entities.
  48653. * @member {array} objects - Cached list of meshes to intersect.
  48654. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  48655. * @member {object} raycaster - three.js Raycaster.
  48656. */
  48657. module.exports.Component = registerComponent('raycaster', {
  48658. schema: {
  48659. autoRefresh: {default: true},
  48660. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  48661. enabled: {default: true},
  48662. far: {default: 1000},
  48663. interval: {default: 0},
  48664. near: {default: 0},
  48665. objects: {default: ''},
  48666. origin: {type: 'vec3'},
  48667. showLine: {default: false},
  48668. useWorldCoordinates: {default: false}
  48669. },
  48670. multiple: true,
  48671. init: function () {
  48672. this.clearedIntersectedEls = [];
  48673. this.unitLineEndVec3 = new THREE.Vector3();
  48674. this.intersectedEls = [];
  48675. this.intersections = [];
  48676. this.newIntersectedEls = [];
  48677. this.newIntersections = [];
  48678. this.objects = [];
  48679. this.prevCheckTime = undefined;
  48680. this.prevIntersectedEls = [];
  48681. this.rawIntersections = [];
  48682. this.raycaster = new THREE.Raycaster();
  48683. this.updateOriginDirection();
  48684. this.setDirty = this.setDirty.bind(this);
  48685. this.updateLine = this.updateLine.bind(this);
  48686. this.observer = new MutationObserver(this.setDirty);
  48687. this.dirty = true;
  48688. this.lineEndVec3 = new THREE.Vector3();
  48689. this.otherLineEndVec3 = new THREE.Vector3();
  48690. this.lineData = {end: this.lineEndVec3};
  48691. this.getIntersection = this.getIntersection.bind(this);
  48692. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  48693. this.intersectedClearedDetail = {el: this.el};
  48694. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  48695. this.intersectionDetail = {};
  48696. },
  48697. /**
  48698. * Create or update raycaster object.
  48699. */
  48700. update: function (oldData) {
  48701. var data = this.data;
  48702. var el = this.el;
  48703. var raycaster = this.raycaster;
  48704. // Set raycaster properties.
  48705. raycaster.far = data.far;
  48706. raycaster.near = data.near;
  48707. // Draw line.
  48708. if (data.showLine &&
  48709. (data.far !== oldData.far || data.origin !== oldData.origin ||
  48710. data.direction !== oldData.direction || !oldData.showLine)) {
  48711. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  48712. // adjust line length.
  48713. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  48714. this.drawLine();
  48715. }
  48716. if (!data.showLine && oldData.showLine) {
  48717. el.removeAttribute('line');
  48718. }
  48719. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  48720. warn('[raycaster] Selector "' + data.objects +
  48721. '" may not update automatically with DOM changes.');
  48722. }
  48723. if (!data.objects) {
  48724. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  48725. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  48726. 'e.g., raycaster="objects: [data-raycastable]".');
  48727. }
  48728. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  48729. data.autoRefresh
  48730. ? this.addEventListeners()
  48731. : this.removeEventListeners();
  48732. }
  48733. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  48734. this.setDirty();
  48735. },
  48736. play: function () {
  48737. this.addEventListeners();
  48738. },
  48739. pause: function () {
  48740. this.removeEventListeners();
  48741. },
  48742. remove: function () {
  48743. if (this.data.showLine) {
  48744. this.el.removeAttribute('line');
  48745. }
  48746. this.clearAllIntersections();
  48747. },
  48748. addEventListeners: function () {
  48749. if (!this.data.autoRefresh) { return; }
  48750. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  48751. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  48752. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  48753. },
  48754. removeEventListeners: function () {
  48755. this.observer.disconnect();
  48756. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  48757. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  48758. },
  48759. /**
  48760. * Mark the object list as dirty, to be refreshed before next raycast.
  48761. */
  48762. setDirty: function () {
  48763. this.dirty = true;
  48764. },
  48765. /**
  48766. * Update list of objects to test for intersection.
  48767. */
  48768. refreshObjects: function () {
  48769. var data = this.data;
  48770. var els;
  48771. // If objects not defined, intersect with everything.
  48772. els = data.objects
  48773. ? this.el.sceneEl.querySelectorAll(data.objects)
  48774. : this.el.sceneEl.querySelectorAll('*');
  48775. this.objects = this.flattenObject3DMaps(els);
  48776. this.dirty = false;
  48777. },
  48778. /**
  48779. * Check for intersections and cleared intersections on an interval.
  48780. */
  48781. tick: function (time) {
  48782. var data = this.data;
  48783. var prevCheckTime = this.prevCheckTime;
  48784. if (!data.enabled) { return; }
  48785. // Only check for intersection if interval time has passed.
  48786. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  48787. // Update check time.
  48788. this.prevCheckTime = time;
  48789. this.checkIntersections();
  48790. },
  48791. /**
  48792. * Raycast for intersections and emit events for current and cleared inersections.
  48793. */
  48794. checkIntersections: function () {
  48795. var clearedIntersectedEls = this.clearedIntersectedEls;
  48796. var el = this.el;
  48797. var data = this.data;
  48798. var i;
  48799. var intersectedEls = this.intersectedEls;
  48800. var intersection;
  48801. var intersections = this.intersections;
  48802. var newIntersectedEls = this.newIntersectedEls;
  48803. var newIntersections = this.newIntersections;
  48804. var prevIntersectedEls = this.prevIntersectedEls;
  48805. var rawIntersections = this.rawIntersections;
  48806. // Refresh the object whitelist if needed.
  48807. if (this.dirty) { this.refreshObjects(); }
  48808. // Store old previously intersected entities.
  48809. copyArray(this.prevIntersectedEls, this.intersectedEls);
  48810. // Raycast.
  48811. this.updateOriginDirection();
  48812. rawIntersections.length = 0;
  48813. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  48814. // Only keep intersections against objects that have a reference to an entity.
  48815. intersections.length = 0;
  48816. intersectedEls.length = 0;
  48817. for (i = 0; i < rawIntersections.length; i++) {
  48818. intersection = rawIntersections[i];
  48819. // Don't intersect with own line.
  48820. if (data.showLine && intersection.object === el.getObject3D('line')) {
  48821. continue;
  48822. }
  48823. if (intersection.object.el) {
  48824. intersections.push(intersection);
  48825. intersectedEls.push(intersection.object.el);
  48826. }
  48827. }
  48828. // Get newly intersected entities.
  48829. newIntersections.length = 0;
  48830. newIntersectedEls.length = 0;
  48831. for (i = 0; i < intersections.length; i++) {
  48832. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  48833. newIntersections.push(intersections[i]);
  48834. newIntersectedEls.push(intersections[i].object.el);
  48835. }
  48836. }
  48837. // Emit intersection cleared on both entities per formerly intersected entity.
  48838. clearedIntersectedEls.length = 0;
  48839. for (i = 0; i < prevIntersectedEls.length; i++) {
  48840. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  48841. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  48842. this.intersectedClearedDetail);
  48843. clearedIntersectedEls.push(prevIntersectedEls[i]);
  48844. }
  48845. if (clearedIntersectedEls.length) {
  48846. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  48847. }
  48848. // Emit intersected on intersected entity per intersected entity.
  48849. for (i = 0; i < newIntersectedEls.length; i++) {
  48850. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  48851. }
  48852. // Emit all intersections at once on raycasting entity.
  48853. if (newIntersections.length) {
  48854. this.intersectionDetail.els = newIntersectedEls;
  48855. this.intersectionDetail.intersections = newIntersections;
  48856. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  48857. }
  48858. // Update line length.
  48859. if (data.showLine) { setTimeout(this.updateLine); }
  48860. },
  48861. updateLine: function () {
  48862. var el = this.el;
  48863. var intersections = this.intersections;
  48864. var lineLength;
  48865. if (intersections.length) {
  48866. if (intersections[0].object.el === el && intersections[1]) {
  48867. lineLength = intersections[1].distance;
  48868. } else {
  48869. lineLength = intersections[0].distance;
  48870. }
  48871. }
  48872. this.drawLine(lineLength);
  48873. },
  48874. /**
  48875. * Return the most recent intersection details for a given entity, if any.
  48876. * @param {AEntity} el
  48877. * @return {Object}
  48878. */
  48879. getIntersection: function (el) {
  48880. var i;
  48881. var intersection;
  48882. for (i = 0; i < this.intersections.length; i++) {
  48883. intersection = this.intersections[i];
  48884. if (intersection.object.el === el) { return intersection; }
  48885. }
  48886. return null;
  48887. },
  48888. /**
  48889. * Update origin and direction of raycaster using entity transforms and supplied origin or
  48890. * direction offsets.
  48891. */
  48892. updateOriginDirection: (function () {
  48893. var direction = new THREE.Vector3();
  48894. var originVec3 = new THREE.Vector3();
  48895. // Closure to make quaternion/vector3 objects private.
  48896. return function updateOriginDirection () {
  48897. var el = this.el;
  48898. var data = this.data;
  48899. if (data.useWorldCoordinates) {
  48900. this.raycaster.set(data.origin, data.direction);
  48901. return;
  48902. }
  48903. el.object3D.updateMatrixWorld();
  48904. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  48905. // If non-zero origin, translate the origin into world space.
  48906. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  48907. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  48908. }
  48909. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  48910. // provide. Apply the offset to the direction, then rotation from the object,
  48911. // and normalize.
  48912. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  48913. // Apply offset and direction, in world coordinates.
  48914. this.raycaster.set(originVec3, direction);
  48915. };
  48916. })(),
  48917. /**
  48918. * Create or update line to give raycaster visual representation.
  48919. * Customize the line through through line component.
  48920. * We draw the line in the raycaster component to customize the line to the
  48921. * raycaster's origin, direction, and far.
  48922. *
  48923. * Unlike the raycaster, we create the line as a child of the object. The line will
  48924. * be affected by the transforms of the objects, so we don't have to calculate transforms
  48925. * like we do with the raycaster.
  48926. *
  48927. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  48928. * point. If not provided, length will default to the max length, `raycaster.far`.
  48929. */
  48930. drawLine: function (length) {
  48931. var data = this.data;
  48932. var el = this.el;
  48933. var endVec3;
  48934. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  48935. endVec3 = this.lineData.end === this.lineEndVec3
  48936. ? this.otherLineEndVec3
  48937. : this.lineEndVec3;
  48938. // Treat Infinity as 1000m for the line.
  48939. if (length === undefined) {
  48940. length = data.far === Infinity ? 1000 : data.far;
  48941. }
  48942. // Update the length of the line if given. `unitLineEndVec3` is the direction
  48943. // given by data.direction, then we apply a scalar to give it a length.
  48944. this.lineData.start = data.origin;
  48945. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  48946. el.setAttribute('line', this.lineData);
  48947. },
  48948. /**
  48949. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  48950. * Children are flattened by one level, removing the THREE.Group wrapper,
  48951. * so that non-recursive raycasting remains useful.
  48952. *
  48953. * Only push children defined as component attachemnts (e.g., setObject3D),
  48954. * NOT actual children in the scene graph hierarchy.
  48955. *
  48956. * @param {Array<Element>} els
  48957. * @return {Array<THREE.Object3D>}
  48958. */
  48959. flattenObject3DMaps: function (els) {
  48960. var key;
  48961. var i;
  48962. var objects = this.objects;
  48963. // Push meshes and other attachments onto list of objects to intersect.
  48964. objects.length = 0;
  48965. for (i = 0; i < els.length; i++) {
  48966. if (els[i].isEntity && els[i].object3D) {
  48967. for (key in els[i].object3DMap) {
  48968. objects.push(els[i].getObject3D(key));
  48969. }
  48970. }
  48971. }
  48972. return objects;
  48973. },
  48974. clearAllIntersections: function () {
  48975. var i;
  48976. for (i = 0; i < this.intersectedEls.length; i++) {
  48977. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  48978. this.intersectedClearedDetail);
  48979. }
  48980. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  48981. this.intersectedEls.length = 0;
  48982. this.intersections.length = 0;
  48983. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  48984. }
  48985. });
  48986. /**
  48987. * Copy contents of one array to another without allocating new array.
  48988. */
  48989. function copyArray (a, b) {
  48990. var i;
  48991. a.length = b.length;
  48992. for (i = 0; i < b.length; i++) {
  48993. a[i] = b[i];
  48994. }
  48995. }
  48996. },{"../core/component":129,"../lib/three":177,"../utils/":203}],96:[function(_dereq_,module,exports){
  48997. var degToRad = _dereq_('../lib/three').Math.degToRad;
  48998. var registerComponent = _dereq_('../core/component').registerComponent;
  48999. module.exports.Component = registerComponent('rotation', {
  49000. schema: {type: 'vec3'},
  49001. /**
  49002. * Updates object3D rotation.
  49003. */
  49004. update: function () {
  49005. var data = this.data;
  49006. var object3D = this.el.object3D;
  49007. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  49008. object3D.rotation.order = 'YXZ';
  49009. },
  49010. remove: function () {
  49011. // Pretty much for mixins.
  49012. this.el.object3D.rotation.set(0, 0, 0);
  49013. }
  49014. });
  49015. },{"../core/component":129,"../lib/three":177}],97:[function(_dereq_,module,exports){
  49016. var registerComponent = _dereq_('../core/component').registerComponent;
  49017. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  49018. var zeroScale = 0.00001;
  49019. module.exports.Component = registerComponent('scale', {
  49020. schema: {
  49021. type: 'vec3',
  49022. default: {x: 1, y: 1, z: 1}
  49023. },
  49024. update: function () {
  49025. var data = this.data;
  49026. var object3D = this.el.object3D;
  49027. var x = data.x === 0 ? zeroScale : data.x;
  49028. var y = data.y === 0 ? zeroScale : data.y;
  49029. var z = data.z === 0 ? zeroScale : data.z;
  49030. object3D.scale.set(x, y, z);
  49031. },
  49032. remove: function () {
  49033. // Pretty much for mixins.
  49034. this.el.object3D.scale.set(1, 1, 1);
  49035. }
  49036. });
  49037. },{"../core/component":129}],98:[function(_dereq_,module,exports){
  49038. /* global THREE */
  49039. var register = _dereq_('../../core/component').registerComponent;
  49040. module.exports.Component = register('background', {
  49041. schema: {
  49042. color: {type: 'color', default: 'black'},
  49043. transparent: {default: false}
  49044. },
  49045. update: function () {
  49046. var data = this.data;
  49047. var object3D = this.el.object3D;
  49048. if (data.transparent) {
  49049. object3D.background = null;
  49050. return;
  49051. }
  49052. object3D.background = new THREE.Color(data.color);
  49053. }
  49054. });
  49055. },{"../../core/component":129}],99:[function(_dereq_,module,exports){
  49056. var register = _dereq_('../../core/component').registerComponent;
  49057. module.exports.Component = register('debug', {
  49058. schema: {default: true}
  49059. });
  49060. },{"../../core/component":129}],100:[function(_dereq_,module,exports){
  49061. /* global DeviceOrientationEvent, location */
  49062. var registerComponent = _dereq_('../../core/component').registerComponent;
  49063. var utils = _dereq_('../../utils/');
  49064. var bind = utils.bind;
  49065. var constants = _dereq_('../../constants/');
  49066. var MODAL_CLASS = 'a-modal';
  49067. var DIALOG_CLASS = 'a-dialog';
  49068. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  49069. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  49070. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  49071. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  49072. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  49073. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  49074. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  49075. /**
  49076. * UI for enabling device motion permission
  49077. */
  49078. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  49079. schema: {enabled: {default: true}},
  49080. init: function () {
  49081. var self = this;
  49082. if (!this.data.enabled) { return; }
  49083. if (location.hostname !== 'localhost' &&
  49084. location.hostname !== '127.0.0.1' &&
  49085. location.protocol === 'http:') {
  49086. this.showHTTPAlert();
  49087. }
  49088. // Show alert on iPad if Safari is on desktop mode.
  49089. if (utils.device.isMobileDeviceRequestingDesktopSite()) {
  49090. this.showMobileDesktopModeAlert();
  49091. return;
  49092. }
  49093. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  49094. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  49095. this.permissionGranted = true;
  49096. return;
  49097. }
  49098. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  49099. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  49100. // Show dialog only if permission has not yet been granted.
  49101. DeviceOrientationEvent.requestPermission().catch(function () {
  49102. self.devicePermissionDialogEl = createPermissionDialog(
  49103. 'This immersive website requires access to your device motion sensors.',
  49104. self.onDeviceMotionDialogAllowClicked,
  49105. self.onDeviceMotionDialogDenyClicked);
  49106. self.el.appendChild(self.devicePermissionDialogEl);
  49107. }).then(function () {
  49108. self.el.emit('deviceorientationpermissiongranted');
  49109. self.permissionGranted = true;
  49110. });
  49111. },
  49112. remove: function () {
  49113. // This removes the modal screen
  49114. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  49115. },
  49116. onDeviceMotionDialogDenyClicked: function () {
  49117. this.remove();
  49118. },
  49119. showMobileDesktopModeAlert: function () {
  49120. var self = this;
  49121. var safariIpadAlertEl = createAlertDialog(
  49122. 'Set your browser to request the mobile version of the site and reload the page to enjoy immersive mode.',
  49123. function () { self.el.removeChild(safariIpadAlertEl); });
  49124. this.el.appendChild(safariIpadAlertEl);
  49125. },
  49126. showHTTPAlert: function () {
  49127. var self = this;
  49128. var httpAlertEl = createAlertDialog(
  49129. 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.',
  49130. function () { self.el.removeChild(httpAlertEl); });
  49131. this.el.appendChild(httpAlertEl);
  49132. },
  49133. /**
  49134. * Enable device motion permission when clicked.
  49135. */
  49136. onDeviceMotionDialogAllowClicked: function () {
  49137. var self = this;
  49138. this.el.emit('deviceorientationpermissionrequested');
  49139. DeviceOrientationEvent.requestPermission().then(function (response) {
  49140. if (response === 'granted') {
  49141. self.el.emit('deviceorientationpermissiongranted');
  49142. self.permissionGranted = true;
  49143. } else {
  49144. self.el.emit('deviceorientationpermissionrejected');
  49145. }
  49146. self.remove();
  49147. }).catch(console.error);
  49148. }
  49149. });
  49150. /**
  49151. * Create a modal dialog that request users permission to access the Device Motion API.
  49152. *
  49153. * @param {function} onAllowClicked - click event handler
  49154. * @returns {Element} Wrapper <div>.
  49155. */
  49156. function createPermissionDialog (text, onAllowClicked, onDenyClicked) {
  49157. var buttonsContainer;
  49158. var denyButton;
  49159. var acceptButton;
  49160. buttonsContainer = document.createElement('div');
  49161. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  49162. // Buttons
  49163. denyButton = document.createElement('button');
  49164. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  49165. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  49166. denyButton.innerHTML = 'Deny';
  49167. buttonsContainer.appendChild(denyButton);
  49168. acceptButton = document.createElement('button');
  49169. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  49170. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  49171. acceptButton.innerHTML = 'Allow';
  49172. buttonsContainer.appendChild(acceptButton);
  49173. // Ask for sensor events to be used
  49174. acceptButton.addEventListener('click', function (evt) {
  49175. evt.stopPropagation();
  49176. onAllowClicked();
  49177. });
  49178. denyButton.addEventListener('click', function (evt) {
  49179. evt.stopPropagation();
  49180. onDenyClicked();
  49181. });
  49182. return createDialog(text, buttonsContainer);
  49183. }
  49184. function createAlertDialog (text, onOkClicked) {
  49185. var buttonsContainer;
  49186. var okButton;
  49187. buttonsContainer = document.createElement('div');
  49188. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  49189. // Buttons
  49190. okButton = document.createElement('button');
  49191. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  49192. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  49193. okButton.innerHTML = 'Close';
  49194. buttonsContainer.appendChild(okButton);
  49195. // Ask for sensor events to be used
  49196. okButton.addEventListener('click', function (evt) {
  49197. evt.stopPropagation();
  49198. onOkClicked();
  49199. });
  49200. return createDialog(text, buttonsContainer);
  49201. }
  49202. function createDialog (text, buttonsContainerEl) {
  49203. var modalContainer;
  49204. var dialog;
  49205. var dialogTextContainer;
  49206. var dialogText;
  49207. modalContainer = document.createElement('div');
  49208. modalContainer.classList.add(MODAL_CLASS);
  49209. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  49210. dialog = document.createElement('div');
  49211. dialog.className = DIALOG_CLASS;
  49212. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  49213. modalContainer.appendChild(dialog);
  49214. dialogTextContainer = document.createElement('div');
  49215. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  49216. dialog.appendChild(dialogTextContainer);
  49217. dialogText = document.createElement('div');
  49218. dialogText.classList.add(DIALOG_TEXT_CLASS);
  49219. dialogText.innerHTML = text;
  49220. dialogTextContainer.appendChild(dialogText);
  49221. dialog.appendChild(buttonsContainerEl);
  49222. return modalContainer;
  49223. }
  49224. },{"../../constants/":121,"../../core/component":129,"../../utils/":203}],101:[function(_dereq_,module,exports){
  49225. var registerComponent = _dereq_('../../core/component').registerComponent;
  49226. /**
  49227. * Component to embed an a-frame scene within the layout of a 2D page.
  49228. */
  49229. module.exports.Component = registerComponent('embedded', {
  49230. dependencies: ['vr-mode-ui'],
  49231. schema: {default: true},
  49232. update: function () {
  49233. var sceneEl = this.el;
  49234. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  49235. if (this.data === true) {
  49236. if (enterVREl) { enterVREl.classList.add('embedded'); }
  49237. sceneEl.removeFullScreenStyles();
  49238. } else {
  49239. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  49240. sceneEl.addFullScreenStyles();
  49241. }
  49242. }
  49243. });
  49244. },{"../../core/component":129}],102:[function(_dereq_,module,exports){
  49245. var register = _dereq_('../../core/component').registerComponent;
  49246. var THREE = _dereq_('../../lib/three');
  49247. var debug = _dereq_('../../utils/debug');
  49248. var warn = debug('components:fog:warn');
  49249. /**
  49250. * Fog component.
  49251. * Applies only to the scene entity.
  49252. */
  49253. module.exports.Component = register('fog', {
  49254. schema: {
  49255. color: {type: 'color', default: '#000'},
  49256. density: {default: 0.00025},
  49257. far: {default: 1000, min: 0},
  49258. near: {default: 1, min: 0},
  49259. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  49260. },
  49261. update: function () {
  49262. var data = this.data;
  49263. var el = this.el;
  49264. var fog = this.el.object3D.fog;
  49265. if (!el.isScene) {
  49266. warn('Fog component can only be applied to <a-scene>');
  49267. return;
  49268. }
  49269. // (Re)create fog if fog doesn't exist or fog type changed.
  49270. if (!fog || data.type !== fog.name) {
  49271. el.object3D.fog = getFog(data);
  49272. el.systems.material.updateMaterials();
  49273. return;
  49274. }
  49275. // Fog data changed. Update fog.
  49276. Object.keys(this.schema).forEach(function (key) {
  49277. var value = data[key];
  49278. if (key === 'color') { value = new THREE.Color(value); }
  49279. fog[key] = value;
  49280. });
  49281. },
  49282. /**
  49283. * Remove fog on remove (callback).
  49284. */
  49285. remove: function () {
  49286. var fog = this.el.object3D.fog;
  49287. if (!fog) { return; }
  49288. fog.far = 0;
  49289. fog.near = 0.1;
  49290. }
  49291. });
  49292. /**
  49293. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  49294. *
  49295. * @param {object} data - Fog data.
  49296. * @returns {object} fog
  49297. */
  49298. function getFog (data) {
  49299. var fog;
  49300. if (data.type === 'exponential') {
  49301. fog = new THREE.FogExp2(data.color, data.density);
  49302. } else {
  49303. fog = new THREE.Fog(data.color, data.near, data.far);
  49304. }
  49305. fog.name = data.type;
  49306. return fog;
  49307. }
  49308. },{"../../core/component":129,"../../lib/three":177,"../../utils/debug":199}],103:[function(_dereq_,module,exports){
  49309. (function (process){
  49310. /* global AFRAME */
  49311. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  49312. var pkg = _dereq_('../../../package');
  49313. var registerComponent = _dereq_('../../core/component').registerComponent;
  49314. var utils = _dereq_('../../utils/');
  49315. /**
  49316. * 0.4.2 to 0.4.x
  49317. * Will need to update this when A-Frame goes to 1.x.x.
  49318. */
  49319. function getFuzzyPatchVersion (version) {
  49320. var split = version.split('.');
  49321. split[2] = 'x';
  49322. return split.join('.');
  49323. }
  49324. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  49325. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  49326. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  49327. var LOADING_MESSAGE = 'Loading Inspector';
  49328. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  49329. module.exports.Component = registerComponent('inspector', {
  49330. schema: {
  49331. url: {default: INSPECTOR_URL}
  49332. },
  49333. init: function () {
  49334. this.firstPlay = true;
  49335. this.onKeydown = this.onKeydown.bind(this);
  49336. this.onMessage = this.onMessage.bind(this);
  49337. this.initOverlay();
  49338. window.addEventListener('keydown', this.onKeydown);
  49339. window.addEventListener('message', this.onMessage);
  49340. },
  49341. play: function () {
  49342. var urlParam;
  49343. if (!this.firstPlay) { return; }
  49344. urlParam = utils.getUrlParameter('inspector');
  49345. if (urlParam !== 'false' && !!urlParam) {
  49346. this.openInspector();
  49347. this.firstPlay = false;
  49348. }
  49349. },
  49350. initOverlay: function () {
  49351. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  49352. this.loadingMessageEl = document.createElement('div');
  49353. this.loadingMessageEl.classList.add('a-inspector-loader');
  49354. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  49355. },
  49356. remove: function () {
  49357. this.removeEventListeners();
  49358. },
  49359. /**
  49360. * <ctrl> + <alt> + i keyboard shortcut.
  49361. */
  49362. onKeydown: function (evt) {
  49363. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  49364. if (!shortcutPressed) { return; }
  49365. this.openInspector();
  49366. },
  49367. showLoader: function () {
  49368. document.body.appendChild(this.loadingMessageEl);
  49369. },
  49370. hideLoader: function () {
  49371. document.body.removeChild(this.loadingMessageEl);
  49372. },
  49373. /**
  49374. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  49375. */
  49376. onMessage: function (evt) {
  49377. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  49378. },
  49379. openInspector: function (focusEl) {
  49380. var self = this;
  49381. var script;
  49382. // Already injected. Open.
  49383. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  49384. AFRAME.INSPECTOR.open(focusEl);
  49385. return;
  49386. }
  49387. this.showLoader();
  49388. // Inject.
  49389. script = document.createElement('script');
  49390. script.src = this.data.url;
  49391. script.setAttribute('data-name', 'aframe-inspector');
  49392. script.setAttribute(AFRAME_INJECTED, '');
  49393. script.onload = function () {
  49394. AFRAME.INSPECTOR.open(focusEl);
  49395. self.hideLoader();
  49396. self.removeEventListeners();
  49397. };
  49398. script.onerror = function () {
  49399. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  49400. };
  49401. document.head.appendChild(script);
  49402. AFRAME.inspectorInjected = true;
  49403. },
  49404. removeEventListeners: function () {
  49405. window.removeEventListener('keydown', this.onKeydown);
  49406. window.removeEventListener('message', this.onMessage);
  49407. }
  49408. });
  49409. }).call(this,_dereq_('_process'))
  49410. },{"../../../package":72,"../../constants":121,"../../core/component":129,"../../utils/":203,"_process":49}],104:[function(_dereq_,module,exports){
  49411. var registerComponent = _dereq_('../../core/component').registerComponent;
  49412. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  49413. module.exports.Component = registerComponent('keyboard-shortcuts', {
  49414. schema: {
  49415. enterVR: {default: true},
  49416. exitVR: {default: true}
  49417. },
  49418. init: function () {
  49419. this.onKeyup = this.onKeyup.bind(this);
  49420. },
  49421. update: function (oldData) {
  49422. var data = this.data;
  49423. this.enterVREnabled = data.enterVR;
  49424. },
  49425. play: function () {
  49426. window.addEventListener('keyup', this.onKeyup, false);
  49427. },
  49428. pause: function () {
  49429. window.removeEventListener('keyup', this.onKeyup);
  49430. },
  49431. onKeyup: function (evt) {
  49432. var scene = this.el;
  49433. if (!shouldCaptureKeyEvent(evt)) { return; }
  49434. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  49435. scene.enterVR();
  49436. }
  49437. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  49438. scene.exitVR();
  49439. }
  49440. }
  49441. });
  49442. },{"../../core/component":129,"../../utils/":203}],105:[function(_dereq_,module,exports){
  49443. var debug = _dereq_('../../utils/debug');
  49444. var registerComponent = _dereq_('../../core/component').registerComponent;
  49445. var warn = debug('components:pool:warn');
  49446. /**
  49447. * Pool component to reuse entities.
  49448. * Avoids creating and destroying the same kind of entities.
  49449. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  49450. *
  49451. * @member {array} availableEls - Available entities in the pool.
  49452. * @member {array} usedEls - Entities of the pool in use.
  49453. */
  49454. module.exports.Component = registerComponent('pool', {
  49455. schema: {
  49456. container: {default: ''},
  49457. mixin: {default: ''},
  49458. size: {default: 0},
  49459. dynamic: {default: false}
  49460. },
  49461. multiple: true,
  49462. initPool: function () {
  49463. var i;
  49464. this.availableEls = [];
  49465. this.usedEls = [];
  49466. if (!this.data.mixin) {
  49467. warn('No mixin provided for pool component.');
  49468. }
  49469. if (this.data.container) {
  49470. this.container = document.querySelector(this.data.container);
  49471. if (!this.container) {
  49472. warn('Container ' + this.data.container + ' not found.');
  49473. }
  49474. }
  49475. this.container = this.container || this.el;
  49476. for (i = 0; i < this.data.size; ++i) {
  49477. this.createEntity();
  49478. }
  49479. },
  49480. update: function (oldData) {
  49481. var data = this.data;
  49482. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  49483. this.initPool();
  49484. }
  49485. },
  49486. /**
  49487. * Add a new entity to the list of available entities.
  49488. */
  49489. createEntity: function () {
  49490. var el;
  49491. el = document.createElement('a-entity');
  49492. el.play = this.wrapPlay(el.play);
  49493. el.setAttribute('mixin', this.data.mixin);
  49494. el.object3D.visible = false;
  49495. el.pause();
  49496. this.container.appendChild(el);
  49497. this.availableEls.push(el);
  49498. },
  49499. /**
  49500. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  49501. * entities that are not in use.
  49502. */
  49503. wrapPlay: function (playMethod) {
  49504. var usedEls = this.usedEls;
  49505. return function () {
  49506. if (usedEls.indexOf(this) === -1) { return; }
  49507. playMethod.call(this);
  49508. };
  49509. },
  49510. /**
  49511. * Used to request one of the available entities of the pool.
  49512. */
  49513. requestEntity: function () {
  49514. var el;
  49515. if (this.availableEls.length === 0) {
  49516. if (this.data.dynamic === false) {
  49517. warn('Requested entity from empty pool: ' + this.attrName);
  49518. return;
  49519. } else {
  49520. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  49521. 'automatically. You might want to increase its initial size: ' + this.attrName);
  49522. }
  49523. this.createEntity();
  49524. }
  49525. el = this.availableEls.shift();
  49526. this.usedEls.push(el);
  49527. el.object3D.visible = true;
  49528. return el;
  49529. },
  49530. /**
  49531. * Used to return a used entity to the pool.
  49532. */
  49533. returnEntity: function (el) {
  49534. var index = this.usedEls.indexOf(el);
  49535. if (index === -1) {
  49536. warn('The returned entity was not previously pooled from ' + this.attrName);
  49537. return;
  49538. }
  49539. this.usedEls.splice(index, 1);
  49540. this.availableEls.push(el);
  49541. el.object3D.visible = false;
  49542. el.pause();
  49543. return el;
  49544. }
  49545. });
  49546. },{"../../core/component":129,"../../utils/debug":199}],106:[function(_dereq_,module,exports){
  49547. /* global ImageData, URL */
  49548. var registerComponent = _dereq_('../../core/component').registerComponent;
  49549. var THREE = _dereq_('../../lib/three');
  49550. var VERTEX_SHADER = [
  49551. 'attribute vec3 position;',
  49552. 'attribute vec2 uv;',
  49553. 'uniform mat4 projectionMatrix;',
  49554. 'uniform mat4 modelViewMatrix;',
  49555. 'varying vec2 vUv;',
  49556. 'void main() {',
  49557. ' vUv = vec2( 1.- uv.x, uv.y );',
  49558. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  49559. '}'
  49560. ].join('\n');
  49561. var FRAGMENT_SHADER = [
  49562. 'precision mediump float;',
  49563. 'uniform samplerCube map;',
  49564. 'varying vec2 vUv;',
  49565. '#define M_PI 3.141592653589793238462643383279',
  49566. 'void main() {',
  49567. ' vec2 uv = vUv;',
  49568. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  49569. ' float latitude = uv.y * M_PI;',
  49570. ' vec3 dir = vec3(',
  49571. ' - sin( longitude ) * sin( latitude ),',
  49572. ' cos( latitude ),',
  49573. ' - cos( longitude ) * sin( latitude )',
  49574. ' );',
  49575. ' normalize( dir );',
  49576. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  49577. '}'
  49578. ].join('\n');
  49579. /**
  49580. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  49581. * It can be configured to either take 360&deg; captures (`equirectangular`)
  49582. * or regular screenshots (`projection`)
  49583. *
  49584. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  49585. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  49586. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  49587. * WebGLRenderTarget with an ortographic camera.
  49588. */
  49589. module.exports.Component = registerComponent('screenshot', {
  49590. schema: {
  49591. width: {default: 4096},
  49592. height: {default: 2048},
  49593. camera: {type: 'selector'}
  49594. },
  49595. init: function () {
  49596. var el = this.el;
  49597. var self = this;
  49598. if (el.renderer) {
  49599. setup();
  49600. } else {
  49601. el.addEventListener('render-target-loaded', setup);
  49602. }
  49603. function setup () {
  49604. var gl = el.renderer.getContext();
  49605. if (!gl) { return; }
  49606. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  49607. self.material = new THREE.RawShaderMaterial({
  49608. uniforms: {map: {type: 't', value: null}},
  49609. vertexShader: VERTEX_SHADER,
  49610. fragmentShader: FRAGMENT_SHADER,
  49611. side: THREE.DoubleSide
  49612. });
  49613. self.quad = new THREE.Mesh(
  49614. new THREE.PlaneBufferGeometry(1, 1),
  49615. self.material
  49616. );
  49617. self.quad.visible = false;
  49618. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  49619. self.canvas = document.createElement('canvas');
  49620. self.ctx = self.canvas.getContext('2d');
  49621. el.object3D.add(self.quad);
  49622. self.onKeyDown = self.onKeyDown.bind(self);
  49623. }
  49624. },
  49625. getRenderTarget: function (width, height) {
  49626. return new THREE.WebGLRenderTarget(width, height, {
  49627. minFilter: THREE.LinearFilter,
  49628. magFilter: THREE.LinearFilter,
  49629. wrapS: THREE.ClampToEdgeWrapping,
  49630. wrapT: THREE.ClampToEdgeWrapping,
  49631. format: THREE.RGBAFormat,
  49632. type: THREE.UnsignedByteType
  49633. });
  49634. },
  49635. resize: function (width, height) {
  49636. // Resize quad.
  49637. this.quad.scale.set(width, height, 1);
  49638. // Resize camera.
  49639. this.camera.left = -1 * width / 2;
  49640. this.camera.right = width / 2;
  49641. this.camera.top = height / 2;
  49642. this.camera.bottom = -1 * height / 2;
  49643. this.camera.updateProjectionMatrix();
  49644. // Resize canvas.
  49645. this.canvas.width = width;
  49646. this.canvas.height = height;
  49647. },
  49648. play: function () {
  49649. window.addEventListener('keydown', this.onKeyDown);
  49650. },
  49651. /**
  49652. * <ctrl> + <alt> + s = Regular screenshot.
  49653. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  49654. */
  49655. onKeyDown: function (evt) {
  49656. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  49657. if (!this.data || !shortcutPressed) { return; }
  49658. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  49659. this.capture(projection);
  49660. },
  49661. /**
  49662. * Capture a screenshot of the scene.
  49663. *
  49664. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  49665. */
  49666. setCapture: function (projection) {
  49667. var el = this.el;
  49668. var size;
  49669. var camera;
  49670. var cubeCamera;
  49671. // Configure camera.
  49672. if (projection === 'perspective') {
  49673. // Quad is only used in equirectangular mode. Hide it in this case.
  49674. this.quad.visible = false;
  49675. // Use scene camera.
  49676. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  49677. size = {width: this.data.width, height: this.data.height};
  49678. } else {
  49679. // Use ortho camera.
  49680. camera = this.camera;
  49681. // Create cube camera and copy position from scene camera.
  49682. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  49683. Math.min(this.cubeMapSize, 2048));
  49684. // Copy camera position into cube camera;
  49685. el.camera.getWorldPosition(cubeCamera.position);
  49686. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  49687. // Render scene with cube camera.
  49688. cubeCamera.update(el.renderer, el.object3D);
  49689. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  49690. size = {width: this.data.width, height: this.data.height};
  49691. // Use quad to project image taken by the cube camera.
  49692. this.quad.visible = true;
  49693. }
  49694. return {
  49695. camera: camera,
  49696. size: size,
  49697. projection: projection
  49698. };
  49699. },
  49700. /**
  49701. * Maintained for backwards compatibility.
  49702. */
  49703. capture: function (projection) {
  49704. var isVREnabled = this.el.renderer.xr.enabled;
  49705. var renderer = this.el.renderer;
  49706. var params;
  49707. // Disable VR.
  49708. renderer.xr.enabled = false;
  49709. params = this.setCapture(projection);
  49710. this.renderCapture(params.camera, params.size, params.projection);
  49711. // Trigger file download.
  49712. this.saveCapture();
  49713. // Restore VR.
  49714. renderer.xr.enabled = isVREnabled;
  49715. },
  49716. /**
  49717. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  49718. */
  49719. getCanvas: function (projection) {
  49720. var isVREnabled = this.el.renderer.xr.enabled;
  49721. var renderer = this.el.renderer;
  49722. // Disable VR.
  49723. var params = this.setCapture(projection);
  49724. renderer.xr.enabled = false;
  49725. this.renderCapture(params.camera, params.size, params.projection);
  49726. // Restore VR.
  49727. renderer.xr.enabled = isVREnabled;
  49728. return this.canvas;
  49729. },
  49730. renderCapture: function (camera, size, projection) {
  49731. var autoClear = this.el.renderer.autoClear;
  49732. var el = this.el;
  49733. var imageData;
  49734. var output;
  49735. var pixels;
  49736. var renderer = el.renderer;
  49737. // Create rendering target and buffer to store the read pixels.
  49738. output = this.getRenderTarget(size.width, size.height);
  49739. pixels = new Uint8Array(4 * size.width * size.height);
  49740. // Resize quad, camera, and canvas.
  49741. this.resize(size.width, size.height);
  49742. // Render scene to render target.
  49743. renderer.autoClear = true;
  49744. renderer.clear();
  49745. renderer.setRenderTarget(output);
  49746. renderer.render(el.object3D, camera);
  49747. renderer.autoClear = autoClear;
  49748. // Read image pizels back.
  49749. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  49750. renderer.setRenderTarget(null);
  49751. if (projection === 'perspective') {
  49752. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  49753. }
  49754. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  49755. // Hide quad after projecting the image.
  49756. this.quad.visible = false;
  49757. // Copy pixels into canvas.
  49758. this.ctx.putImageData(imageData, 0, 0);
  49759. },
  49760. flipPixelsVertically: function (pixels, width, height) {
  49761. var flippedPixels = pixels.slice(0);
  49762. for (var x = 0; x < width; ++x) {
  49763. for (var y = 0; y < height; ++y) {
  49764. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  49765. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  49766. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  49767. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  49768. }
  49769. }
  49770. return flippedPixels;
  49771. },
  49772. /**
  49773. * Download capture to file.
  49774. */
  49775. saveCapture: function () {
  49776. this.canvas.toBlob(function (blob) {
  49777. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  49778. var linkEl = document.createElement('a');
  49779. var url = URL.createObjectURL(blob);
  49780. linkEl.href = url;
  49781. linkEl.setAttribute('download', fileName);
  49782. linkEl.innerHTML = 'downloading...';
  49783. linkEl.style.display = 'none';
  49784. document.body.appendChild(linkEl);
  49785. setTimeout(function () {
  49786. linkEl.click();
  49787. document.body.removeChild(linkEl);
  49788. }, 1);
  49789. }, 'image/png');
  49790. }
  49791. });
  49792. },{"../../core/component":129,"../../lib/three":177}],107:[function(_dereq_,module,exports){
  49793. var registerComponent = _dereq_('../../core/component').registerComponent;
  49794. var RStats = _dereq_('../../../vendor/rStats');
  49795. var utils = _dereq_('../../utils');
  49796. _dereq_('../../../vendor/rStats.extras');
  49797. _dereq_('../../lib/rStatsAframe');
  49798. var AFrameStats = window.aframeStats;
  49799. var bind = utils.bind;
  49800. var HIDDEN_CLASS = 'a-hidden';
  49801. var ThreeStats = window.threeStats;
  49802. /**
  49803. * Stats appended to document.body by RStats.
  49804. */
  49805. module.exports.Component = registerComponent('stats', {
  49806. schema: {default: true},
  49807. init: function () {
  49808. var scene = this.el;
  49809. if (utils.getUrlParameter('stats') === 'false') { return; }
  49810. this.stats = createStats(scene);
  49811. this.statsEl = document.querySelector('.rs-base');
  49812. this.hideBound = bind(this.hide, this);
  49813. this.showBound = bind(this.show, this);
  49814. scene.addEventListener('enter-vr', this.hideBound);
  49815. scene.addEventListener('exit-vr', this.showBound);
  49816. },
  49817. update: function () {
  49818. if (!this.stats) { return; }
  49819. return (!this.data) ? this.hide() : this.show();
  49820. },
  49821. remove: function () {
  49822. this.el.removeEventListener('enter-vr', this.hideBound);
  49823. this.el.removeEventListener('exit-vr', this.showBound);
  49824. if (!this.statsEl) { return; } // Scene detached.
  49825. this.statsEl.parentNode.removeChild(this.statsEl);
  49826. },
  49827. tick: function () {
  49828. var stats = this.stats;
  49829. if (!stats) { return; }
  49830. stats('rAF').tick();
  49831. stats('FPS').frame();
  49832. stats().update();
  49833. },
  49834. hide: function () {
  49835. this.statsEl.classList.add(HIDDEN_CLASS);
  49836. },
  49837. show: function () {
  49838. this.statsEl.classList.remove(HIDDEN_CLASS);
  49839. }
  49840. });
  49841. function createStats (scene) {
  49842. var threeStats = new ThreeStats(scene.renderer);
  49843. var aframeStats = new AFrameStats(scene);
  49844. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  49845. return new RStats({
  49846. css: [], // Our stylesheet is injected from `src/index.js`.
  49847. values: {
  49848. fps: {caption: 'fps', below: 30}
  49849. },
  49850. groups: [
  49851. {caption: 'Framerate', values: ['fps', 'raf']}
  49852. ],
  49853. plugins: plugins
  49854. });
  49855. }
  49856. },{"../../../vendor/rStats":214,"../../../vendor/rStats.extras":213,"../../core/component":129,"../../lib/rStatsAframe":176,"../../utils":203}],108:[function(_dereq_,module,exports){
  49857. var registerComponent = _dereq_('../../core/component').registerComponent;
  49858. var constants = _dereq_('../../constants/');
  49859. var utils = _dereq_('../../utils/');
  49860. var bind = utils.bind;
  49861. var ENTER_VR_CLASS = 'a-enter-vr';
  49862. var ENTER_AR_CLASS = 'a-enter-ar';
  49863. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  49864. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  49865. var HIDDEN_CLASS = 'a-hidden';
  49866. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  49867. /**
  49868. * UI for entering VR mode.
  49869. */
  49870. module.exports.Component = registerComponent('vr-mode-ui', {
  49871. dependencies: ['canvas'],
  49872. schema: {
  49873. enabled: {default: true},
  49874. enterVRButton: {default: ''},
  49875. enterARButton: {default: ''}
  49876. },
  49877. init: function () {
  49878. var self = this;
  49879. var sceneEl = this.el;
  49880. if (utils.getUrlParameter('ui') === 'false') { return; }
  49881. this.insideLoader = false;
  49882. this.enterVREl = null;
  49883. this.enterAREl = null;
  49884. this.orientationModalEl = null;
  49885. this.bindMethods();
  49886. // Hide/show VR UI when entering/exiting VR mode.
  49887. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  49888. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  49889. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  49890. window.addEventListener('message', function (event) {
  49891. if (event.data.type === 'loaderReady') {
  49892. self.insideLoader = true;
  49893. self.remove();
  49894. }
  49895. });
  49896. // Modal that tells the user to change orientation if in portrait.
  49897. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  49898. },
  49899. bindMethods: function () {
  49900. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  49901. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  49902. this.onModalClick = bind(this.onModalClick, this);
  49903. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  49904. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  49905. },
  49906. /**
  49907. * Exit VR when modal clicked.
  49908. */
  49909. onModalClick: function () {
  49910. this.el.exitVR();
  49911. },
  49912. /**
  49913. * Enter VR when clicked.
  49914. */
  49915. onEnterVRButtonClick: function () {
  49916. this.el.enterVR();
  49917. },
  49918. /**
  49919. * Enter AR when clicked.
  49920. */
  49921. onEnterARButtonClick: function () {
  49922. this.el.enterAR();
  49923. },
  49924. update: function () {
  49925. var data = this.data;
  49926. var sceneEl = this.el;
  49927. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  49928. return this.remove();
  49929. }
  49930. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  49931. // Add UI if enabled and not already present.
  49932. if (data.enterVRButton) {
  49933. // Custom button.
  49934. this.enterVREl = document.querySelector(data.enterVRButton);
  49935. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  49936. } else {
  49937. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  49938. sceneEl.appendChild(this.enterVREl);
  49939. }
  49940. if (data.enterARButton) {
  49941. // Custom button.
  49942. this.enterAREl = document.querySelector(data.enterARButton);
  49943. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  49944. } else {
  49945. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  49946. sceneEl.appendChild(this.enterAREl);
  49947. }
  49948. this.orientationModalEl = createOrientationModal(this.onModalClick);
  49949. sceneEl.appendChild(this.orientationModalEl);
  49950. this.updateEnterInterfaces();
  49951. },
  49952. remove: function () {
  49953. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  49954. if (uiElement && uiElement.parentNode) {
  49955. uiElement.parentNode.removeChild(uiElement);
  49956. }
  49957. });
  49958. },
  49959. updateEnterInterfaces: function () {
  49960. this.toggleEnterVRButtonIfNeeded();
  49961. this.toggleEnterARButtonIfNeeded();
  49962. this.toggleOrientationModalIfNeeded();
  49963. },
  49964. toggleEnterVRButtonIfNeeded: function () {
  49965. var sceneEl = this.el;
  49966. if (!this.enterVREl) { return; }
  49967. if (sceneEl.is('vr-mode')) {
  49968. this.enterVREl.classList.add(HIDDEN_CLASS);
  49969. } else {
  49970. this.enterVREl.classList.remove(HIDDEN_CLASS);
  49971. }
  49972. },
  49973. toggleEnterARButtonIfNeeded: function () {
  49974. var sceneEl = this.el;
  49975. if (!this.enterAREl) { return; }
  49976. // Hide the button while in a session, or if AR is not supported.
  49977. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  49978. this.enterAREl.classList.add(HIDDEN_CLASS);
  49979. } else {
  49980. this.enterAREl.classList.remove(HIDDEN_CLASS);
  49981. }
  49982. },
  49983. toggleOrientationModalIfNeeded: function () {
  49984. var sceneEl = this.el;
  49985. var orientationModalEl = this.orientationModalEl;
  49986. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  49987. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  49988. // Show if in VR mode on portrait.
  49989. orientationModalEl.classList.remove(HIDDEN_CLASS);
  49990. } else {
  49991. orientationModalEl.classList.add(HIDDEN_CLASS);
  49992. }
  49993. }
  49994. });
  49995. /**
  49996. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  49997. *
  49998. * Structure: <div><button></div>
  49999. *
  50000. * @param {function} onClick - click event handler
  50001. * @returns {Element} Wrapper <div>.
  50002. */
  50003. function createEnterVRButton (onClick) {
  50004. var vrButton;
  50005. var wrapper;
  50006. // Create elements.
  50007. wrapper = document.createElement('div');
  50008. wrapper.classList.add(ENTER_VR_CLASS);
  50009. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  50010. vrButton = document.createElement('button');
  50011. vrButton.className = ENTER_VR_BTN_CLASS;
  50012. vrButton.setAttribute('title',
  50013. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  50014. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  50015. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  50016. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  50017. // Insert elements.
  50018. wrapper.appendChild(vrButton);
  50019. vrButton.addEventListener('click', function (evt) {
  50020. onClick();
  50021. evt.stopPropagation();
  50022. });
  50023. return wrapper;
  50024. }
  50025. /**
  50026. * Create a button that when clicked will enter into AR mode
  50027. *
  50028. * Structure: <div><button></div>
  50029. *
  50030. * @param {function} onClick - click event handler
  50031. * @returns {Element} Wrapper <div>.
  50032. */
  50033. function createEnterARButton (onClick) {
  50034. var arButton;
  50035. var wrapper;
  50036. // Create elements.
  50037. wrapper = document.createElement('div');
  50038. wrapper.classList.add(ENTER_AR_CLASS);
  50039. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  50040. arButton = document.createElement('button');
  50041. arButton.className = ENTER_AR_BTN_CLASS;
  50042. arButton.setAttribute('title',
  50043. 'Enter AR mode with a headset or handheld device. ' +
  50044. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  50045. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  50046. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  50047. // Insert elements.
  50048. wrapper.appendChild(arButton);
  50049. arButton.addEventListener('click', function (evt) {
  50050. onClick();
  50051. evt.stopPropagation();
  50052. });
  50053. return wrapper;
  50054. }
  50055. /**
  50056. * Creates a modal dialog to request the user to switch to landscape orientation.
  50057. *
  50058. * @param {function} onClick - click event handler
  50059. * @returns {Element} Wrapper <div>.
  50060. */
  50061. function createOrientationModal (onClick) {
  50062. var modal = document.createElement('div');
  50063. modal.className = ORIENTATION_MODAL_CLASS;
  50064. modal.classList.add(HIDDEN_CLASS);
  50065. modal.setAttribute(constants.AFRAME_INJECTED, '');
  50066. var exit = document.createElement('button');
  50067. exit.setAttribute(constants.AFRAME_INJECTED, '');
  50068. exit.innerHTML = 'Exit VR';
  50069. // Exit VR on close.
  50070. exit.addEventListener('click', onClick);
  50071. modal.appendChild(exit);
  50072. return modal;
  50073. }
  50074. /**
  50075. * CSS hover state is sticky in iOS (as in 12/18/2019)
  50076. * They are not removed on mouseleave and this function applies a class
  50077. * to resets the style.
  50078. *
  50079. * @param {function} buttonEl - Button element
  50080. */
  50081. function applyStickyHoverFix (buttonEl) {
  50082. buttonEl.addEventListener('touchstart', function () {
  50083. buttonEl.classList.remove('resethover');
  50084. });
  50085. buttonEl.addEventListener('touchend', function () {
  50086. buttonEl.classList.add('resethover');
  50087. });
  50088. }
  50089. },{"../../constants/":121,"../../core/component":129,"../../utils/":203}],109:[function(_dereq_,module,exports){
  50090. var component = _dereq_('../core/component');
  50091. var THREE = _dereq_('../lib/three');
  50092. var bind = _dereq_('../utils/bind');
  50093. var registerComponent = component.registerComponent;
  50094. /**
  50095. * Shadow component.
  50096. *
  50097. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  50098. * shadows as specified by the `cast` and `receive` properties.
  50099. */
  50100. module.exports.Component = registerComponent('shadow', {
  50101. schema: {
  50102. cast: {default: true},
  50103. receive: {default: true}
  50104. },
  50105. init: function () {
  50106. this.onMeshChanged = bind(this.update, this);
  50107. this.el.addEventListener('object3dset', this.onMeshChanged);
  50108. this.system.setShadowMapEnabled(true);
  50109. },
  50110. update: function () {
  50111. var data = this.data;
  50112. this.updateDescendants(data.cast, data.receive);
  50113. },
  50114. remove: function () {
  50115. var el = this.el;
  50116. el.removeEventListener('object3dset', this.onMeshChanged);
  50117. this.updateDescendants(false, false);
  50118. },
  50119. updateDescendants: function (cast, receive) {
  50120. var sceneEl = this.el.sceneEl;
  50121. this.el.object3D.traverse(function (node) {
  50122. if (!(node instanceof THREE.Mesh)) { return; }
  50123. node.castShadow = cast;
  50124. node.receiveShadow = receive;
  50125. // If scene has already rendered, materials must be updated.
  50126. if (sceneEl.hasLoaded && node.material) {
  50127. var materials = Array.isArray(node.material) ? node.material : [node.material];
  50128. for (var i = 0; i < materials.length; i++) {
  50129. materials[i].needsUpdate = true;
  50130. }
  50131. }
  50132. });
  50133. }
  50134. });
  50135. },{"../core/component":129,"../lib/three":177,"../utils/bind":197}],110:[function(_dereq_,module,exports){
  50136. var registerComponent = _dereq_('../core/component').registerComponent;
  50137. var debug = _dereq_('../utils/debug');
  50138. var THREE = _dereq_('../lib/three');
  50139. var warn = debug('components:sound:warn');
  50140. /**
  50141. * Sound component.
  50142. */
  50143. module.exports.Component = registerComponent('sound', {
  50144. schema: {
  50145. autoplay: {default: false},
  50146. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  50147. loop: {default: false},
  50148. maxDistance: {default: 10000},
  50149. on: {default: ''},
  50150. poolSize: {default: 1},
  50151. positional: {default: true},
  50152. refDistance: {default: 1},
  50153. rolloffFactor: {default: 1},
  50154. src: {type: 'audio'},
  50155. volume: {default: 1}
  50156. },
  50157. multiple: true,
  50158. init: function () {
  50159. var self = this;
  50160. this.listener = null;
  50161. this.audioLoader = new THREE.AudioLoader();
  50162. this.pool = new THREE.Group();
  50163. this.loaded = false;
  50164. this.mustPlay = false;
  50165. // Don't pass evt because playSound takes a function as parameter.
  50166. this.playSoundBound = function () { self.playSound(); };
  50167. },
  50168. update: function (oldData) {
  50169. var data = this.data;
  50170. var i;
  50171. var sound;
  50172. var srcChanged = data.src !== oldData.src;
  50173. // Create new sound if not yet created or changing `src`.
  50174. if (srcChanged) {
  50175. if (!data.src) { return; }
  50176. this.setupSound();
  50177. }
  50178. for (i = 0; i < this.pool.children.length; i++) {
  50179. sound = this.pool.children[i];
  50180. if (data.positional) {
  50181. sound.setDistanceModel(data.distanceModel);
  50182. sound.setMaxDistance(data.maxDistance);
  50183. sound.setRefDistance(data.refDistance);
  50184. sound.setRolloffFactor(data.rolloffFactor);
  50185. }
  50186. sound.setLoop(data.loop);
  50187. sound.setVolume(data.volume);
  50188. sound.isPaused = false;
  50189. }
  50190. if (data.on !== oldData.on) {
  50191. this.updateEventListener(oldData.on);
  50192. }
  50193. // All sound values set. Load in `src`.
  50194. if (srcChanged) {
  50195. var self = this;
  50196. this.loaded = false;
  50197. this.audioLoader.load(data.src, function (buffer) {
  50198. for (i = 0; i < self.pool.children.length; i++) {
  50199. sound = self.pool.children[i];
  50200. sound.setBuffer(buffer);
  50201. }
  50202. self.loaded = true;
  50203. // Remove this key from cache, otherwise we can't play it again
  50204. THREE.Cache.remove(data.src);
  50205. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  50206. self.el.emit('sound-loaded', self.evtDetail, false);
  50207. });
  50208. }
  50209. },
  50210. pause: function () {
  50211. this.stopSound();
  50212. this.removeEventListener();
  50213. },
  50214. play: function () {
  50215. if (this.data.autoplay) { this.playSound(); }
  50216. this.updateEventListener();
  50217. },
  50218. remove: function () {
  50219. var i;
  50220. var sound;
  50221. this.removeEventListener();
  50222. if (this.el.getObject3D(this.attrName)) {
  50223. this.el.removeObject3D(this.attrName);
  50224. }
  50225. try {
  50226. for (i = 0; i < this.pool.children.length; i++) {
  50227. sound = this.pool.children[i];
  50228. sound.disconnect();
  50229. }
  50230. } catch (e) {
  50231. // disconnect() will throw if it was never connected initially.
  50232. warn('Audio source not properly disconnected');
  50233. }
  50234. },
  50235. /**
  50236. * Update listener attached to the user defined on event.
  50237. */
  50238. updateEventListener: function (oldEvt) {
  50239. var el = this.el;
  50240. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  50241. el.addEventListener(this.data.on, this.playSoundBound);
  50242. },
  50243. removeEventListener: function () {
  50244. this.el.removeEventListener(this.data.on, this.playSoundBound);
  50245. },
  50246. /**
  50247. * Removes current sound object, creates new sound object, adds to entity.
  50248. *
  50249. * @returns {object} sound
  50250. */
  50251. setupSound: function () {
  50252. var el = this.el;
  50253. var i;
  50254. var sceneEl = el.sceneEl;
  50255. var self = this;
  50256. var sound;
  50257. if (this.pool.children.length > 0) {
  50258. this.stopSound();
  50259. el.removeObject3D('sound');
  50260. }
  50261. // Only want one AudioListener. Cache it on the scene.
  50262. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  50263. sceneEl.audioListener = listener;
  50264. if (sceneEl.camera) {
  50265. sceneEl.camera.add(listener);
  50266. }
  50267. // Wait for camera if necessary.
  50268. sceneEl.addEventListener('camera-set-active', function (evt) {
  50269. evt.detail.cameraEl.getObject3D('camera').add(listener);
  50270. });
  50271. // Create [poolSize] audio instances and attach them to pool
  50272. this.pool = new THREE.Group();
  50273. for (i = 0; i < this.data.poolSize; i++) {
  50274. sound = this.data.positional
  50275. ? new THREE.PositionalAudio(listener)
  50276. : new THREE.Audio(listener);
  50277. this.pool.add(sound);
  50278. }
  50279. el.setObject3D(this.attrName, this.pool);
  50280. for (i = 0; i < this.pool.children.length; i++) {
  50281. sound = this.pool.children[i];
  50282. sound.onEnded = function () {
  50283. this.isPlaying = false;
  50284. self.el.emit('sound-ended', self.evtDetail, false);
  50285. };
  50286. }
  50287. },
  50288. /**
  50289. * Pause all the sounds in the pool.
  50290. */
  50291. pauseSound: function () {
  50292. var i;
  50293. var sound;
  50294. this.isPlaying = false;
  50295. for (i = 0; i < this.pool.children.length; i++) {
  50296. sound = this.pool.children[i];
  50297. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  50298. continue;
  50299. }
  50300. sound.isPaused = true;
  50301. sound.pause();
  50302. }
  50303. },
  50304. /**
  50305. * Look for an unused sound in the pool and play it if found.
  50306. */
  50307. playSound: function (processSound) {
  50308. var found;
  50309. var i;
  50310. var sound;
  50311. if (!this.loaded) {
  50312. warn('Sound not loaded yet. It will be played once it finished loading');
  50313. this.mustPlay = true;
  50314. return;
  50315. }
  50316. found = false;
  50317. this.isPlaying = true;
  50318. for (i = 0; i < this.pool.children.length; i++) {
  50319. sound = this.pool.children[i];
  50320. if (!sound.isPlaying && sound.buffer && !found) {
  50321. if (processSound) { processSound(sound); }
  50322. sound.play();
  50323. sound.isPaused = false;
  50324. found = true;
  50325. continue;
  50326. }
  50327. }
  50328. if (!found) {
  50329. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  50330. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  50331. return;
  50332. }
  50333. this.mustPlay = false;
  50334. },
  50335. /**
  50336. * Stop all the sounds in the pool.
  50337. */
  50338. stopSound: function () {
  50339. var i;
  50340. var sound;
  50341. this.isPlaying = false;
  50342. for (i = 0; i < this.pool.children.length; i++) {
  50343. sound = this.pool.children[i];
  50344. if (!sound.source || !sound.source.buffer) { return; }
  50345. sound.stop();
  50346. }
  50347. }
  50348. });
  50349. },{"../core/component":129,"../lib/three":177,"../utils/debug":199}],111:[function(_dereq_,module,exports){
  50350. var createTextGeometry = _dereq_('three-bmfont-text');
  50351. var loadBMFont = _dereq_('load-bmfont');
  50352. var registerComponent = _dereq_('../core/component').registerComponent;
  50353. var coreShader = _dereq_('../core/shader');
  50354. var THREE = _dereq_('../lib/three');
  50355. var utils = _dereq_('../utils/');
  50356. var error = utils.debug('components:text:error');
  50357. var shaders = coreShader.shaders;
  50358. var warn = utils.debug('components:text:warn');
  50359. // 1 to match other A-Frame default widths.
  50360. var DEFAULT_WIDTH = 1;
  50361. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  50362. var MAX_ANISOTROPY = 16;
  50363. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  50364. var FONTS = {
  50365. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  50366. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  50367. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  50368. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  50369. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  50370. monoid: FONT_BASE_URL + 'Monoid.fnt',
  50371. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  50372. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  50373. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  50374. };
  50375. var MSDF_FONTS = ['roboto'];
  50376. var DEFAULT_FONT = 'roboto';
  50377. module.exports.FONTS = FONTS;
  50378. var cache = new PromiseCache();
  50379. var fontWidthFactors = {};
  50380. var textures = {};
  50381. // Regular expression for detecting a URLs with a protocol prefix.
  50382. var protocolRe = /^\w+:/;
  50383. /**
  50384. * SDF-based text component.
  50385. * Based on https://github.com/Jam3/three-bmfont-text.
  50386. *
  50387. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  50388. * original `sdf` shader.
  50389. */
  50390. module.exports.Component = registerComponent('text', {
  50391. multiple: true,
  50392. schema: {
  50393. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  50394. alphaTest: {default: 0.5},
  50395. // `anchor` defaults to center to match geometries.
  50396. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  50397. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  50398. color: {type: 'color', default: '#FFF'},
  50399. font: {type: 'string', default: DEFAULT_FONT},
  50400. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  50401. fontImage: {type: 'string'},
  50402. // `height` has no default, will be populated at layout.
  50403. height: {type: 'number'},
  50404. letterSpacing: {type: 'number', default: 0},
  50405. // `lineHeight` defaults to font's `lineHeight` value.
  50406. lineHeight: {type: 'number'},
  50407. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  50408. negate: {type: 'boolean', default: true},
  50409. opacity: {type: 'number', default: 1.0},
  50410. shader: {default: 'sdf', oneOf: shaders},
  50411. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  50412. tabSize: {default: 4},
  50413. transparent: {default: true},
  50414. value: {type: 'string'},
  50415. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  50416. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  50417. width: {type: 'number'},
  50418. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  50419. wrapCount: {type: 'number', default: 40},
  50420. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  50421. wrapPixels: {type: 'number'},
  50422. // `xOffset` to add padding.
  50423. xOffset: {type: 'number', default: 0},
  50424. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  50425. yOffset: {type: 'number', default: 0},
  50426. // `zOffset` will provide a small z offset to avoid z-fighting.
  50427. zOffset: {type: 'number', default: 0.001}
  50428. },
  50429. init: function () {
  50430. this.shaderData = {};
  50431. this.geometry = createTextGeometry();
  50432. this.createOrUpdateMaterial();
  50433. this.mesh = new THREE.Mesh(this.geometry, this.material);
  50434. this.el.setObject3D(this.attrName, this.mesh);
  50435. },
  50436. update: function (oldData) {
  50437. var data = this.data;
  50438. var font = this.currentFont;
  50439. if (textures[data.font]) {
  50440. this.texture = textures[data.font];
  50441. } else {
  50442. // Create texture per font.
  50443. this.texture = textures[data.font] = new THREE.Texture();
  50444. this.texture.anisotropy = MAX_ANISOTROPY;
  50445. }
  50446. // Update material.
  50447. this.createOrUpdateMaterial();
  50448. // New font. `updateFont` will later change data and layout.
  50449. if (oldData.font !== data.font) {
  50450. this.updateFont();
  50451. return;
  50452. }
  50453. // Update geometry and layout.
  50454. if (font) {
  50455. this.updateGeometry(this.geometry, font);
  50456. this.updateLayout();
  50457. }
  50458. },
  50459. /**
  50460. * Clean up geometry, material, texture, mesh, objects.
  50461. */
  50462. remove: function () {
  50463. this.geometry.dispose();
  50464. this.geometry = null;
  50465. this.el.removeObject3D(this.attrName);
  50466. this.material.dispose();
  50467. this.material = null;
  50468. this.texture.dispose();
  50469. this.texture = null;
  50470. if (this.shaderObject) {
  50471. delete this.shaderObject;
  50472. }
  50473. },
  50474. /**
  50475. * Update the shader of the material.
  50476. */
  50477. createOrUpdateMaterial: function () {
  50478. var data = this.data;
  50479. var hasChangedShader;
  50480. var material = this.material;
  50481. var NewShader;
  50482. var shaderData = this.shaderData;
  50483. var shaderName;
  50484. // Infer shader if using a stock font (or from `-msdf` filename convention).
  50485. shaderName = data.shader;
  50486. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  50487. //LiveCoding.space FIX
  50488. let webgl2 = document.querySelector('a-scene').renderer.capabilities.isWebGL2;
  50489. shaderName = webgl2 ? 'msdf' : 'msdf1'
  50490. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  50491. shaderName = 'sdf';
  50492. }
  50493. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  50494. shaderData.alphaTest = data.alphaTest;
  50495. shaderData.color = data.color;
  50496. shaderData.map = this.texture;
  50497. shaderData.opacity = data.opacity;
  50498. shaderData.side = parseSide(data.side);
  50499. shaderData.transparent = data.transparent;
  50500. shaderData.negate = data.negate;
  50501. // Shader has not changed, do an update.
  50502. if (!hasChangedShader) {
  50503. // Update shader material.
  50504. this.shaderObject.update(shaderData);
  50505. // Apparently, was not set on `init` nor `update`.
  50506. material.transparent = shaderData.transparent;
  50507. material.side = shaderData.side;
  50508. return;
  50509. }
  50510. // Shader has changed. Create a shader material.
  50511. NewShader = createShader(this.el, shaderName, shaderData);
  50512. this.material = NewShader.material;
  50513. this.shaderObject = NewShader.shader;
  50514. // Set new shader material.
  50515. this.material.side = shaderData.side;
  50516. if (this.mesh) { this.mesh.material = this.material; }
  50517. },
  50518. /**
  50519. * Load font for geometry, load font image for material, and apply.
  50520. */
  50521. updateFont: function () {
  50522. var data = this.data;
  50523. var el = this.el;
  50524. var fontSrc;
  50525. var geometry = this.geometry;
  50526. var self = this;
  50527. if (!data.font) { warn('No font specified. Using the default font.'); }
  50528. // Make invisible during font swap.
  50529. this.mesh.visible = false;
  50530. // Look up font URL to use, and perform cached load.
  50531. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  50532. cache.get(fontSrc, function doLoadFont () {
  50533. return loadFont(fontSrc, data.yOffset);
  50534. }).then(function setFont (font) {
  50535. var fontImgSrc;
  50536. if (font.pages.length !== 1) {
  50537. throw new Error('Currently only single-page bitmap fonts are supported.');
  50538. }
  50539. if (!fontWidthFactors[fontSrc]) {
  50540. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  50541. }
  50542. // Update geometry given font metrics.
  50543. self.updateGeometry(geometry, font);
  50544. // Set font and update layout.
  50545. self.currentFont = font;
  50546. self.updateLayout();
  50547. // Look up font image URL to use, and perform cached load.
  50548. fontImgSrc = self.getFontImageSrc();
  50549. cache.get(fontImgSrc, function () {
  50550. return loadTexture(fontImgSrc);
  50551. }).then(function (image) {
  50552. // Make mesh visible and apply font image as texture.
  50553. var texture = self.texture;
  50554. texture.image = image;
  50555. texture.needsUpdate = true;
  50556. textures[data.font] = texture;
  50557. self.texture = texture;
  50558. self.mesh.visible = true;
  50559. el.emit('textfontset', {font: data.font, fontObj: font});
  50560. }).catch(function (err) {
  50561. error(err.message);
  50562. error(err.stack);
  50563. });
  50564. }).catch(function (err) {
  50565. error(err.message);
  50566. error(err.stack);
  50567. });
  50568. },
  50569. getFontImageSrc: function () {
  50570. if (this.data.fontImage) { return this.data.fontImage; }
  50571. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  50572. var imageSrc = this.currentFont.pages[0];
  50573. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  50574. // path on disk and try to infer the path from the font source instead.
  50575. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  50576. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  50577. }
  50578. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  50579. },
  50580. /**
  50581. * Update layout with anchor, alignment, baseline, and considering any meshes.
  50582. */
  50583. updateLayout: function () {
  50584. var anchor;
  50585. var baseline;
  50586. var el = this.el;
  50587. var data = this.data;
  50588. var geometry = this.geometry;
  50589. var geometryComponent;
  50590. var height;
  50591. var layout;
  50592. var mesh = this.mesh;
  50593. var textRenderWidth;
  50594. var textScale;
  50595. var width;
  50596. var x;
  50597. var y;
  50598. if (!geometry.layout) { return; }
  50599. // Determine width to use (defined width, geometry's width, or default width).
  50600. geometryComponent = el.getAttribute('geometry');
  50601. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  50602. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  50603. // Note that experimental factor will never be correct for variable width fonts.
  50604. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  50605. this.currentFont.widthFactor);
  50606. textScale = width / textRenderWidth;
  50607. // Determine height to use.
  50608. layout = geometry.layout;
  50609. height = textScale * (layout.height + layout.descender);
  50610. // Update geometry dimensions to match text layout if width and height are set to 0.
  50611. // For example, scales a plane to fit text.
  50612. if (geometryComponent && geometryComponent.primitive === 'plane') {
  50613. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  50614. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  50615. }
  50616. // Calculate X position to anchor text left, center, or right.
  50617. anchor = data.anchor === 'align' ? data.align : data.anchor;
  50618. if (anchor === 'left') {
  50619. x = 0;
  50620. } else if (anchor === 'right') {
  50621. x = -1 * layout.width;
  50622. } else if (anchor === 'center') {
  50623. x = -1 * layout.width / 2;
  50624. } else {
  50625. throw new TypeError('Invalid text.anchor property value', anchor);
  50626. }
  50627. // Calculate Y position to anchor text top, center, or bottom.
  50628. baseline = data.baseline;
  50629. if (baseline === 'bottom') {
  50630. y = 0;
  50631. } else if (baseline === 'top') {
  50632. y = -1 * layout.height + layout.ascender;
  50633. } else if (baseline === 'center') {
  50634. y = -1 * layout.height / 2;
  50635. } else {
  50636. throw new TypeError('Invalid text.baseline property value', baseline);
  50637. }
  50638. // Position and scale mesh to apply layout.
  50639. mesh.position.x = x * textScale + data.xOffset;
  50640. mesh.position.y = y * textScale;
  50641. // Place text slightly in front to avoid Z-fighting.
  50642. mesh.position.z = data.zOffset;
  50643. mesh.scale.set(textScale, -1 * textScale, textScale);
  50644. },
  50645. /**
  50646. * Grab font from the constant.
  50647. * Set as a method for test stubbing purposes.
  50648. */
  50649. lookupFont: function (key) {
  50650. return FONTS[key];
  50651. },
  50652. /**
  50653. * Update the text geometry using `three-bmfont-text.update`.
  50654. */
  50655. updateGeometry: (function () {
  50656. var geometryUpdateBase = {};
  50657. var geometryUpdateData = {};
  50658. var newLineRegex = /\\n/g;
  50659. var tabRegex = /\\t/g;
  50660. return function (geometry, font) {
  50661. var data = this.data;
  50662. geometryUpdateData.font = font;
  50663. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  50664. ? data.lineHeight
  50665. : font.common.lineHeight;
  50666. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  50667. .replace(tabRegex, '\t');
  50668. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  50669. font.widthFactor);
  50670. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  50671. };
  50672. })()
  50673. });
  50674. /**
  50675. * Due to using negative scale, we return the opposite side specified.
  50676. * https://github.com/mrdoob/three.js/pull/12787/
  50677. */
  50678. function parseSide (side) {
  50679. switch (side) {
  50680. case 'back': {
  50681. return THREE.FrontSide;
  50682. }
  50683. case 'double': {
  50684. return THREE.DoubleSide;
  50685. }
  50686. default: {
  50687. return THREE.BackSide;
  50688. }
  50689. }
  50690. }
  50691. /**
  50692. * @returns {Promise}
  50693. */
  50694. function loadFont (src, yOffset) {
  50695. return new Promise(function (resolve, reject) {
  50696. loadBMFont(src, function (err, font) {
  50697. if (err) {
  50698. error('Error loading font', src);
  50699. reject(err);
  50700. return;
  50701. }
  50702. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  50703. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  50704. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  50705. resolve(font);
  50706. });
  50707. });
  50708. }
  50709. /**
  50710. * @returns {Promise}
  50711. */
  50712. function loadTexture (src) {
  50713. return new Promise(function (resolve, reject) {
  50714. new THREE.ImageLoader().load(src, function (image) {
  50715. resolve(image);
  50716. }, undefined, function () {
  50717. error('Error loading font image', src);
  50718. reject(null);
  50719. });
  50720. });
  50721. }
  50722. function createShader (el, shaderName, data) {
  50723. var shader;
  50724. var shaderObject;
  50725. // Set up Shader.
  50726. shaderObject = new shaders[shaderName].Shader();
  50727. shaderObject.el = el;
  50728. shaderObject.init(data);
  50729. shaderObject.update(data);
  50730. // Get material.
  50731. shader = shaderObject.material;
  50732. // Apparently, was not set on `init` nor `update`.
  50733. shader.transparent = data.transparent;
  50734. return {
  50735. material: shader,
  50736. shader: shaderObject
  50737. };
  50738. }
  50739. /**
  50740. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  50741. * Note that experimental factor will never be correct for variable width fonts.
  50742. */
  50743. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  50744. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  50745. }
  50746. /**
  50747. * Compute default font width factor to use.
  50748. */
  50749. function computeFontWidthFactor (font) {
  50750. var sum = 0;
  50751. var digitsum = 0;
  50752. var digits = 0;
  50753. font.chars.map(function (ch) {
  50754. sum += ch.xadvance;
  50755. if (ch.id >= 48 && ch.id <= 57) {
  50756. digits++;
  50757. digitsum += ch.xadvance;
  50758. }
  50759. });
  50760. return digits ? digitsum / digits : sum / font.chars.length;
  50761. }
  50762. /**
  50763. * Get or create a promise given a key and promise generator.
  50764. * @todo Move to a utility and use in other parts of A-Frame.
  50765. */
  50766. function PromiseCache () {
  50767. var cache = this.cache = {};
  50768. this.get = function (key, promiseGenerator) {
  50769. if (key in cache) {
  50770. return cache[key];
  50771. }
  50772. cache[key] = promiseGenerator();
  50773. return cache[key];
  50774. };
  50775. }
  50776. },{"../core/component":129,"../core/shader":139,"../lib/three":177,"../utils/":203,"load-bmfont":37,"three-bmfont-text":62}],112:[function(_dereq_,module,exports){
  50777. var registerComponent = _dereq_('../core/component').registerComponent;
  50778. var controllerUtils = _dereq_('../utils/tracked-controls');
  50779. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  50780. var THREE = _dereq_('../lib/three');
  50781. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  50782. // Vector from eyes to elbow (divided by user height).
  50783. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  50784. // Vector from eyes to elbow (divided by user height).
  50785. var FOREARM = {x: 0, y: 0, z: -0.175};
  50786. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  50787. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  50788. var EVENTS = {
  50789. AXISMOVE: 'axismove',
  50790. BUTTONCHANGED: 'buttonchanged',
  50791. BUTTONDOWN: 'buttondown',
  50792. BUTTONUP: 'buttonup',
  50793. TOUCHSTART: 'touchstart',
  50794. TOUCHEND: 'touchend'
  50795. };
  50796. /**
  50797. * Tracked controls component.
  50798. * Wrap the gamepad API for pose and button states.
  50799. * Select the appropriate controller and apply pose to the entity.
  50800. * Observe button states and emit appropriate events.
  50801. *
  50802. * @property {number} controller - Index of controller in array returned by Gamepad API.
  50803. * Only used if hand property is not set.
  50804. * @property {string} id - Selected controller among those returned by Gamepad API.
  50805. * @property {number} hand - If multiple controllers found with id, choose the one with the
  50806. * given value for hand. If set, we ignore 'controller' property
  50807. */
  50808. module.exports.Component = registerComponent('tracked-controls-webvr', {
  50809. schema: {
  50810. autoHide: {default: true},
  50811. controller: {default: 0},
  50812. id: {type: 'string', default: ''},
  50813. hand: {type: 'string', default: ''},
  50814. idPrefix: {type: 'string', default: ''},
  50815. orientationOffset: {type: 'vec3'},
  50816. // Arm model parameters when not 6DoF.
  50817. armModel: {default: false},
  50818. headElement: {type: 'selector'}
  50819. },
  50820. init: function () {
  50821. // Copy variables back to tracked-controls for backwards compatibility.
  50822. // Some 3rd components rely on them.
  50823. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  50824. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  50825. this.changedAxes = [];
  50826. this.targetControllerNumber = this.data.controller;
  50827. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  50828. this.deltaControllerPosition = new THREE.Vector3();
  50829. this.controllerQuaternion = new THREE.Quaternion();
  50830. this.controllerEuler = new THREE.Euler();
  50831. this.updateGamepad();
  50832. this.buttonEventDetails = {};
  50833. },
  50834. tick: function (time, delta) {
  50835. var mesh = this.el.getObject3D('mesh');
  50836. // Update mesh animations.
  50837. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  50838. this.updateGamepad();
  50839. this.updatePose();
  50840. this.updateButtons();
  50841. },
  50842. /**
  50843. * Return default user height to use for non-6DOF arm model.
  50844. */
  50845. defaultUserHeight: function () {
  50846. return DEFAULT_CAMERA_HEIGHT;
  50847. },
  50848. /**
  50849. * Return head element to use for non-6DOF arm model.
  50850. */
  50851. getHeadElement: function () {
  50852. return this.data.headElement || this.el.sceneEl.camera.el;
  50853. },
  50854. /**
  50855. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  50856. */
  50857. updateGamepad: function () {
  50858. var data = this.data;
  50859. var controller = controllerUtils.findMatchingControllerWebVR(
  50860. this.system.controllers,
  50861. data.id,
  50862. data.idPrefix,
  50863. data.hand,
  50864. data.controller
  50865. );
  50866. this.controller = controller;
  50867. // Legacy handle to the controller for old components.
  50868. this.el.components['tracked-controls'].controller = controller;
  50869. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  50870. },
  50871. /**
  50872. * Applies an artificial arm model to simulate elbow to wrist positioning
  50873. * based on the orientation of the controller.
  50874. *
  50875. * @param {object} controllerPosition - Existing vector to update with controller position.
  50876. */
  50877. applyArmModel: function (controllerPosition) {
  50878. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  50879. var controller = this.controller;
  50880. var controllerEuler = this.controllerEuler;
  50881. var controllerQuaternion = this.controllerQuaternion;
  50882. var deltaControllerPosition = this.deltaControllerPosition;
  50883. var hand;
  50884. var headEl;
  50885. var headObject3D;
  50886. var pose;
  50887. var userHeight;
  50888. headEl = this.getHeadElement();
  50889. headObject3D = headEl.object3D;
  50890. userHeight = this.defaultUserHeight();
  50891. pose = controller.pose;
  50892. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  50893. // Use camera position as head position.
  50894. controllerPosition.copy(headObject3D.position);
  50895. // Set offset for degenerate "arm model" to elbow.
  50896. deltaControllerPosition.set(
  50897. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  50898. EYES_TO_ELBOW.y, // Lower than our eyes.
  50899. EYES_TO_ELBOW.z); // Slightly out in front.
  50900. // Scale offset by user height.
  50901. deltaControllerPosition.multiplyScalar(userHeight);
  50902. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  50903. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  50904. // Apply rotated offset to position.
  50905. controllerPosition.add(deltaControllerPosition);
  50906. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  50907. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  50908. // Scale offset by user height.
  50909. deltaControllerPosition.multiplyScalar(userHeight);
  50910. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  50911. if (pose.orientation) {
  50912. controllerQuaternion.fromArray(pose.orientation);
  50913. } else {
  50914. controllerQuaternion.copy(headObject3D.quaternion);
  50915. }
  50916. controllerEuler.setFromQuaternion(controllerQuaternion);
  50917. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  50918. deltaControllerPosition.applyEuler(controllerEuler);
  50919. // Apply rotated offset to position.
  50920. controllerPosition.add(deltaControllerPosition);
  50921. },
  50922. /**
  50923. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  50924. */
  50925. updatePose: function () {
  50926. var controller = this.controller;
  50927. var data = this.data;
  50928. var object3D = this.el.object3D;
  50929. var pose;
  50930. var vrDisplay = this.system.vrDisplay;
  50931. var standingMatrix;
  50932. if (!controller) { return; }
  50933. // Compose pose from Gamepad.
  50934. pose = controller.pose;
  50935. if (pose.position) {
  50936. object3D.position.fromArray(pose.position);
  50937. } else {
  50938. // Controller not 6DOF, apply arm model.
  50939. if (data.armModel) { this.applyArmModel(object3D.position); }
  50940. }
  50941. if (pose.orientation) {
  50942. object3D.quaternion.fromArray(pose.orientation);
  50943. }
  50944. // Apply transforms, if 6DOF and in VR.
  50945. if (vrDisplay && pose.position) {
  50946. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  50947. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  50948. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  50949. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  50950. }
  50951. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  50952. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  50953. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  50954. },
  50955. /**
  50956. * Handle button changes including axes, presses, touches, values.
  50957. */
  50958. updateButtons: function () {
  50959. var buttonState;
  50960. var controller = this.controller;
  50961. var id;
  50962. if (!controller) { return; }
  50963. // Check every button.
  50964. for (id = 0; id < controller.buttons.length; ++id) {
  50965. // Initialize button state.
  50966. if (!this.buttonStates[id]) {
  50967. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  50968. }
  50969. if (!this.buttonEventDetails[id]) {
  50970. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  50971. }
  50972. buttonState = controller.buttons[id];
  50973. this.handleButton(id, buttonState);
  50974. }
  50975. // Check axes.
  50976. this.handleAxes();
  50977. },
  50978. /**
  50979. * Handle presses and touches for a single button.
  50980. *
  50981. * @param {number} id - Index of button in Gamepad button array.
  50982. * @param {number} buttonState - Value of button state from 0 to 1.
  50983. * @returns {boolean} Whether button has changed in any way.
  50984. */
  50985. handleButton: function (id, buttonState) {
  50986. var changed;
  50987. changed = this.handlePress(id, buttonState) |
  50988. this.handleTouch(id, buttonState) |
  50989. this.handleValue(id, buttonState);
  50990. if (!changed) { return false; }
  50991. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  50992. return true;
  50993. },
  50994. /**
  50995. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  50996. * Compare each component of the axis to the previous value to determine change.
  50997. *
  50998. * @returns {boolean} Whether axes changed.
  50999. */
  51000. handleAxes: function () {
  51001. var changed = false;
  51002. var controllerAxes = this.controller.axes;
  51003. var i;
  51004. var previousAxis = this.axis;
  51005. var changedAxes = this.changedAxes;
  51006. // Check if axis changed.
  51007. this.changedAxes.splice(0, this.changedAxes.length);
  51008. for (i = 0; i < controllerAxes.length; ++i) {
  51009. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  51010. if (changedAxes[i]) { changed = true; }
  51011. }
  51012. if (!changed) { return false; }
  51013. this.axis.splice(0, this.axis.length);
  51014. for (i = 0; i < controllerAxes.length; i++) {
  51015. this.axis.push(controllerAxes[i]);
  51016. }
  51017. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  51018. return true;
  51019. },
  51020. /**
  51021. * Determine whether a button press has occured and emit events as appropriate.
  51022. *
  51023. * @param {string} id - ID of the button to check.
  51024. * @param {object} buttonState - State of the button to check.
  51025. * @returns {boolean} Whether button press state changed.
  51026. */
  51027. handlePress: function (id, buttonState) {
  51028. var evtName;
  51029. var previousButtonState = this.buttonStates[id];
  51030. // Not changed.
  51031. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  51032. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  51033. this.el.emit(evtName, this.buttonEventDetails[id], false);
  51034. previousButtonState.pressed = buttonState.pressed;
  51035. return true;
  51036. },
  51037. /**
  51038. * Determine whether a button touch has occured and emit events as appropriate.
  51039. *
  51040. * @param {string} id - ID of the button to check.
  51041. * @param {object} buttonState - State of the button to check.
  51042. * @returns {boolean} Whether button touch state changed.
  51043. */
  51044. handleTouch: function (id, buttonState) {
  51045. var evtName;
  51046. var previousButtonState = this.buttonStates[id];
  51047. // Not changed.
  51048. if (buttonState.touched === previousButtonState.touched) { return false; }
  51049. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  51050. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  51051. previousButtonState.touched = buttonState.touched;
  51052. return true;
  51053. },
  51054. /**
  51055. * Determine whether a button value has changed.
  51056. *
  51057. * @param {string} id - Id of the button to check.
  51058. * @param {object} buttonState - State of the button to check.
  51059. * @returns {boolean} Whether button value changed.
  51060. */
  51061. handleValue: function (id, buttonState) {
  51062. var previousButtonState = this.buttonStates[id];
  51063. // Not changed.
  51064. if (buttonState.value === previousButtonState.value) { return false; }
  51065. previousButtonState.value = buttonState.value;
  51066. return true;
  51067. }
  51068. });
  51069. },{"../constants":121,"../core/component":129,"../lib/three":177,"../utils/tracked-controls":211}],113:[function(_dereq_,module,exports){
  51070. var controllerUtils = _dereq_('../utils/tracked-controls');
  51071. var registerComponent = _dereq_('../core/component').registerComponent;
  51072. var EVENTS = {
  51073. AXISMOVE: 'axismove',
  51074. BUTTONCHANGED: 'buttonchanged',
  51075. BUTTONDOWN: 'buttondown',
  51076. BUTTONUP: 'buttonup',
  51077. TOUCHSTART: 'touchstart',
  51078. TOUCHEND: 'touchend'
  51079. };
  51080. module.exports.Component = registerComponent('tracked-controls-webxr', {
  51081. schema: {
  51082. id: {type: 'string', default: ''},
  51083. hand: {type: 'string', default: ''},
  51084. handTrackingEnabled: {default: false},
  51085. index: {type: 'int', default: -1},
  51086. iterateControllerProfiles: {default: false}
  51087. },
  51088. init: function () {
  51089. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  51090. this.updateController = this.updateController.bind(this);
  51091. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  51092. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  51093. this.selectEventDetails = {id: 'trigger', state: {pressed: false}};
  51094. this.buttonEventDetails = {};
  51095. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  51096. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  51097. this.changedAxes = [];
  51098. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  51099. },
  51100. update: function () {
  51101. this.updateController();
  51102. },
  51103. play: function () {
  51104. var sceneEl = this.el.sceneEl;
  51105. this.updateController();
  51106. this.addSessionEventListeners();
  51107. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  51108. sceneEl.addEventListener('controllersupdated', this.updateController);
  51109. },
  51110. pause: function () {
  51111. var sceneEl = this.el.sceneEl;
  51112. this.removeSessionEventListeners();
  51113. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  51114. sceneEl.removeEventListener('controllersupdated', this.updateController);
  51115. },
  51116. addSessionEventListeners: function () {
  51117. var sceneEl = this.el.sceneEl;
  51118. if (!sceneEl.xrSession) { return; }
  51119. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  51120. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  51121. },
  51122. removeSessionEventListeners: function () {
  51123. var sceneEl = this.el.sceneEl;
  51124. if (!sceneEl.xrSession) { return; }
  51125. sceneEl.xrSession.removeEventListener('selectstart', this.emitButtonDownEvent);
  51126. sceneEl.xrSession.removeEventListener('selectend', this.emitButtonUpEvent);
  51127. },
  51128. isControllerPresent: function (evt) {
  51129. if (!this.controller || this.controller.gamepad) { return false; }
  51130. if (evt.inputSource.handedness !== 'none' &&
  51131. evt.inputSource.handedness !== this.data.hand) {
  51132. return false;
  51133. }
  51134. return true;
  51135. },
  51136. emitButtonDownEvent: function (evt) {
  51137. if (!this.isControllerPresent(evt)) { return; }
  51138. this.selectEventDetails.state.pressed = true;
  51139. this.el.emit('buttondown', this.selectEventDetails);
  51140. this.el.emit('buttonchanged', this.selectEventDetails);
  51141. this.el.emit('triggerdown');
  51142. },
  51143. emitButtonUpEvent: function (evt) {
  51144. if (!this.isControllerPresent(evt)) { return; }
  51145. this.selectEventDetails.state.pressed = false;
  51146. this.el.emit('buttonup', this.selectEventDetails);
  51147. this.el.emit('buttonchanged', this.selectEventDetails);
  51148. this.el.emit('triggerup');
  51149. },
  51150. /**
  51151. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  51152. */
  51153. updateController: function () {
  51154. this.controller = controllerUtils.findMatchingControllerWebXR(
  51155. this.system.controllers,
  51156. this.data.id,
  51157. this.data.hand,
  51158. this.data.index,
  51159. this.data.iterateControllerProfiles,
  51160. this.data.handTrackingEnabled
  51161. );
  51162. // Legacy handle to the controller for old components.
  51163. this.el.components['tracked-controls'].controller = this.controller;
  51164. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  51165. },
  51166. tick: function () {
  51167. var sceneEl = this.el.sceneEl;
  51168. var controller = this.controller;
  51169. var frame = sceneEl.frame;
  51170. if (!controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  51171. if (!controller.hand) {
  51172. this.pose = frame.getPose(controller.targetRaySpace, this.system.referenceSpace);
  51173. this.updatePose();
  51174. this.updateButtons();
  51175. }
  51176. },
  51177. updatePose: function () {
  51178. var object3D = this.el.object3D;
  51179. var pose = this.pose;
  51180. if (!pose) { return; }
  51181. object3D.matrix.elements = pose.transform.matrix;
  51182. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  51183. },
  51184. /**
  51185. * Handle button changes including axes, presses, touches, values.
  51186. */
  51187. updateButtons: function () {
  51188. var buttonState;
  51189. var id;
  51190. var controller = this.controller;
  51191. var gamepad;
  51192. if (!controller || !controller.gamepad) { return; }
  51193. gamepad = controller.gamepad;
  51194. // Check every button.
  51195. for (id = 0; id < gamepad.buttons.length; ++id) {
  51196. // Initialize button state.
  51197. if (!this.buttonStates[id]) {
  51198. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  51199. }
  51200. if (!this.buttonEventDetails[id]) {
  51201. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  51202. }
  51203. buttonState = gamepad.buttons[id];
  51204. this.handleButton(id, buttonState);
  51205. }
  51206. // Check axes.
  51207. this.handleAxes();
  51208. },
  51209. /**
  51210. * Handle presses and touches for a single button.
  51211. *
  51212. * @param {number} id - Index of button in Gamepad button array.
  51213. * @param {number} buttonState - Value of button state from 0 to 1.
  51214. * @returns {boolean} Whether button has changed in any way.
  51215. */
  51216. handleButton: function (id, buttonState) {
  51217. var changed;
  51218. changed = this.handlePress(id, buttonState) |
  51219. this.handleTouch(id, buttonState) |
  51220. this.handleValue(id, buttonState);
  51221. if (!changed) { return false; }
  51222. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  51223. return true;
  51224. },
  51225. /**
  51226. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  51227. * Compare each component of the axis to the previous value to determine change.
  51228. *
  51229. * @returns {boolean} Whether axes changed.
  51230. */
  51231. handleAxes: function () {
  51232. var changed = false;
  51233. var controllerAxes = this.controller.gamepad.axes;
  51234. var i;
  51235. var previousAxis = this.axis;
  51236. var changedAxes = this.changedAxes;
  51237. // Check if axis changed.
  51238. this.changedAxes.splice(0, this.changedAxes.length);
  51239. for (i = 0; i < controllerAxes.length; ++i) {
  51240. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  51241. if (changedAxes[i]) { changed = true; }
  51242. }
  51243. if (!changed) { return false; }
  51244. this.axis.splice(0, this.axis.length);
  51245. for (i = 0; i < controllerAxes.length; i++) {
  51246. this.axis.push(controllerAxes[i]);
  51247. }
  51248. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  51249. return true;
  51250. },
  51251. /**
  51252. * Determine whether a button press has occured and emit events as appropriate.
  51253. *
  51254. * @param {string} id - ID of the button to check.
  51255. * @param {object} buttonState - State of the button to check.
  51256. * @returns {boolean} Whether button press state changed.
  51257. */
  51258. handlePress: function (id, buttonState) {
  51259. var evtName;
  51260. var previousButtonState = this.buttonStates[id];
  51261. // Not changed.
  51262. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  51263. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  51264. this.el.emit(evtName, this.buttonEventDetails[id], false);
  51265. previousButtonState.pressed = buttonState.pressed;
  51266. return true;
  51267. },
  51268. /**
  51269. * Determine whether a button touch has occured and emit events as appropriate.
  51270. *
  51271. * @param {string} id - ID of the button to check.
  51272. * @param {object} buttonState - State of the button to check.
  51273. * @returns {boolean} Whether button touch state changed.
  51274. */
  51275. handleTouch: function (id, buttonState) {
  51276. var evtName;
  51277. var previousButtonState = this.buttonStates[id];
  51278. // Not changed.
  51279. if (buttonState.touched === previousButtonState.touched) { return false; }
  51280. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  51281. this.el.emit(evtName, this.buttonEventDetails[id], false);
  51282. previousButtonState.touched = buttonState.touched;
  51283. return true;
  51284. },
  51285. /**
  51286. * Determine whether a button value has changed.
  51287. *
  51288. * @param {string} id - Id of the button to check.
  51289. * @param {object} buttonState - State of the button to check.
  51290. * @returns {boolean} Whether button value changed.
  51291. */
  51292. handleValue: function (id, buttonState) {
  51293. var previousButtonState = this.buttonStates[id];
  51294. // Not changed.
  51295. if (buttonState.value === previousButtonState.value) { return false; }
  51296. previousButtonState.value = buttonState.value;
  51297. return true;
  51298. }
  51299. });
  51300. },{"../core/component":129,"../utils/tracked-controls":211}],114:[function(_dereq_,module,exports){
  51301. var registerComponent = _dereq_('../core/component').registerComponent;
  51302. /**
  51303. * Tracked controls.
  51304. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  51305. *
  51306. * @property {number} controller - Index of controller in array returned by Gamepad API.
  51307. * Only used if hand property is not set.
  51308. * @property {string} id - Selected controller among those returned by Gamepad API.
  51309. * @property {number} hand - If multiple controllers found with id, choose the one with the
  51310. * given value for hand. If set, we ignore 'controller' property
  51311. */
  51312. module.exports.Component = registerComponent('tracked-controls', {
  51313. schema: {
  51314. autoHide: {default: true},
  51315. controller: {default: -1},
  51316. id: {type: 'string', default: ''},
  51317. hand: {type: 'string', default: ''},
  51318. idPrefix: {type: 'string', default: ''},
  51319. handTrackingEnabled: {default: false},
  51320. orientationOffset: {type: 'vec3'},
  51321. // Arm model parameters when not 6DoF.
  51322. armModel: {default: false},
  51323. headElement: {type: 'selector'},
  51324. iterateControllerProfiles: {default: false}
  51325. },
  51326. update: function () {
  51327. var data = this.data;
  51328. var el = this.el;
  51329. if (el.sceneEl.hasWebXR) {
  51330. el.setAttribute('tracked-controls-webxr', {
  51331. id: data.id,
  51332. hand: data.hand,
  51333. index: data.controller,
  51334. iterateControllerProfiles: data.iterateControllerProfiles,
  51335. handTrackingEnabled: data.handTrackingEnabled
  51336. });
  51337. } else {
  51338. el.setAttribute('tracked-controls-webvr', data);
  51339. }
  51340. }
  51341. });
  51342. },{"../core/component":129}],115:[function(_dereq_,module,exports){
  51343. var registerComponent = _dereq_('../core/component').registerComponent;
  51344. var bind = _dereq_('../utils/bind');
  51345. var THREE = _dereq_('../lib/three');
  51346. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  51347. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  51348. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  51349. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  51350. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve_index_';
  51351. var INDEX_CONTROLLER_MODEL_URL = {
  51352. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  51353. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  51354. };
  51355. var GAMEPAD_ID_PREFIX = 'valve';
  51356. var INDEX_CONTROLLER_POSITION_OFFSET = {
  51357. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  51358. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  51359. };
  51360. var INDEX_CONTROLLER_ROTATION_OFFSET = {
  51361. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  51362. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  51363. };
  51364. /**
  51365. * Vive controls.
  51366. * Interface with Vive controllers and map Gamepad events to controller buttons:
  51367. * trackpad, trigger, grip, menu, system
  51368. * Load a controller model and highlight the pressed buttons.
  51369. */
  51370. module.exports.Component = registerComponent('valve-index-controls', {
  51371. schema: {
  51372. hand: {default: 'left'},
  51373. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  51374. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  51375. model: {default: true},
  51376. orientationOffset: {type: 'vec3'}
  51377. },
  51378. mapping: {
  51379. axes: {trackpad: [0, 1]},
  51380. buttons: [
  51381. 'trigger', 'grip', 'joystick', 'abutton', 'abutton',
  51382. 'system', 'finger1', 'finger2', 'finger3',
  51383. 'finger4', 'finger5']
  51384. },
  51385. init: function () {
  51386. var self = this;
  51387. this.controllerPresent = false;
  51388. this.lastControllerCheck = 0;
  51389. this.onButtonChanged = bind(this.onButtonChanged, this);
  51390. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  51391. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  51392. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  51393. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  51394. this.previousButtonValues = {};
  51395. this.rendererSystem = this.el.sceneEl.systems.renderer;
  51396. this.bindMethods();
  51397. },
  51398. play: function () {
  51399. this.checkIfControllerPresent();
  51400. this.addControllersUpdateListener();
  51401. },
  51402. pause: function () {
  51403. this.removeEventListeners();
  51404. this.removeControllersUpdateListener();
  51405. },
  51406. bindMethods: function () {
  51407. this.onModelLoaded = bind(this.onModelLoaded, this);
  51408. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  51409. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  51410. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  51411. this.onAxisMoved = bind(this.onAxisMoved, this);
  51412. },
  51413. addEventListeners: function () {
  51414. var el = this.el;
  51415. el.addEventListener('buttonchanged', this.onButtonChanged);
  51416. el.addEventListener('buttondown', this.onButtonDown);
  51417. el.addEventListener('buttonup', this.onButtonUp);
  51418. el.addEventListener('touchend', this.onButtonTouchEnd);
  51419. el.addEventListener('touchstart', this.onButtonTouchStart);
  51420. el.addEventListener('model-loaded', this.onModelLoaded);
  51421. el.addEventListener('axismove', this.onAxisMoved);
  51422. this.controllerEventsActive = true;
  51423. },
  51424. removeEventListeners: function () {
  51425. var el = this.el;
  51426. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51427. el.removeEventListener('buttondown', this.onButtonDown);
  51428. el.removeEventListener('buttonup', this.onButtonUp);
  51429. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51430. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51431. el.removeEventListener('model-loaded', this.onModelLoaded);
  51432. el.removeEventListener('axismove', this.onAxisMoved);
  51433. this.controllerEventsActive = false;
  51434. },
  51435. /**
  51436. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  51437. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  51438. { hand: data.hand });
  51439. * Until then, use hardcoded index.
  51440. */
  51441. checkIfControllerPresent: function () {
  51442. var data = this.data;
  51443. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  51444. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  51445. },
  51446. injectTrackedControls: function () {
  51447. var el = this.el;
  51448. var data = this.data;
  51449. // If we have an OpenVR Gamepad, use the fixed mapping.
  51450. el.setAttribute('tracked-controls', {
  51451. idPrefix: GAMEPAD_ID_PREFIX,
  51452. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  51453. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  51454. hand: data.hand,
  51455. orientationOffset: data.orientationOffset
  51456. });
  51457. this.loadModel();
  51458. },
  51459. loadModel: function () {
  51460. var data = this.data;
  51461. if (!data.model) { return; }
  51462. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  51463. },
  51464. addControllersUpdateListener: function () {
  51465. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51466. },
  51467. removeControllersUpdateListener: function () {
  51468. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51469. },
  51470. onControllersUpdate: function () {
  51471. this.checkIfControllerPresent();
  51472. },
  51473. /**
  51474. * Rotate the trigger button based on how hard the trigger is pressed.
  51475. */
  51476. onButtonChanged: function (evt) {
  51477. var button = this.mapping.buttons[evt.detail.id];
  51478. var buttonMeshes = this.buttonMeshes;
  51479. var analogValue;
  51480. if (!button) { return; }
  51481. if (button === 'trigger') {
  51482. analogValue = evt.detail.state.value;
  51483. // Update trigger rotation depending on button value.
  51484. if (buttonMeshes && buttonMeshes.trigger) {
  51485. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  51486. }
  51487. }
  51488. // Pass along changed event with button state, using button mapping for convenience.
  51489. this.el.emit(button + 'changed', evt.detail.state);
  51490. },
  51491. onModelLoaded: function (evt) {
  51492. var buttonMeshes;
  51493. var controllerObject3D = evt.detail.model;
  51494. var self = this;
  51495. if (!this.data.model) { return; }
  51496. // Store button meshes object to be able to change their colors.
  51497. buttonMeshes = this.buttonMeshes = {};
  51498. buttonMeshes.grip = {
  51499. left: controllerObject3D.getObjectByName('leftgrip'),
  51500. right: controllerObject3D.getObjectByName('rightgrip')
  51501. };
  51502. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  51503. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  51504. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  51505. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  51506. // Set default colors.
  51507. Object.keys(buttonMeshes).forEach(function (buttonName) {
  51508. self.setButtonColor(buttonName, self.data.buttonColor);
  51509. });
  51510. // Offset pivot point.
  51511. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  51512. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  51513. this.el.emit('controllermodelready', {
  51514. name: 'valve-index-controlls',
  51515. model: this.data.model,
  51516. rayOrigin: new THREE.Vector3(0, 0, 0)
  51517. });
  51518. },
  51519. onAxisMoved: function (evt) {
  51520. emitIfAxesChanged(this, this.mapping.axes, evt);
  51521. },
  51522. updateModel: function (buttonName, evtName) {
  51523. var color;
  51524. var isTouch;
  51525. if (!this.data.model) { return; }
  51526. isTouch = evtName.indexOf('touch') !== -1;
  51527. // Don't change color for trackpad touch.
  51528. if (isTouch) { return; }
  51529. // Update colors.
  51530. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  51531. this.setButtonColor(buttonName, color);
  51532. },
  51533. setButtonColor: function (buttonName, color) {
  51534. // TODO: The meshes aren't set up correctly now, skipping for the moment
  51535. return;
  51536. }
  51537. });
  51538. },{"../core/component":129,"../lib/three":177,"../utils/bind":197,"../utils/tracked-controls":211}],116:[function(_dereq_,module,exports){
  51539. var registerComponent = _dereq_('../core/component').registerComponent;
  51540. /**
  51541. * Visibility component.
  51542. */
  51543. module.exports.Component = registerComponent('visible', {
  51544. schema: {default: true},
  51545. update: function () {
  51546. this.el.object3D.visible = this.data;
  51547. }
  51548. });
  51549. },{"../core/component":129}],117:[function(_dereq_,module,exports){
  51550. var registerComponent = _dereq_('../core/component').registerComponent;
  51551. var bind = _dereq_('../utils/bind');
  51552. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  51553. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  51554. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  51555. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  51556. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  51557. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  51558. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  51559. var GAMEPAD_ID_WEBXR = 'htc-vive-controller-mv';
  51560. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  51561. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  51562. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  51563. /**
  51564. * Button IDs:
  51565. * 0 - trackpad
  51566. * 1 - trigger (intensity value from 0.5 to 1)
  51567. * 2 - grip
  51568. * 3 - menu (dispatch but better for menu options)
  51569. * 4 - system (never dispatched on this layer)
  51570. */
  51571. var INPUT_MAPPING_WEBVR = {
  51572. axes: {trackpad: [0, 1]},
  51573. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  51574. };
  51575. /**
  51576. * Button IDs:
  51577. * 0 - trigger
  51578. * 1 - squeeze
  51579. * 2 - touchpad
  51580. * 3 - none (dispatch but better for menu options)
  51581. * 4 - menu (never dispatched on this layer)
  51582. *
  51583. * Axis:
  51584. * 0 - touchpad x axis
  51585. * 1 - touchpad y axis
  51586. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  51587. */
  51588. var INPUT_MAPPING_WEBXR = {
  51589. axes: {thumbstick: [0, 1]},
  51590. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  51591. };
  51592. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  51593. /**
  51594. * Vive controls.
  51595. * Interface with Vive controllers and map Gamepad events to controller buttons:
  51596. * trackpad, trigger, grip, menu, system
  51597. * Load a controller model and highlight the pressed buttons.
  51598. */
  51599. module.exports.Component = registerComponent('vive-controls', {
  51600. schema: {
  51601. hand: {default: 'left'},
  51602. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  51603. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  51604. model: {default: true},
  51605. orientationOffset: {type: 'vec3'}
  51606. },
  51607. mapping: INPUT_MAPPING,
  51608. init: function () {
  51609. var self = this;
  51610. this.controllerPresent = false;
  51611. this.lastControllerCheck = 0;
  51612. this.onButtonChanged = bind(this.onButtonChanged, this);
  51613. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  51614. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  51615. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  51616. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  51617. this.previousButtonValues = {};
  51618. this.rendererSystem = this.el.sceneEl.systems.renderer;
  51619. this.bindMethods();
  51620. },
  51621. update: function () {
  51622. var data = this.data;
  51623. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  51624. },
  51625. play: function () {
  51626. this.checkIfControllerPresent();
  51627. this.addControllersUpdateListener();
  51628. },
  51629. pause: function () {
  51630. this.removeEventListeners();
  51631. this.removeControllersUpdateListener();
  51632. },
  51633. bindMethods: function () {
  51634. this.onModelLoaded = bind(this.onModelLoaded, this);
  51635. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  51636. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  51637. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  51638. this.onAxisMoved = bind(this.onAxisMoved, this);
  51639. },
  51640. addEventListeners: function () {
  51641. var el = this.el;
  51642. el.addEventListener('buttonchanged', this.onButtonChanged);
  51643. el.addEventListener('buttondown', this.onButtonDown);
  51644. el.addEventListener('buttonup', this.onButtonUp);
  51645. el.addEventListener('touchend', this.onButtonTouchEnd);
  51646. el.addEventListener('touchstart', this.onButtonTouchStart);
  51647. el.addEventListener('model-loaded', this.onModelLoaded);
  51648. el.addEventListener('axismove', this.onAxisMoved);
  51649. this.controllerEventsActive = true;
  51650. },
  51651. removeEventListeners: function () {
  51652. var el = this.el;
  51653. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51654. el.removeEventListener('buttondown', this.onButtonDown);
  51655. el.removeEventListener('buttonup', this.onButtonUp);
  51656. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51657. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51658. el.removeEventListener('model-loaded', this.onModelLoaded);
  51659. el.removeEventListener('axismove', this.onAxisMoved);
  51660. this.controllerEventsActive = false;
  51661. },
  51662. /**
  51663. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  51664. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  51665. { hand: data.hand });
  51666. * Until then, use hardcoded index.
  51667. */
  51668. checkIfControllerPresent: function () {
  51669. var data = this.data;
  51670. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  51671. },
  51672. injectTrackedControls: function () {
  51673. var el = this.el;
  51674. var data = this.data;
  51675. // If we have an OpenVR Gamepad, use the fixed mapping.
  51676. el.setAttribute('tracked-controls', {
  51677. idPrefix: GAMEPAD_ID_PREFIX,
  51678. hand: data.hand,
  51679. controller: this.controllerIndex,
  51680. orientationOffset: data.orientationOffset
  51681. });
  51682. // Load model.
  51683. if (!this.data.model) { return; }
  51684. this.el.setAttribute('obj-model', {
  51685. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  51686. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  51687. });
  51688. },
  51689. addControllersUpdateListener: function () {
  51690. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51691. },
  51692. removeControllersUpdateListener: function () {
  51693. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51694. },
  51695. onControllersUpdate: function () {
  51696. this.checkIfControllerPresent();
  51697. },
  51698. /**
  51699. * Rotate the trigger button based on how hard the trigger is pressed.
  51700. */
  51701. onButtonChanged: function (evt) {
  51702. var button = this.mapping.buttons[evt.detail.id];
  51703. var buttonMeshes = this.buttonMeshes;
  51704. var analogValue;
  51705. if (!button) { return; }
  51706. if (button === 'trigger') {
  51707. analogValue = evt.detail.state.value;
  51708. // Update trigger rotation depending on button value.
  51709. if (buttonMeshes && buttonMeshes.trigger) {
  51710. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  51711. }
  51712. }
  51713. // Pass along changed event with button state, using button mapping for convenience.
  51714. this.el.emit(button + 'changed', evt.detail.state);
  51715. },
  51716. onModelLoaded: function (evt) {
  51717. var buttonMeshes;
  51718. var controllerObject3D = evt.detail.model;
  51719. var self = this;
  51720. if (!this.data.model) { return; }
  51721. // Store button meshes object to be able to change their colors.
  51722. buttonMeshes = this.buttonMeshes = {};
  51723. buttonMeshes.grip = {
  51724. left: controllerObject3D.getObjectByName('leftgrip'),
  51725. right: controllerObject3D.getObjectByName('rightgrip')
  51726. };
  51727. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  51728. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  51729. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  51730. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  51731. // Set default colors.
  51732. Object.keys(buttonMeshes).forEach(function (buttonName) {
  51733. self.setButtonColor(buttonName, self.data.buttonColor);
  51734. });
  51735. // Offset pivot point.
  51736. controllerObject3D.position.set(0, -0.015, 0.04);
  51737. },
  51738. onAxisMoved: function (evt) {
  51739. emitIfAxesChanged(this, this.mapping.axes, evt);
  51740. },
  51741. updateModel: function (buttonName, evtName) {
  51742. var color;
  51743. var isTouch;
  51744. if (!this.data.model) { return; }
  51745. isTouch = evtName.indexOf('touch') !== -1;
  51746. // Don't change color for trackpad touch.
  51747. if (isTouch) { return; }
  51748. // Update colors.
  51749. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  51750. this.setButtonColor(buttonName, color);
  51751. },
  51752. setButtonColor: function (buttonName, color) {
  51753. var buttonMeshes = this.buttonMeshes;
  51754. var rendererSystem = this.rendererSystem;
  51755. if (!buttonMeshes) { return; }
  51756. // Need to do both left and right sides for grip.
  51757. if (buttonName === 'grip') {
  51758. buttonMeshes.grip.left.material.color.set(color);
  51759. buttonMeshes.grip.right.material.color.set(color);
  51760. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  51761. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  51762. return;
  51763. }
  51764. buttonMeshes[buttonName].material.color.set(color);
  51765. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  51766. }
  51767. });
  51768. },{"../core/component":129,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],118:[function(_dereq_,module,exports){
  51769. var registerComponent = _dereq_('../core/component').registerComponent;
  51770. var bind = _dereq_('../utils/bind');
  51771. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  51772. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  51773. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  51774. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  51775. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  51776. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  51777. /**
  51778. * Vive Focus controls.
  51779. * Interface with Vive Focus controller and map Gamepad events to
  51780. * controller buttons: trackpad, trigger
  51781. * Load a controller model and highlight the pressed buttons.
  51782. */
  51783. module.exports.Component = registerComponent('vive-focus-controls', {
  51784. schema: {
  51785. hand: {default: ''}, // This informs the degenerate arm model.
  51786. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  51787. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  51788. model: {default: true},
  51789. orientationOffset: {type: 'vec3'},
  51790. armModel: {default: true}
  51791. },
  51792. /**
  51793. * Button IDs:
  51794. * 0 - trackpad
  51795. * 1 - trigger
  51796. */
  51797. mapping: {
  51798. axes: {trackpad: [0, 1]},
  51799. buttons: ['trackpad', 'trigger']
  51800. },
  51801. bindMethods: function () {
  51802. this.onModelLoaded = bind(this.onModelLoaded, this);
  51803. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  51804. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  51805. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  51806. this.onAxisMoved = bind(this.onAxisMoved, this);
  51807. },
  51808. init: function () {
  51809. var self = this;
  51810. this.onButtonChanged = bind(this.onButtonChanged, this);
  51811. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  51812. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  51813. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  51814. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  51815. this.controllerPresent = false;
  51816. this.lastControllerCheck = 0;
  51817. this.bindMethods();
  51818. },
  51819. addEventListeners: function () {
  51820. var el = this.el;
  51821. el.addEventListener('buttonchanged', this.onButtonChanged);
  51822. el.addEventListener('buttondown', this.onButtonDown);
  51823. el.addEventListener('buttonup', this.onButtonUp);
  51824. el.addEventListener('touchstart', this.onButtonTouchStart);
  51825. el.addEventListener('touchend', this.onButtonTouchEnd);
  51826. el.addEventListener('model-loaded', this.onModelLoaded);
  51827. el.addEventListener('axismove', this.onAxisMoved);
  51828. this.controllerEventsActive = true;
  51829. this.addControllersUpdateListener();
  51830. },
  51831. removeEventListeners: function () {
  51832. var el = this.el;
  51833. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51834. el.removeEventListener('buttondown', this.onButtonDown);
  51835. el.removeEventListener('buttonup', this.onButtonUp);
  51836. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51837. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51838. el.removeEventListener('model-loaded', this.onModelLoaded);
  51839. el.removeEventListener('axismove', this.onAxisMoved);
  51840. this.controllerEventsActive = false;
  51841. this.removeControllersUpdateListener();
  51842. },
  51843. checkIfControllerPresent: function () {
  51844. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  51845. this.data.hand ? {hand: this.data.hand} : {});
  51846. },
  51847. play: function () {
  51848. this.checkIfControllerPresent();
  51849. this.addControllersUpdateListener();
  51850. },
  51851. pause: function () {
  51852. this.removeEventListeners();
  51853. this.removeControllersUpdateListener();
  51854. },
  51855. injectTrackedControls: function () {
  51856. var el = this.el;
  51857. var data = this.data;
  51858. el.setAttribute('tracked-controls', {
  51859. armModel: data.armModel,
  51860. idPrefix: GAMEPAD_ID_PREFIX,
  51861. orientationOffset: data.orientationOffset
  51862. });
  51863. if (!this.data.model) { return; }
  51864. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  51865. },
  51866. addControllersUpdateListener: function () {
  51867. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51868. },
  51869. removeControllersUpdateListener: function () {
  51870. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51871. },
  51872. onControllersUpdate: function () {
  51873. this.checkIfControllerPresent();
  51874. },
  51875. onModelLoaded: function (evt) {
  51876. var controllerObject3D = evt.detail.model;
  51877. var buttonMeshes;
  51878. if (!this.data.model) { return; }
  51879. buttonMeshes = this.buttonMeshes = {};
  51880. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  51881. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  51882. if (buttonMeshes.triggerPressed) {
  51883. buttonMeshes.triggerPressed.visible = false;
  51884. }
  51885. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  51886. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  51887. if (buttonMeshes.trackpadPressed) {
  51888. buttonMeshes.trackpadPressed.visible = false;
  51889. }
  51890. },
  51891. // No analog buttons, only emits 0/1 values
  51892. onButtonChanged: function (evt) {
  51893. var button = this.mapping.buttons[evt.detail.id];
  51894. if (!button) return;
  51895. // Pass along changed event with button state, using button mapping for convenience.
  51896. this.el.emit(button + 'changed', evt.detail.state);
  51897. },
  51898. onAxisMoved: function (evt) {
  51899. emitIfAxesChanged(this, this.mapping.axes, evt);
  51900. },
  51901. updateModel: function (buttonName, evtName) {
  51902. if (!this.data.model) { return; }
  51903. this.updateButtonModel(buttonName, evtName);
  51904. },
  51905. updateButtonModel: function (buttonName, state) {
  51906. var buttonMeshes = this.buttonMeshes;
  51907. var pressedName = buttonName + 'Pressed';
  51908. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  51909. return;
  51910. }
  51911. var color;
  51912. switch (state) {
  51913. case 'down':
  51914. color = this.data.buttonHighlightColor;
  51915. break;
  51916. case 'touchstart':
  51917. color = this.data.buttonTouchedColor;
  51918. break;
  51919. }
  51920. if (color) {
  51921. buttonMeshes[pressedName].material.color.set(color);
  51922. }
  51923. buttonMeshes[pressedName].visible = !!color;
  51924. buttonMeshes[buttonName].visible = !color;
  51925. }
  51926. });
  51927. },{"../core/component":129,"../utils/bind":197,"../utils/tracked-controls":211}],119:[function(_dereq_,module,exports){
  51928. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  51929. var registerComponent = _dereq_('../core/component').registerComponent;
  51930. var THREE = _dereq_('../lib/three');
  51931. var utils = _dereq_('../utils/');
  51932. var bind = utils.bind;
  51933. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  51934. var CLAMP_VELOCITY = 0.00001;
  51935. var MAX_DELTA = 0.2;
  51936. var KEYS = [
  51937. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  51938. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  51939. ];
  51940. /**
  51941. * WASD component to control entities using WASD keys.
  51942. */
  51943. module.exports.Component = registerComponent('wasd-controls', {
  51944. schema: {
  51945. acceleration: {default: 65},
  51946. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  51947. adEnabled: {default: true},
  51948. adInverted: {default: false},
  51949. enabled: {default: true},
  51950. fly: {default: false},
  51951. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  51952. wsEnabled: {default: true},
  51953. wsInverted: {default: false}
  51954. },
  51955. init: function () {
  51956. // To keep track of the pressed keys.
  51957. this.keys = {};
  51958. this.easing = 1.1;
  51959. this.velocity = new THREE.Vector3();
  51960. // Bind methods and add event listeners.
  51961. this.onBlur = bind(this.onBlur, this);
  51962. this.onFocus = bind(this.onFocus, this);
  51963. this.onKeyDown = bind(this.onKeyDown, this);
  51964. this.onKeyUp = bind(this.onKeyUp, this);
  51965. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  51966. this.attachVisibilityEventListeners();
  51967. },
  51968. tick: function (time, delta) {
  51969. var data = this.data;
  51970. var el = this.el;
  51971. var velocity = this.velocity;
  51972. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  51973. isEmptyObject(this.keys)) { return; }
  51974. // Update velocity.
  51975. delta = delta / 1000;
  51976. this.updateVelocity(delta);
  51977. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  51978. // Get movement vector and translate position.
  51979. el.object3D.position.add(this.getMovementVector(delta));
  51980. },
  51981. remove: function () {
  51982. this.removeKeyEventListeners();
  51983. this.removeVisibilityEventListeners();
  51984. },
  51985. play: function () {
  51986. this.attachKeyEventListeners();
  51987. },
  51988. pause: function () {
  51989. this.keys = {};
  51990. this.removeKeyEventListeners();
  51991. },
  51992. updateVelocity: function (delta) {
  51993. var acceleration;
  51994. var adAxis;
  51995. var adSign;
  51996. var data = this.data;
  51997. var keys = this.keys;
  51998. var velocity = this.velocity;
  51999. var wsAxis;
  52000. var wsSign;
  52001. adAxis = data.adAxis;
  52002. wsAxis = data.wsAxis;
  52003. // If FPS too low, reset velocity.
  52004. if (delta > MAX_DELTA) {
  52005. velocity[adAxis] = 0;
  52006. velocity[wsAxis] = 0;
  52007. return;
  52008. }
  52009. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  52010. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  52011. // Velocity Easing.
  52012. if (velocity[adAxis] !== 0) {
  52013. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  52014. }
  52015. if (velocity[wsAxis] !== 0) {
  52016. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  52017. }
  52018. // Clamp velocity easing.
  52019. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  52020. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  52021. if (!data.enabled) { return; }
  52022. // Update velocity using keys pressed.
  52023. acceleration = data.acceleration;
  52024. if (data.adEnabled) {
  52025. adSign = data.adInverted ? -1 : 1;
  52026. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  52027. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  52028. }
  52029. if (data.wsEnabled) {
  52030. wsSign = data.wsInverted ? -1 : 1;
  52031. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  52032. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  52033. }
  52034. },
  52035. getMovementVector: (function () {
  52036. var directionVector = new THREE.Vector3(0, 0, 0);
  52037. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  52038. return function (delta) {
  52039. var rotation = this.el.getAttribute('rotation');
  52040. var velocity = this.velocity;
  52041. var xRotation;
  52042. directionVector.copy(velocity);
  52043. directionVector.multiplyScalar(delta);
  52044. // Absolute.
  52045. if (!rotation) { return directionVector; }
  52046. xRotation = this.data.fly ? rotation.x : 0;
  52047. // Transform direction relative to heading.
  52048. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  52049. directionVector.applyEuler(rotationEuler);
  52050. return directionVector;
  52051. };
  52052. })(),
  52053. attachVisibilityEventListeners: function () {
  52054. window.addEventListener('blur', this.onBlur);
  52055. window.addEventListener('focus', this.onFocus);
  52056. document.addEventListener('visibilitychange', this.onVisibilityChange);
  52057. },
  52058. removeVisibilityEventListeners: function () {
  52059. window.removeEventListener('blur', this.onBlur);
  52060. window.removeEventListener('focus', this.onFocus);
  52061. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  52062. },
  52063. attachKeyEventListeners: function () {
  52064. window.addEventListener('keydown', this.onKeyDown);
  52065. window.addEventListener('keyup', this.onKeyUp);
  52066. },
  52067. removeKeyEventListeners: function () {
  52068. window.removeEventListener('keydown', this.onKeyDown);
  52069. window.removeEventListener('keyup', this.onKeyUp);
  52070. },
  52071. onBlur: function () {
  52072. this.pause();
  52073. },
  52074. onFocus: function () {
  52075. this.play();
  52076. },
  52077. onVisibilityChange: function () {
  52078. if (document.hidden) {
  52079. this.onBlur();
  52080. } else {
  52081. this.onFocus();
  52082. }
  52083. },
  52084. onKeyDown: function (event) {
  52085. var code;
  52086. if (!shouldCaptureKeyEvent(event)) { return; }
  52087. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  52088. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  52089. },
  52090. onKeyUp: function (event) {
  52091. var code;
  52092. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  52093. delete this.keys[code];
  52094. }
  52095. });
  52096. function isEmptyObject (keys) {
  52097. var key;
  52098. for (key in keys) { return false; }
  52099. return true;
  52100. }
  52101. },{"../constants":121,"../core/component":129,"../lib/three":177,"../utils/":203}],120:[function(_dereq_,module,exports){
  52102. /* global THREE */
  52103. var registerComponent = _dereq_('../core/component').registerComponent;
  52104. var bind = _dereq_('../utils/bind');
  52105. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  52106. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52107. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52108. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52109. var utils = _dereq_('../utils/');
  52110. var debug = utils.debug('components:windows-motion-controls:debug');
  52111. var warn = utils.debug('components:windows-motion-controls:warn');
  52112. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  52113. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  52114. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  52115. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  52116. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  52117. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  52118. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  52119. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  52120. var INPUT_MAPPING_WEBVR = {
  52121. // A-Frame specific semantic axis names
  52122. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  52123. // A-Frame specific semantic button names
  52124. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52125. // A mapping of the semantic name to node name in the glTF model file,
  52126. // that should be transformed by axis value.
  52127. // This array mirrors the browser Gamepad.axes array, such that
  52128. // the mesh corresponding to axis 0 is in this array index 0.
  52129. axisMeshNames: [
  52130. 'THUMBSTICK_X',
  52131. 'THUMBSTICK_Y',
  52132. 'TOUCHPAD_TOUCH_X',
  52133. 'TOUCHPAD_TOUCH_Y'
  52134. ],
  52135. // A mapping of the semantic name to button node name in the glTF model file,
  52136. // that should be transformed by button value.
  52137. buttonMeshNames: {
  52138. 'trigger': 'SELECT',
  52139. 'menu': 'MENU',
  52140. 'grip': 'GRASP',
  52141. 'thumbstick': 'THUMBSTICK_PRESS',
  52142. 'trackpad': 'TOUCHPAD_PRESS'
  52143. },
  52144. pointingPoseMeshName: 'POINTING_POSE'
  52145. };
  52146. var INPUT_MAPPING_WEBXR = {
  52147. // A-Frame specific semantic axis names
  52148. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  52149. // A-Frame specific semantic button names
  52150. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  52151. // A mapping of the semantic name to node name in the glTF model file,
  52152. // that should be transformed by axis value.
  52153. // This array mirrors the browser Gamepad.axes array, such that
  52154. // the mesh corresponding to axis 0 is in this array index 0.
  52155. axisMeshNames: [
  52156. 'TOUCHPAD_TOUCH_X',
  52157. 'TOUCHPAD_TOUCH_X',
  52158. 'THUMBSTICK_X',
  52159. 'THUMBSTICK_Y'
  52160. ],
  52161. // A mapping of the semantic name to button node name in the glTF model file,
  52162. // that should be transformed by button value.
  52163. buttonMeshNames: {
  52164. 'trigger': 'SELECT',
  52165. 'menu': 'MENU',
  52166. 'squeeze': 'GRASP',
  52167. 'thumbstick': 'THUMBSTICK_PRESS',
  52168. 'touchpad': 'TOUCHPAD_PRESS'
  52169. },
  52170. pointingPoseMeshName: 'POINTING_POSE'
  52171. };
  52172. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  52173. /**
  52174. * Windows Motion Controller controls.
  52175. * Interface with Windows Motion Controller controllers and map Gamepad events to
  52176. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  52177. * Load a controller model and transform the pressed buttons.
  52178. */
  52179. module.exports.Component = registerComponent('windows-motion-controls', {
  52180. schema: {
  52181. hand: {default: DEFAULT_HANDEDNESS},
  52182. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  52183. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  52184. pair: {default: 0},
  52185. // If true, loads the controller glTF asset.
  52186. model: {default: true},
  52187. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  52188. hideDisconnected: {default: true}
  52189. },
  52190. mapping: INPUT_MAPPING,
  52191. bindMethods: function () {
  52192. this.onModelError = bind(this.onModelError, this);
  52193. this.onModelLoaded = bind(this.onModelLoaded, this);
  52194. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52195. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52196. this.onAxisMoved = bind(this.onAxisMoved, this);
  52197. },
  52198. init: function () {
  52199. var self = this;
  52200. var el = this.el;
  52201. this.onButtonChanged = bind(this.onButtonChanged, this);
  52202. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52203. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52204. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52205. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52206. this.onControllerConnected = function () { self.setModelVisibility(true); };
  52207. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  52208. this.controllerPresent = false;
  52209. this.lastControllerCheck = 0;
  52210. this.previousButtonValues = {};
  52211. this.bindMethods();
  52212. // Cache for submeshes that we have looked up by name.
  52213. this.loadedMeshInfo = {
  52214. buttonMeshes: null,
  52215. axisMeshes: null
  52216. };
  52217. // Pointing poses
  52218. this.rayOrigin = {
  52219. origin: new THREE.Vector3(),
  52220. direction: new THREE.Vector3(0, 0, -1),
  52221. createdFromMesh: false
  52222. };
  52223. el.addEventListener('controllerconnected', this.onControllerConnected);
  52224. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  52225. },
  52226. addEventListeners: function () {
  52227. var el = this.el;
  52228. el.addEventListener('buttonchanged', this.onButtonChanged);
  52229. el.addEventListener('buttondown', this.onButtonDown);
  52230. el.addEventListener('buttonup', this.onButtonUp);
  52231. el.addEventListener('touchstart', this.onButtonTouchStart);
  52232. el.addEventListener('touchend', this.onButtonTouchEnd);
  52233. el.addEventListener('axismove', this.onAxisMoved);
  52234. el.addEventListener('model-error', this.onModelError);
  52235. el.addEventListener('model-loaded', this.onModelLoaded);
  52236. this.controllerEventsActive = true;
  52237. },
  52238. removeEventListeners: function () {
  52239. var el = this.el;
  52240. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52241. el.removeEventListener('buttondown', this.onButtonDown);
  52242. el.removeEventListener('buttonup', this.onButtonUp);
  52243. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52244. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52245. el.removeEventListener('axismove', this.onAxisMoved);
  52246. el.removeEventListener('model-error', this.onModelError);
  52247. el.removeEventListener('model-loaded', this.onModelLoaded);
  52248. this.controllerEventsActive = false;
  52249. },
  52250. checkIfControllerPresent: function () {
  52251. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  52252. hand: this.data.hand,
  52253. index: this.data.pair,
  52254. iterateControllerProfiles: true
  52255. });
  52256. },
  52257. play: function () {
  52258. this.checkIfControllerPresent();
  52259. this.addControllersUpdateListener();
  52260. },
  52261. pause: function () {
  52262. this.removeEventListeners();
  52263. this.removeControllersUpdateListener();
  52264. },
  52265. updateControllerModel: function () {
  52266. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  52267. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  52268. this.modelReady();
  52269. return;
  52270. }
  52271. var sourceUrl = this.createControllerModelUrl();
  52272. this.loadModel(sourceUrl);
  52273. },
  52274. /**
  52275. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  52276. * art assets.
  52277. */
  52278. createControllerModelUrl: function (forceDefault) {
  52279. // Determine the device specific folder based on the ID suffix
  52280. var trackedControlsComponent = this.el.components['tracked-controls'];
  52281. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  52282. var device = 'default';
  52283. var hand = this.data.hand;
  52284. var filename;
  52285. if (controller && !window.hasNativeWebXRImplementation) {
  52286. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  52287. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  52288. // In this case, we want to load the universal model, so need to get the '' from the controller.
  52289. hand = controller.hand;
  52290. if (!forceDefault) {
  52291. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  52292. device = ((match && match[0]) || device);
  52293. }
  52294. }
  52295. // Hand
  52296. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  52297. // Final url
  52298. return MODEL_BASE_URL + device + '/' + filename;
  52299. },
  52300. injectTrackedControls: function () {
  52301. var data = this.data;
  52302. this.el.setAttribute('tracked-controls', {
  52303. idPrefix: GAMEPAD_ID_PREFIX,
  52304. controller: data.pair,
  52305. hand: data.hand,
  52306. armModel: false
  52307. });
  52308. this.updateControllerModel();
  52309. },
  52310. addControllersUpdateListener: function () {
  52311. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52312. },
  52313. removeControllersUpdateListener: function () {
  52314. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52315. },
  52316. onControllersUpdate: function () {
  52317. this.checkIfControllerPresent();
  52318. },
  52319. onModelError: function (evt) {
  52320. var defaultUrl = this.createControllerModelUrl(true);
  52321. if (evt.detail.src !== defaultUrl) {
  52322. warn('Failed to load controller model for device, attempting to load default.');
  52323. this.loadModel(defaultUrl);
  52324. } else {
  52325. warn('Failed to load default controller model.');
  52326. }
  52327. },
  52328. loadModel: function (url) {
  52329. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  52330. // removed and re-loaded if the given url changes.
  52331. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  52332. },
  52333. onModelLoaded: function (evt) {
  52334. var rootNode = this.controllerModel = evt.detail.model;
  52335. var loadedMeshInfo = this.loadedMeshInfo;
  52336. var i;
  52337. var meshName;
  52338. var mesh;
  52339. var meshInfo;
  52340. debug('Processing model');
  52341. // Reset the caches
  52342. loadedMeshInfo.buttonMeshes = {};
  52343. loadedMeshInfo.axisMeshes = {};
  52344. // Cache our meshes so we aren't traversing the hierarchy per frame
  52345. if (rootNode) {
  52346. // Button Meshes
  52347. for (i = 0; i < this.mapping.buttons.length; i++) {
  52348. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  52349. if (!meshName) {
  52350. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  52351. continue;
  52352. }
  52353. mesh = rootNode.getObjectByName(meshName);
  52354. if (!mesh) {
  52355. warn('Missing button mesh with name: ' + meshName);
  52356. continue;
  52357. }
  52358. meshInfo = {
  52359. index: i,
  52360. value: getImmediateChildByName(mesh, 'VALUE'),
  52361. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  52362. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  52363. };
  52364. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  52365. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  52366. } else {
  52367. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52368. warn('Missing button submesh under mesh with name: ' + meshName +
  52369. '(VALUE: ' + !!meshInfo.value +
  52370. ', PRESSED: ' + !!meshInfo.pressed +
  52371. ', UNPRESSED:' + !!meshInfo.unpressed +
  52372. ')');
  52373. }
  52374. }
  52375. // Axis Meshes
  52376. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  52377. meshName = this.mapping.axisMeshNames[i];
  52378. if (!meshName) {
  52379. debug('Skipping unknown axis at index: ' + i);
  52380. continue;
  52381. }
  52382. mesh = rootNode.getObjectByName(meshName);
  52383. if (!mesh) {
  52384. warn('Missing axis mesh with name: ' + meshName);
  52385. continue;
  52386. }
  52387. meshInfo = {
  52388. index: i,
  52389. value: getImmediateChildByName(mesh, 'VALUE'),
  52390. min: getImmediateChildByName(mesh, 'MIN'),
  52391. max: getImmediateChildByName(mesh, 'MAX')
  52392. };
  52393. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  52394. loadedMeshInfo.axisMeshes[i] = meshInfo;
  52395. } else {
  52396. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  52397. warn('Missing axis submesh under mesh with name: ' + meshName +
  52398. '(VALUE: ' + !!meshInfo.value +
  52399. ', MIN: ' + !!meshInfo.min +
  52400. ', MAX:' + !!meshInfo.max +
  52401. ')');
  52402. }
  52403. }
  52404. this.calculateRayOriginFromMesh(rootNode);
  52405. // Determine if the model has to be visible or not.
  52406. this.setModelVisibility();
  52407. }
  52408. debug('Model load complete.');
  52409. // Look through only immediate children. This will return null if no mesh exists with the given name.
  52410. function getImmediateChildByName (object3d, value) {
  52411. for (var i = 0, l = object3d.children.length; i < l; i++) {
  52412. var obj = object3d.children[i];
  52413. if (obj && obj['name'] === value) {
  52414. return obj;
  52415. }
  52416. }
  52417. return undefined;
  52418. }
  52419. },
  52420. calculateRayOriginFromMesh: (function () {
  52421. var quaternion = new THREE.Quaternion();
  52422. return function (rootNode) {
  52423. var mesh;
  52424. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  52425. // in the glTF (assumes that root node is at world origin)
  52426. this.rayOrigin.origin.set(0, 0, 0);
  52427. this.rayOrigin.direction.set(0, 0, -1);
  52428. this.rayOrigin.createdFromMesh = true;
  52429. // Try to read Pointing pose from the source model
  52430. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  52431. if (mesh) {
  52432. var parent = rootNode.parent;
  52433. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  52434. if (parent) {
  52435. rootNode.parent = null;
  52436. rootNode.updateMatrixWorld(true);
  52437. rootNode.parent = parent;
  52438. }
  52439. mesh.getWorldPosition(this.rayOrigin.origin);
  52440. mesh.getWorldQuaternion(quaternion);
  52441. this.rayOrigin.direction.applyQuaternion(quaternion);
  52442. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  52443. if (parent) {
  52444. rootNode.updateMatrixWorld(true);
  52445. }
  52446. } else {
  52447. debug('Mesh does not contain pointing origin data, defaulting to none.');
  52448. }
  52449. // Emit event stating that our pointing ray is now accurate.
  52450. this.modelReady();
  52451. };
  52452. })(),
  52453. lerpAxisTransform: (function () {
  52454. var quaternion = new THREE.Quaternion();
  52455. return function (axis, axisValue) {
  52456. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  52457. if (!axisMeshInfo) return;
  52458. var min = axisMeshInfo.min;
  52459. var max = axisMeshInfo.max;
  52460. var target = axisMeshInfo.value;
  52461. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52462. var lerpValue = axisValue * 0.5 + 0.5;
  52463. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  52464. target.position.lerpVectors(min.position, max.position, lerpValue);
  52465. };
  52466. })(),
  52467. lerpButtonTransform: (function () {
  52468. var quaternion = new THREE.Quaternion();
  52469. return function (buttonName, buttonValue) {
  52470. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  52471. if (!buttonMeshInfo) return;
  52472. var min = buttonMeshInfo.unpressed;
  52473. var max = buttonMeshInfo.pressed;
  52474. var target = buttonMeshInfo.value;
  52475. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  52476. target.position.lerpVectors(min.position, max.position, buttonValue);
  52477. };
  52478. })(),
  52479. modelReady: function () {
  52480. this.el.emit('controllermodelready', {
  52481. name: 'windows-motion-controls',
  52482. model: this.data.model,
  52483. rayOrigin: this.rayOrigin
  52484. });
  52485. },
  52486. onButtonChanged: function (evt) {
  52487. var buttonName = this.mapping.buttons[evt.detail.id];
  52488. if (buttonName) {
  52489. // Update the button mesh transform
  52490. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  52491. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  52492. }
  52493. // Only emit events for buttons that we know how to map from index to name
  52494. this.el.emit(buttonName + 'changed', evt.detail.state);
  52495. }
  52496. },
  52497. onAxisMoved: function (evt) {
  52498. var numAxes = this.mapping.axisMeshNames.length;
  52499. // Only attempt to update meshes if we have valid data.
  52500. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  52501. for (var axis = 0; axis < numAxes; axis++) {
  52502. // Update the button mesh transform
  52503. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  52504. }
  52505. }
  52506. emitIfAxesChanged(this, this.mapping.axes, evt);
  52507. },
  52508. setModelVisibility: function (visible) {
  52509. var model = this.el.getObject3D('mesh');
  52510. visible = visible !== undefined ? visible : this.modelVisible;
  52511. this.modelVisible = visible;
  52512. if (!model) { return; }
  52513. model.visible = visible;
  52514. }
  52515. });
  52516. },{"../constants":121,"../core/component":129,"../utils/":203,"../utils/bind":197,"../utils/tracked-controls":211}],121:[function(_dereq_,module,exports){
  52517. module.exports = {
  52518. AFRAME_INJECTED: 'aframe-injected',
  52519. DEFAULT_CAMERA_HEIGHT: 1.6,
  52520. DEFAULT_HANDEDNESS: 'right',
  52521. keyboardevent: _dereq_('./keyboardevent')
  52522. };
  52523. },{"./keyboardevent":122}],122:[function(_dereq_,module,exports){
  52524. module.exports = {
  52525. // Tiny KeyboardEvent.code polyfill.
  52526. KEYCODE_TO_CODE: {
  52527. '38': 'ArrowUp',
  52528. '37': 'ArrowLeft',
  52529. '40': 'ArrowDown',
  52530. '39': 'ArrowRight',
  52531. '87': 'KeyW',
  52532. '65': 'KeyA',
  52533. '83': 'KeyS',
  52534. '68': 'KeyD'
  52535. }
  52536. };
  52537. },{}],123:[function(_dereq_,module,exports){
  52538. var ANode = _dereq_('./a-node');
  52539. var bind = _dereq_('../utils/bind');
  52540. var debug = _dereq_('../utils/debug');
  52541. var registerElement = _dereq_('./a-register-element').registerElement;
  52542. var THREE = _dereq_('../lib/three');
  52543. var fileLoader = new THREE.FileLoader();
  52544. var warn = debug('core:a-assets:warn');
  52545. /**
  52546. * Asset management system. Handles blocking on asset loading.
  52547. */
  52548. module.exports = registerElement('a-assets', {
  52549. prototype: Object.create(ANode.prototype, {
  52550. createdCallback: {
  52551. value: function () {
  52552. this.isAssets = true;
  52553. this.fileLoader = fileLoader;
  52554. this.timeout = null;
  52555. }
  52556. },
  52557. attachedCallback: {
  52558. value: function () {
  52559. var self = this;
  52560. var i;
  52561. var loaded = [];
  52562. var mediaEl;
  52563. var mediaEls;
  52564. var imgEl;
  52565. var imgEls;
  52566. var timeout;
  52567. if (!this.parentNode.isScene) {
  52568. throw new Error('<a-assets> must be a child of a <a-scene>.');
  52569. }
  52570. // Wait for <img>s.
  52571. imgEls = this.querySelectorAll('img');
  52572. for (i = 0; i < imgEls.length; i++) {
  52573. imgEl = fixUpMediaElement(imgEls[i]);
  52574. loaded.push(new Promise(function (resolve, reject) {
  52575. // Set in cache because we won't be needing to call three.js loader if we have.
  52576. // a loaded media element.
  52577. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  52578. imgEl.onload = resolve;
  52579. imgEl.onerror = reject;
  52580. }));
  52581. }
  52582. // Wait for <audio>s and <video>s.
  52583. mediaEls = this.querySelectorAll('audio, video');
  52584. for (i = 0; i < mediaEls.length; i++) {
  52585. mediaEl = fixUpMediaElement(mediaEls[i]);
  52586. if (!mediaEl.src && !mediaEl.srcObject) {
  52587. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  52588. }
  52589. loaded.push(mediaElementLoaded(mediaEl));
  52590. }
  52591. // Trigger loaded for scene to start rendering.
  52592. Promise.all(loaded).then(bind(this.load, this));
  52593. // Timeout to start loading anyways.
  52594. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  52595. this.timeout = setTimeout(function () {
  52596. if (self.hasLoaded) { return; }
  52597. warn('Asset loading timed out in ', timeout, 'ms');
  52598. self.emit('timeout');
  52599. self.load();
  52600. }, timeout);
  52601. }
  52602. },
  52603. detachedCallback: {
  52604. value: function () {
  52605. if (this.timeout) { clearTimeout(this.timeout); }
  52606. }
  52607. },
  52608. load: {
  52609. value: function () {
  52610. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  52611. return el.isAssetItem && el.hasAttribute('src');
  52612. });
  52613. }
  52614. }
  52615. })
  52616. });
  52617. /**
  52618. * Preload using XHRLoader for any type of asset.
  52619. */
  52620. registerElement('a-asset-item', {
  52621. prototype: Object.create(ANode.prototype, {
  52622. createdCallback: {
  52623. value: function () {
  52624. this.data = null;
  52625. this.isAssetItem = true;
  52626. }
  52627. },
  52628. attachedCallback: {
  52629. value: function () {
  52630. var self = this;
  52631. var src = this.getAttribute('src');
  52632. fileLoader.setResponseType(
  52633. this.getAttribute('response-type') || inferResponseType(src));
  52634. fileLoader.load(src, function handleOnLoad (response) {
  52635. self.data = response;
  52636. /*
  52637. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  52638. previous one closes, the second request never finishes.
  52639. setTimeout finishes the first request and lets the logic triggered by load open
  52640. subsequent requests.
  52641. setTimeout can be removed once the fix for the bug below ships:
  52642. 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
  52643. */
  52644. setTimeout(function load () { ANode.prototype.load.call(self); });
  52645. }, function handleOnProgress (xhr) {
  52646. self.emit('progress', {
  52647. loadedBytes: xhr.loaded,
  52648. totalBytes: xhr.total,
  52649. xhr: xhr
  52650. });
  52651. }, function handleOnError (xhr) {
  52652. self.emit('error', {xhr: xhr});
  52653. });
  52654. }
  52655. }
  52656. })
  52657. });
  52658. /**
  52659. * Create a Promise that resolves once the media element has finished buffering.
  52660. *
  52661. * @param {Element} el - HTMLMediaElement.
  52662. * @returns {Promise}
  52663. */
  52664. function mediaElementLoaded (el) {
  52665. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  52666. return;
  52667. }
  52668. // If media specifies autoplay or preload, wait until media is completely buffered.
  52669. return new Promise(function (resolve, reject) {
  52670. if (el.readyState === 4) { return resolve(); } // Already loaded.
  52671. if (el.error) { return reject(); } // Error.
  52672. el.addEventListener('loadeddata', checkProgress, false);
  52673. el.addEventListener('progress', checkProgress, false);
  52674. el.addEventListener('error', reject, false);
  52675. function checkProgress () {
  52676. // Add up the seconds buffered.
  52677. var secondsBuffered = 0;
  52678. for (var i = 0; i < el.buffered.length; i++) {
  52679. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  52680. }
  52681. // Compare seconds buffered to media duration.
  52682. if (secondsBuffered >= el.duration) {
  52683. // Set in cache because we won't be needing to call three.js loader if we have.
  52684. // a loaded media element.
  52685. // Store video elements only. three.js loader is used for audio elements.
  52686. // See assetParse too.
  52687. if (el.tagName === 'VIDEO') {
  52688. THREE.Cache.files[el.getAttribute('src')] = el;
  52689. }
  52690. resolve();
  52691. }
  52692. }
  52693. });
  52694. }
  52695. /**
  52696. * Automatically add attributes to media elements where convenient.
  52697. * crossorigin, playsinline.
  52698. */
  52699. function fixUpMediaElement (mediaEl) {
  52700. // Cross-origin.
  52701. var newMediaEl = setCrossOrigin(mediaEl);
  52702. // Plays inline for mobile.
  52703. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  52704. newMediaEl.setAttribute('playsinline', '');
  52705. newMediaEl.setAttribute('webkit-playsinline', '');
  52706. }
  52707. if (newMediaEl !== mediaEl) {
  52708. mediaEl.parentNode.appendChild(newMediaEl);
  52709. mediaEl.parentNode.removeChild(mediaEl);
  52710. }
  52711. return newMediaEl;
  52712. }
  52713. /**
  52714. * Automatically set `crossorigin` if not defined on the media element.
  52715. * If it is not defined, we must create and re-append a new media element <img> and
  52716. * have the browser re-request it with `crossorigin` set.
  52717. *
  52718. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  52719. * @returns {Element} Media element to be used to listen to for loaded events.
  52720. */
  52721. function setCrossOrigin (mediaEl) {
  52722. var newMediaEl;
  52723. var src;
  52724. // Already has crossorigin set.
  52725. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  52726. src = mediaEl.getAttribute('src');
  52727. if (src !== null) {
  52728. // Does not have protocol.
  52729. if (src.indexOf('://') === -1) { return mediaEl; }
  52730. // Determine if cross origin is actually needed.
  52731. if (extractDomain(src) === window.location.host) { return mediaEl; }
  52732. }
  52733. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  52734. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  52735. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  52736. mediaEl.crossOrigin = 'anonymous';
  52737. newMediaEl = mediaEl.cloneNode(true);
  52738. return newMediaEl;
  52739. }
  52740. /**
  52741. * Extract domain out of URL.
  52742. *
  52743. * @param {string} url
  52744. * @returns {string}
  52745. */
  52746. function extractDomain (url) {
  52747. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  52748. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  52749. // Find and remove port number.
  52750. return domain.substring(0, domain.indexOf(':'));
  52751. }
  52752. /**
  52753. * Infer response-type attribute from src.
  52754. * Default is text (default XMLHttpRequest.responseType)
  52755. * and arraybuffer for .glb files.
  52756. *
  52757. * @param {string} src
  52758. * @returns {string}
  52759. */
  52760. function inferResponseType (src) {
  52761. var fileName = getFileNameFromURL(src);
  52762. var dotLastIndex = fileName.lastIndexOf('.');
  52763. if (dotLastIndex >= 0) {
  52764. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  52765. if (extension === '.glb') {
  52766. return 'arraybuffer';
  52767. }
  52768. }
  52769. return 'text';
  52770. }
  52771. module.exports.inferResponseType = inferResponseType;
  52772. /**
  52773. * Extract filename from URL
  52774. *
  52775. * @param {string} url
  52776. * @returns {string}
  52777. */
  52778. function getFileNameFromURL (url) {
  52779. var parser = document.createElement('a');
  52780. parser.href = url;
  52781. var query = parser.search.replace(/^\?/, '');
  52782. var filePath = url.replace(query, '').replace('?', '');
  52783. return filePath.substring(filePath.lastIndexOf('/') + 1);
  52784. }
  52785. module.exports.getFileNameFromURL = getFileNameFromURL;
  52786. },{"../lib/three":177,"../utils/bind":197,"../utils/debug":199,"./a-node":127,"./a-register-element":128}],124:[function(_dereq_,module,exports){
  52787. var debug = _dereq_('../utils/debug');
  52788. var registerElement = _dereq_('./a-register-element').registerElement;
  52789. var warn = debug('core:cubemap:warn');
  52790. /**
  52791. * Cubemap element that handles validation and exposes list of URLs.
  52792. * Does not listen to updates.
  52793. */
  52794. module.exports = registerElement('a-cubemap', {
  52795. prototype: Object.create(window.HTMLElement.prototype, {
  52796. /**
  52797. * Calculates this.srcs.
  52798. */
  52799. attachedCallback: {
  52800. value: function () {
  52801. this.srcs = this.validate();
  52802. },
  52803. writable: window.debug
  52804. },
  52805. /**
  52806. * Checks for exactly six elements with [src].
  52807. * Does not check explicitly for <img>s in case user does not want
  52808. * prefetching.
  52809. *
  52810. * @returns {Array|null} - six URLs if valid, else null.
  52811. */
  52812. validate: {
  52813. value: function () {
  52814. var elements = this.querySelectorAll('[src]');
  52815. var i;
  52816. var srcs = [];
  52817. if (elements.length === 6) {
  52818. for (i = 0; i < elements.length; i++) {
  52819. srcs.push(elements[i].getAttribute('src'));
  52820. }
  52821. return srcs;
  52822. }
  52823. // Else if there are not six elements, throw a warning.
  52824. warn(
  52825. '<a-cubemap> did not contain exactly six elements each with a ' +
  52826. '`src` attribute.');
  52827. },
  52828. writable: window.debug
  52829. }
  52830. })
  52831. });
  52832. },{"../utils/debug":199,"./a-register-element":128}],125:[function(_dereq_,module,exports){
  52833. var ANode = _dereq_('./a-node');
  52834. var COMPONENTS = _dereq_('./component').components;
  52835. var registerElement = _dereq_('./a-register-element').registerElement;
  52836. var THREE = _dereq_('../lib/three');
  52837. var utils = _dereq_('../utils/');
  52838. var AEntity;
  52839. var debug = utils.debug('core:a-entity:debug');
  52840. var warn = utils.debug('core:a-entity:warn');
  52841. var MULTIPLE_COMPONENT_DELIMITER = '__';
  52842. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  52843. var ONCE = {once: true};
  52844. /**
  52845. * Entity is a container object that components are plugged into to comprise everything in
  52846. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  52847. *
  52848. * To be able to take components, the scene element inherits from the entity definition.
  52849. *
  52850. * @member {object} components - entity's currently initialized components.
  52851. * @member {object} object3D - three.js object.
  52852. * @member {array} states
  52853. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  52854. */
  52855. var proto = Object.create(ANode.prototype, {
  52856. createdCallback: {
  52857. value: function () {
  52858. this.components = {};
  52859. // To avoid double initializations and infinite loops.
  52860. this.initializingComponents = {};
  52861. this.componentsToUpdate = {};
  52862. this.isEntity = true;
  52863. this.isPlaying = false;
  52864. this.object3D = new THREE.Group();
  52865. this.object3D.el = this;
  52866. this.object3DMap = {};
  52867. this.parentEl = null;
  52868. this.rotationObj = {};
  52869. this.states = [];
  52870. }
  52871. },
  52872. /**
  52873. * Handle changes coming from the browser DOM inspector.
  52874. */
  52875. attributeChangedCallback: {
  52876. value: function (attr, oldVal, newVal) {
  52877. var component = this.components[attr];
  52878. // If the empty string is passed by the component initialization
  52879. // logic we ignore the component update.
  52880. if (component && component.justInitialized && newVal === '') {
  52881. delete component.justInitialized;
  52882. return;
  52883. }
  52884. // When a component is removed after calling el.removeAttribute('material')
  52885. if (!component && newVal === null) { return; }
  52886. this.setEntityAttribute(attr, oldVal, newVal);
  52887. }
  52888. },
  52889. /**
  52890. * Add to parent, load, play.
  52891. */
  52892. attachedCallback: {
  52893. value: function () {
  52894. var assetsEl; // Asset management system element.
  52895. var sceneEl = this.sceneEl;
  52896. var self = this; // Component.
  52897. this.addToParent();
  52898. // Don't .load() scene on attachedCallback.
  52899. if (this.isScene) { return; }
  52900. // Gracefully not error when outside of <a-scene> (e.g., tests).
  52901. if (!sceneEl) {
  52902. this.load();
  52903. return;
  52904. }
  52905. // Wait for asset management system to finish before loading.
  52906. assetsEl = sceneEl.querySelector('a-assets');
  52907. if (assetsEl && !assetsEl.hasLoaded) {
  52908. assetsEl.addEventListener('loaded', function () { self.load(); });
  52909. return;
  52910. }
  52911. this.load();
  52912. }
  52913. },
  52914. /**
  52915. * Tell parent to remove this element's object3D from its object3D.
  52916. * Do not call on scene element because that will cause a call to document.body.remove().
  52917. */
  52918. detachedCallback: {
  52919. value: function () {
  52920. var componentName;
  52921. if (!this.parentEl) { return; }
  52922. // Remove components.
  52923. for (componentName in this.components) {
  52924. this.removeComponent(componentName, false);
  52925. }
  52926. if (this.isScene) { return; }
  52927. this.removeFromParent();
  52928. ANode.prototype.detachedCallback.call(this);
  52929. // Remove cyclic reference.
  52930. this.object3D.el = null;
  52931. }
  52932. },
  52933. getObject3D: {
  52934. value: function (type) {
  52935. return this.object3DMap[type];
  52936. }
  52937. },
  52938. /**
  52939. * Set a THREE.Object3D into the map.
  52940. *
  52941. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  52942. * @param {object} obj - A THREE.Object3D.
  52943. */
  52944. setObject3D: {
  52945. value: function (type, obj) {
  52946. var oldObj;
  52947. var self = this;
  52948. if (!(obj instanceof THREE.Object3D)) {
  52949. throw new Error(
  52950. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  52951. 'THREE.Object3D.'
  52952. );
  52953. }
  52954. // Remove existing object of the type.
  52955. oldObj = this.getObject3D(type);
  52956. if (oldObj) { this.object3D.remove(oldObj); }
  52957. // Set references to A-Frame entity.
  52958. obj.el = this;
  52959. if (obj.children.length) {
  52960. obj.traverse(function bindEl (child) {
  52961. child.el = self;
  52962. });
  52963. }
  52964. // Add.
  52965. this.object3D.add(obj);
  52966. this.object3DMap[type] = obj;
  52967. this.emit('object3dset', {object: obj, type: type});
  52968. }
  52969. },
  52970. /**
  52971. * Remove object from scene and entity object3D map.
  52972. */
  52973. removeObject3D: {
  52974. value: function (type) {
  52975. var obj = this.getObject3D(type);
  52976. if (!obj) {
  52977. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  52978. return;
  52979. }
  52980. this.object3D.remove(obj);
  52981. delete this.object3DMap[type];
  52982. this.emit('object3dremove', {type: type});
  52983. }
  52984. },
  52985. /**
  52986. * Gets or creates an object3D of a given type.
  52987. *
  52988. * @param {string} type - Type of the object3D.
  52989. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  52990. * @returns {object}
  52991. */
  52992. getOrCreateObject3D: {
  52993. value: function (type, Constructor) {
  52994. var object3D = this.getObject3D(type);
  52995. if (!object3D && Constructor) {
  52996. object3D = new Constructor();
  52997. this.setObject3D(type, object3D);
  52998. }
  52999. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  53000. 'and `object3dset` event instead.');
  53001. return object3D;
  53002. }
  53003. },
  53004. /**
  53005. * Add child entity.
  53006. *
  53007. * @param {Element} el - Child entity.
  53008. */
  53009. add: {
  53010. value: function (el) {
  53011. if (!el.object3D) {
  53012. throw new Error("Trying to add an element that doesn't have an `object3D`");
  53013. }
  53014. this.object3D.add(el.object3D);
  53015. this.emit('child-attached', {el: el});
  53016. }
  53017. },
  53018. /**
  53019. * Tell parentNode to add this entity to itself.
  53020. */
  53021. addToParent: {
  53022. value: function () {
  53023. var parentNode = this.parentEl = this.parentNode;
  53024. // `!parentNode` check primarily for unit tests.
  53025. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  53026. parentNode.add(this);
  53027. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  53028. }
  53029. },
  53030. /**
  53031. * Tell parentNode to remove this entity from itself.
  53032. */
  53033. removeFromParent: {
  53034. value: function () {
  53035. var parentEl = this.parentEl;
  53036. this.parentEl.remove(this);
  53037. this.attachedToParent = false;
  53038. this.parentEl = null;
  53039. parentEl.emit('child-detached', {el: this});
  53040. }
  53041. },
  53042. load: {
  53043. value: function () {
  53044. var self = this;
  53045. if (this.hasLoaded || !this.parentEl) { return; }
  53046. ANode.prototype.load.call(this, function entityLoadCallback () {
  53047. // Check if entity was detached while it was waiting to load.
  53048. if (!self.parentEl) { return; }
  53049. self.updateComponents();
  53050. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  53051. });
  53052. },
  53053. writable: window.debug
  53054. },
  53055. /**
  53056. * Remove child entity.
  53057. *
  53058. * @param {Element} el - Child entity.
  53059. */
  53060. remove: {
  53061. value: function (el) {
  53062. if (el) {
  53063. this.object3D.remove(el.object3D);
  53064. } else {
  53065. this.parentNode.removeChild(this);
  53066. }
  53067. }
  53068. },
  53069. /**
  53070. * @returns {array} Direct children that are entities.
  53071. */
  53072. getChildEntities: {
  53073. value: function () {
  53074. var children = this.children;
  53075. var childEntities = [];
  53076. for (var i = 0; i < children.length; i++) {
  53077. var child = children[i];
  53078. if (child instanceof AEntity) {
  53079. childEntities.push(child);
  53080. }
  53081. }
  53082. return childEntities;
  53083. }
  53084. },
  53085. /**
  53086. * Initialize component.
  53087. *
  53088. * @param {string} attrName - Attribute name asociated to the component.
  53089. * @param {object} data - Component data
  53090. * @param {boolean} isDependency - True if the component is a dependency.
  53091. */
  53092. initComponent: {
  53093. value: function (attrName, data, isDependency) {
  53094. var component;
  53095. var componentId;
  53096. var componentInfo;
  53097. var componentName;
  53098. var isComponentDefined;
  53099. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  53100. componentName = componentInfo[0];
  53101. componentId = componentInfo.length > 2
  53102. ? componentInfo.slice(1).join('__')
  53103. : componentInfo[1];
  53104. // Not a registered component.
  53105. if (!COMPONENTS[componentName]) { return; }
  53106. // Component is not a dependency and is undefined.
  53107. // If a component is a dependency, then it is okay to have no data.
  53108. isComponentDefined = checkComponentDefined(this, attrName) ||
  53109. data !== undefined;
  53110. if (!isComponentDefined && !isDependency) { return; }
  53111. // Component already initialized.
  53112. if (attrName in this.components) { return; }
  53113. // Initialize dependencies first
  53114. this.initComponentDependencies(componentName);
  53115. // If component name has an id we check component type multiplic
  53116. if (componentId && !COMPONENTS[componentName].multiple) {
  53117. throw new Error('Trying to initialize multiple ' +
  53118. 'components of type `' + componentName +
  53119. '`. There can only be one component of this type per entity.');
  53120. }
  53121. component = new COMPONENTS[componentName].Component(this, data, componentId);
  53122. if (this.isPlaying) { component.play(); }
  53123. // Components are reflected in the DOM as attributes but the state is not shown
  53124. // hence we set the attribute to empty string.
  53125. // The flag justInitialized is for attributeChangedCallback to not overwrite
  53126. // the component with the empty string.
  53127. if (!this.hasAttribute(attrName)) {
  53128. component.justInitialized = true;
  53129. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  53130. }
  53131. debug('Component initialized: %s', attrName);
  53132. },
  53133. writable: window.debug
  53134. },
  53135. /**
  53136. * Initialize dependencies of a component.
  53137. *
  53138. * @param {string} name - Root component name.
  53139. */
  53140. initComponentDependencies: {
  53141. value: function (name) {
  53142. var self = this;
  53143. var component = COMPONENTS[name];
  53144. var dependencies;
  53145. var i;
  53146. // Not a component.
  53147. if (!component) { return; }
  53148. // No dependencies.
  53149. dependencies = COMPONENTS[name].dependencies;
  53150. if (!dependencies) { return; }
  53151. // Initialize dependencies.
  53152. for (i = 0; i < dependencies.length; i++) {
  53153. // Call getAttribute to initialize the data from the DOM.
  53154. self.initComponent(
  53155. dependencies[i],
  53156. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  53157. true
  53158. );
  53159. }
  53160. }
  53161. },
  53162. removeComponent: {
  53163. value: function (name, destroy) {
  53164. var component;
  53165. component = this.components[name];
  53166. if (!component) { return; }
  53167. // Wait for component to initialize.
  53168. if (!component.initialized) {
  53169. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  53170. if (evt.detail.name !== name) { return; }
  53171. this.removeComponent(name, destroy);
  53172. this.removeEventListener('componentinitialized', tryRemoveLater);
  53173. });
  53174. return;
  53175. }
  53176. component.pause();
  53177. component.remove();
  53178. // Keep component attached to entity in case of just full entity detach.
  53179. if (destroy) {
  53180. component.destroy();
  53181. delete this.components[name];
  53182. }
  53183. this.emit('componentremoved', component.evtDetail, false);
  53184. },
  53185. writable: window.debug
  53186. },
  53187. /**
  53188. * Initialize or update all components.
  53189. * Build data using initial components, defined attributes, mixins, and defaults.
  53190. * Update default components before the rest.
  53191. *
  53192. * @member {function} getExtraComponents - Can be implemented to include component data
  53193. * from other sources (e.g., implemented by primitives).
  53194. */
  53195. updateComponents: {
  53196. value: function () {
  53197. var data;
  53198. var extraComponents;
  53199. var i;
  53200. var name;
  53201. var componentsToUpdate = this.componentsToUpdate;
  53202. if (!this.hasLoaded) { return; }
  53203. // Gather mixin-defined components.
  53204. for (i = 0; i < this.mixinEls.length; i++) {
  53205. for (name in this.mixinEls[i].componentCache) {
  53206. if (isComponent(name)) { componentsToUpdate[name] = true; }
  53207. }
  53208. }
  53209. // Gather from extra initial component data if defined (e.g., primitives).
  53210. if (this.getExtraComponents) {
  53211. extraComponents = this.getExtraComponents();
  53212. for (name in extraComponents) {
  53213. if (isComponent(name)) { componentsToUpdate[name] = true; }
  53214. }
  53215. }
  53216. // Gather entity-defined components.
  53217. for (i = 0; i < this.attributes.length; ++i) {
  53218. name = this.attributes[i].name;
  53219. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  53220. if (isComponent(name)) { componentsToUpdate[name] = true; }
  53221. }
  53222. // object3D components first (position, rotation, scale, visible).
  53223. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  53224. name = OBJECT3D_COMPONENTS[i];
  53225. if (!this.hasAttribute(name)) { continue; }
  53226. this.updateComponent(name, this.getDOMAttribute(name));
  53227. }
  53228. // Initialize or update rest of components.
  53229. for (name in componentsToUpdate) {
  53230. data = mergeComponentData(this.getDOMAttribute(name),
  53231. extraComponents && extraComponents[name]);
  53232. this.updateComponent(name, data);
  53233. delete componentsToUpdate[name];
  53234. }
  53235. },
  53236. writable: window.debug
  53237. },
  53238. /**
  53239. * Initialize, update, or remove a single component.
  53240. *
  53241. * When initializing, we set the component on `this.components`.
  53242. *
  53243. * @param {string} attr - Component name.
  53244. * @param {object} attrValue - Value of the DOM attribute.
  53245. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  53246. */
  53247. updateComponent: {
  53248. value: function (attr, attrValue, clobber) {
  53249. var component = this.components[attr];
  53250. if (component) {
  53251. // Remove component.
  53252. if (attrValue === null && !checkComponentDefined(this, attr)) {
  53253. this.removeComponent(attr, true);
  53254. return;
  53255. }
  53256. // Component already initialized. Update component.
  53257. component.updateProperties(attrValue, clobber);
  53258. return;
  53259. }
  53260. // Component not yet initialized. Initialize component.
  53261. this.initComponent(attr, attrValue, false);
  53262. }
  53263. },
  53264. /**
  53265. * If `attr` is a component name, detach the component from the entity.
  53266. *
  53267. * If `propertyName` is given, reset the component property value to its default.
  53268. *
  53269. * @param {string} attr - Attribute name, which could also be a component name.
  53270. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  53271. */
  53272. removeAttribute: {
  53273. value: function (attr, propertyName) {
  53274. var component = this.components[attr];
  53275. // Remove component.
  53276. if (component && propertyName === undefined) {
  53277. this.removeComponent(attr, true);
  53278. }
  53279. // Reset component property value.
  53280. if (component && propertyName !== undefined) {
  53281. component.resetProperty(propertyName);
  53282. return;
  53283. }
  53284. // Remove mixins.
  53285. if (attr === 'mixin') {
  53286. this.mixinUpdate('');
  53287. }
  53288. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  53289. }
  53290. },
  53291. /**
  53292. * Start dynamic behavior associated with entity such as dynamic components and animations.
  53293. * Tell all children entities to also play.
  53294. */
  53295. play: {
  53296. value: function () {
  53297. var entities;
  53298. var i;
  53299. var key;
  53300. // Already playing.
  53301. if (this.isPlaying || !this.hasLoaded) { return; }
  53302. this.isPlaying = true;
  53303. // Wake up all components.
  53304. for (key in this.components) { this.components[key].play(); }
  53305. // Tell all child entities to play.
  53306. entities = this.getChildEntities();
  53307. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  53308. this.emit('play');
  53309. },
  53310. writable: true
  53311. },
  53312. /**
  53313. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  53314. * Tell all children entities to also pause.
  53315. */
  53316. pause: {
  53317. value: function () {
  53318. var entities;
  53319. var i;
  53320. var key;
  53321. if (!this.isPlaying) { return; }
  53322. this.isPlaying = false;
  53323. // Sleep all components.
  53324. for (key in this.components) { this.components[key].pause(); }
  53325. // Tell all child entities to pause.
  53326. entities = this.getChildEntities();
  53327. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  53328. this.emit('pause');
  53329. },
  53330. writable: true
  53331. },
  53332. /**
  53333. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  53334. *
  53335. * @param {string} attr
  53336. * @param {string} oldVal
  53337. * @param {string|object} newVal
  53338. */
  53339. setEntityAttribute: {
  53340. value: function (attr, oldVal, newVal) {
  53341. if (COMPONENTS[attr] || this.components[attr]) {
  53342. this.updateComponent(attr, newVal);
  53343. return;
  53344. }
  53345. if (attr === 'mixin') {
  53346. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  53347. if (newVal === this.computedMixinStr) { return; }
  53348. this.mixinUpdate(newVal, oldVal);
  53349. }
  53350. }
  53351. },
  53352. /**
  53353. * When mixins updated, trigger init or optimized-update of relevant components.
  53354. */
  53355. mixinUpdate: {
  53356. value: (function () {
  53357. var componentsUpdated = [];
  53358. return function (newMixins, oldMixins) {
  53359. var component;
  53360. var mixinEl;
  53361. var mixinIds;
  53362. var i;
  53363. var self = this;
  53364. if (!this.hasLoaded) {
  53365. this.addEventListener('loaded', function () {
  53366. self.mixinUpdate(newMixins, oldMixins);
  53367. }, ONCE);
  53368. return;
  53369. }
  53370. oldMixins = oldMixins || this.getAttribute('mixin');
  53371. mixinIds = this.updateMixins(newMixins, oldMixins);
  53372. // Loop over current mixins.
  53373. componentsUpdated.length = 0;
  53374. for (i = 0; i < this.mixinEls.length; i++) {
  53375. for (component in this.mixinEls[i].componentCache) {
  53376. if (componentsUpdated.indexOf(component) === -1) {
  53377. if (this.components[component]) {
  53378. // Update. Just rebuild data.
  53379. this.components[component].handleMixinUpdate();
  53380. } else {
  53381. // Init. buildData will gather mixin values.
  53382. this.initComponent(component, null);
  53383. }
  53384. componentsUpdated.push(component);
  53385. }
  53386. }
  53387. }
  53388. // Loop over old mixins to call for data rebuild.
  53389. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  53390. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  53391. if (!mixinEl) { continue; }
  53392. for (component in mixinEl.componentCache) {
  53393. if (componentsUpdated.indexOf(component) === -1) {
  53394. if (this.components[component]) {
  53395. if (this.getDOMAttribute(component)) {
  53396. // Update component if explicitly defined.
  53397. this.components[component].handleMixinUpdate();
  53398. } else {
  53399. // Remove component if not explicitly defined.
  53400. this.removeComponent(component, true);
  53401. }
  53402. }
  53403. }
  53404. }
  53405. }
  53406. };
  53407. })()
  53408. },
  53409. /**
  53410. * setAttribute can:
  53411. *
  53412. * 1. Set a single property of a multi-property component.
  53413. * 2. Set multiple properties of a multi-property component.
  53414. * 3. Replace properties of a multi-property component.
  53415. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  53416. *
  53417. * @param {string} attrName - Component or attribute name.
  53418. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  53419. * object of properties.
  53420. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  53421. * it is a boolean indicating whether to clobber previous values (defaults to false).
  53422. */
  53423. setAttribute: {
  53424. value: (function () {
  53425. var singlePropUpdate = {};
  53426. return function (attrName, arg1, arg2) {
  53427. var newAttrValue;
  53428. var clobber;
  53429. var componentName;
  53430. var delimiterIndex;
  53431. var isDebugMode;
  53432. var key;
  53433. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  53434. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  53435. // Not a component. Normal set attribute.
  53436. if (!COMPONENTS[componentName]) {
  53437. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  53438. ANode.prototype.setAttribute.call(this, attrName, arg1);
  53439. return;
  53440. }
  53441. // Initialize component first if not yet initialized.
  53442. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  53443. this.updateComponent(
  53444. attrName,
  53445. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  53446. }
  53447. // Determine new attributes from the arguments
  53448. if (typeof arg2 !== 'undefined' &&
  53449. typeof arg1 === 'string' &&
  53450. arg1.length > 0 &&
  53451. typeof utils.styleParser.parse(arg1) === 'string') {
  53452. // Update a single property of a multi-property component
  53453. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  53454. newAttrValue = singlePropUpdate;
  53455. newAttrValue[arg1] = arg2;
  53456. clobber = false;
  53457. } else {
  53458. // Update with a value, object, or CSS-style property string, with the possiblity
  53459. // of clobbering previous values.
  53460. newAttrValue = arg1;
  53461. clobber = (arg2 === true);
  53462. }
  53463. // Update component
  53464. this.updateComponent(attrName, newAttrValue, clobber);
  53465. // In debug mode, write component data up to the DOM.
  53466. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  53467. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  53468. };
  53469. })(),
  53470. writable: window.debug
  53471. },
  53472. /**
  53473. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  53474. *
  53475. * @param {bool} recursive - Also flushToDOM on the children.
  53476. **/
  53477. flushToDOM: {
  53478. value: function (recursive) {
  53479. var components = this.components;
  53480. var child;
  53481. var children = this.children;
  53482. var i;
  53483. var key;
  53484. // Flush entity's components to DOM.
  53485. for (key in components) {
  53486. components[key].flushToDOM();
  53487. }
  53488. // Recurse.
  53489. if (!recursive) { return; }
  53490. for (i = 0; i < children.length; ++i) {
  53491. child = children[i];
  53492. if (!child.flushToDOM) { continue; }
  53493. child.flushToDOM(recursive);
  53494. }
  53495. }
  53496. },
  53497. /**
  53498. * If `attr` is a component, returns ALL component data including applied mixins and
  53499. * defaults.
  53500. *
  53501. * If `attr` is not a component, fall back to HTML getAttribute.
  53502. *
  53503. * @param {string} attr
  53504. * @returns {object|string} Object if component, else string.
  53505. */
  53506. getAttribute: {
  53507. value: function (attr) {
  53508. // If component, return component data.
  53509. var component;
  53510. if (attr === 'position') { return this.object3D.position; }
  53511. if (attr === 'rotation') { return getRotation(this); }
  53512. if (attr === 'scale') { return this.object3D.scale; }
  53513. if (attr === 'visible') { return this.object3D.visible; }
  53514. component = this.components[attr];
  53515. if (component) { return component.data; }
  53516. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  53517. },
  53518. writable: window.debug
  53519. },
  53520. /**
  53521. * If `attr` is a component, returns JUST the component data defined on the entity.
  53522. * Like a partial version of `getComputedAttribute` as returned component data
  53523. * does not include applied mixins or defaults.
  53524. *
  53525. * If `attr` is not a component, fall back to HTML getAttribute.
  53526. *
  53527. * @param {string} attr
  53528. * @returns {object|string} Object if component, else string.
  53529. */
  53530. getDOMAttribute: {
  53531. value: function (attr) {
  53532. // If cached value exists, return partial component data.
  53533. var component = this.components[attr];
  53534. if (component) { return component.attrValue; }
  53535. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  53536. },
  53537. writable: window.debug
  53538. },
  53539. addState: {
  53540. value: function (state) {
  53541. if (this.is(state)) { return; }
  53542. this.states.push(state);
  53543. this.emit('stateadded', state);
  53544. }
  53545. },
  53546. removeState: {
  53547. value: function (state) {
  53548. var stateIndex = this.states.indexOf(state);
  53549. if (stateIndex === -1) { return; }
  53550. this.states.splice(stateIndex, 1);
  53551. this.emit('stateremoved', state);
  53552. }
  53553. },
  53554. /**
  53555. * Checks if the element is in a given state. e.g. el.is('alive');
  53556. * @type {string} state - Name of the state we want to check
  53557. */
  53558. is: {
  53559. value: function (state) {
  53560. return this.states.indexOf(state) !== -1;
  53561. }
  53562. },
  53563. /**
  53564. * Open Inspector to this entity.
  53565. */
  53566. inspect: {
  53567. value: function () {
  53568. this.sceneEl.components.inspector.openInspector(this);
  53569. }
  53570. },
  53571. /**
  53572. * Clean up memory and return memory to object pools.
  53573. */
  53574. destroy: {
  53575. value: function () {
  53576. var key;
  53577. if (this.parentNode) {
  53578. warn('Entity can only be destroyed if detached from scenegraph.');
  53579. return;
  53580. }
  53581. for (key in this.components) {
  53582. this.components[key].destroy();
  53583. }
  53584. }
  53585. }
  53586. });
  53587. /**
  53588. * Check if a component is *defined* for an entity, including defaults and mixins.
  53589. * Does not check whether the component has been *initialized* for an entity.
  53590. *
  53591. * @param {string} el - Entity.
  53592. * @param {string} name - Component name.
  53593. * @returns {boolean}
  53594. */
  53595. function checkComponentDefined (el, name) {
  53596. // Check if element contains the component.
  53597. if (el.components[name] && el.components[name].attrValue) { return true; }
  53598. return isComponentMixedIn(name, el.mixinEls);
  53599. }
  53600. /**
  53601. * Check if any mixins contains a component.
  53602. *
  53603. * @param {string} name - Component name.
  53604. * @param {array} mixinEls - Array of <a-mixin>s.
  53605. */
  53606. function isComponentMixedIn (name, mixinEls) {
  53607. var i;
  53608. var inMixin = false;
  53609. for (i = 0; i < mixinEls.length; ++i) {
  53610. inMixin = mixinEls[i].hasAttribute(name);
  53611. if (inMixin) { break; }
  53612. }
  53613. return inMixin;
  53614. }
  53615. /**
  53616. * Given entity defined value, merge in extra data if necessary.
  53617. * Handle both single and multi-property components.
  53618. *
  53619. * @param {string} attrValue - Entity data.
  53620. * @param extraData - Entity data from another source to merge in.
  53621. */
  53622. function mergeComponentData (attrValue, extraData) {
  53623. // Extra data not defined, just return attrValue.
  53624. if (!extraData) { return attrValue; }
  53625. // Merge multi-property data.
  53626. if (extraData.constructor === Object) {
  53627. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  53628. }
  53629. // Return data, precendence to the defined value.
  53630. return attrValue || extraData;
  53631. }
  53632. function isComponent (componentName) {
  53633. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  53634. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  53635. }
  53636. if (!COMPONENTS[componentName]) { return false; }
  53637. return true;
  53638. }
  53639. function getRotation (entityEl) {
  53640. var radToDeg = THREE.Math.radToDeg;
  53641. var rotation = entityEl.object3D.rotation;
  53642. var rotationObj = entityEl.rotationObj;
  53643. rotationObj.x = radToDeg(rotation.x);
  53644. rotationObj.y = radToDeg(rotation.y);
  53645. rotationObj.z = radToDeg(rotation.z);
  53646. return rotationObj;
  53647. }
  53648. AEntity = registerElement('a-entity', {prototype: proto});
  53649. module.exports = AEntity;
  53650. },{"../lib/three":177,"../utils/":203,"./a-node":127,"./a-register-element":128,"./component":129}],126:[function(_dereq_,module,exports){
  53651. var ANode = _dereq_('./a-node');
  53652. var registerElement = _dereq_('./a-register-element').registerElement;
  53653. var components = _dereq_('./component').components;
  53654. var utils = _dereq_('../utils');
  53655. var MULTIPLE_COMPONENT_DELIMITER = '__';
  53656. /**
  53657. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  53658. * are component names and the values are already parsed by the component.
  53659. */
  53660. module.exports = registerElement('a-mixin', {
  53661. prototype: Object.create(ANode.prototype, {
  53662. createdCallback: {
  53663. value: function () {
  53664. this.componentCache = {};
  53665. this.id = this.getAttribute('id');
  53666. this.isMixin = true;
  53667. }
  53668. },
  53669. attributeChangedCallback: {
  53670. value: function (attr, oldVal, newVal) {
  53671. this.cacheAttribute(attr, newVal);
  53672. this.updateEntities();
  53673. }
  53674. },
  53675. attachedCallback: {
  53676. value: function () {
  53677. this.sceneEl = this.closestScene();
  53678. this.cacheAttributes();
  53679. this.updateEntities();
  53680. this.load();
  53681. }
  53682. },
  53683. /**
  53684. * setAttribute that parses and caches component values.
  53685. */
  53686. setAttribute: {
  53687. value: function (attr, value) {
  53688. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  53689. this.cacheAttribute(attr, value);
  53690. }
  53691. },
  53692. /**
  53693. * If `attr` is a component, then parse the value using the schema and store it.
  53694. */
  53695. cacheAttribute: {
  53696. value: function (attr, value) {
  53697. var component;
  53698. var componentName;
  53699. // Get component data.
  53700. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  53701. component = components[componentName];
  53702. if (!component) { return; }
  53703. if (value === undefined) {
  53704. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  53705. }
  53706. this.componentCache[attr] = component.parseAttrValueForCache(value);
  53707. }
  53708. },
  53709. /**
  53710. * If `attr` is a component, then grab pre-parsed value from the cache.
  53711. * Else do a normal getAttribute.
  53712. */
  53713. getAttribute: {
  53714. value: function (attr) {
  53715. return this.componentCache[attr] ||
  53716. window.HTMLElement.prototype.getAttribute.call(this, attr);
  53717. }
  53718. },
  53719. /**
  53720. * Parse and cache every component defined on the mixin.
  53721. */
  53722. cacheAttributes: {
  53723. value: function () {
  53724. var attributes = this.attributes;
  53725. var attrName;
  53726. var i;
  53727. for (i = 0; i < attributes.length; i++) {
  53728. attrName = attributes[i].name;
  53729. this.cacheAttribute(attrName);
  53730. }
  53731. }
  53732. },
  53733. /**
  53734. * For entities that already have been loaded by the time the mixin was attached, tell
  53735. * those entities to register the mixin and refresh their component data.
  53736. */
  53737. updateEntities: {
  53738. value: function () {
  53739. var entity;
  53740. var entities;
  53741. var i;
  53742. if (!this.sceneEl) { return; }
  53743. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  53744. for (i = 0; i < entities.length; i++) {
  53745. entity = entities[i];
  53746. if (!entity.hasLoaded || entity.isMixin) { continue; }
  53747. entity.mixinUpdate(this.id);
  53748. }
  53749. }
  53750. }
  53751. })
  53752. });
  53753. },{"../utils":203,"./a-node":127,"./a-register-element":128,"./component":129}],127:[function(_dereq_,module,exports){
  53754. /* global CustomEvent */
  53755. var registerElement = _dereq_('./a-register-element').registerElement;
  53756. var isNode = _dereq_('./a-register-element').isNode;
  53757. var utils = _dereq_('../utils/');
  53758. var warn = utils.debug('core:a-node:warn');
  53759. var error = utils.debug('core:a-node:error');
  53760. /**
  53761. * Base class for A-Frame that manages loading of objects.
  53762. *
  53763. * Nodes can be modified using mixins.
  53764. * Nodes emit a `loaded` event when they and their children have initialized.
  53765. */
  53766. module.exports = registerElement('a-node', {
  53767. prototype: Object.create(window.HTMLElement.prototype, {
  53768. createdCallback: {
  53769. value: function () {
  53770. this.computedMixinStr = '';
  53771. this.hasLoaded = false;
  53772. this.isNode = true;
  53773. this.mixinEls = [];
  53774. },
  53775. writable: window.debug
  53776. },
  53777. attachedCallback: {
  53778. value: function () {
  53779. var mixins;
  53780. this.sceneEl = this.closestScene();
  53781. if (!this.sceneEl) {
  53782. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  53783. 'scene. Append this element to `<a-scene>` instead.');
  53784. }
  53785. this.hasLoaded = false;
  53786. this.emit('nodeready', undefined, false);
  53787. if (!this.isMixin) {
  53788. mixins = this.getAttribute('mixin');
  53789. if (mixins) { this.updateMixins(mixins); }
  53790. }
  53791. },
  53792. writable: window.debug
  53793. },
  53794. /**
  53795. * Handle mixin.
  53796. */
  53797. attributeChangedCallback: {
  53798. value: function (attr, oldVal, newVal) {
  53799. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  53800. if (newVal === this.computedMixinStr) { return; }
  53801. if (attr === 'mixin' && !this.isMixin) {
  53802. this.updateMixins(newVal, oldVal);
  53803. }
  53804. }
  53805. },
  53806. /**
  53807. * Returns the first scene by traversing up the tree starting from and
  53808. * including receiver element.
  53809. */
  53810. closestScene: {
  53811. value: function closest () {
  53812. var element = this;
  53813. while (element) {
  53814. if (element.isScene) { break; }
  53815. element = element.parentElement;
  53816. }
  53817. return element;
  53818. }
  53819. },
  53820. /**
  53821. * Returns first element matching a selector by traversing up the tree starting
  53822. * from and including receiver element.
  53823. *
  53824. * @param {string} selector - Selector of element to find.
  53825. */
  53826. closest: {
  53827. value: function closest (selector) {
  53828. var matches = this.matches || this.mozMatchesSelector ||
  53829. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  53830. var element = this;
  53831. while (element) {
  53832. if (matches.call(element, selector)) { break; }
  53833. element = element.parentElement;
  53834. }
  53835. return element;
  53836. }
  53837. },
  53838. detachedCallback: {
  53839. value: function () {
  53840. this.hasLoaded = false;
  53841. }
  53842. },
  53843. /**
  53844. * Wait for children to load, if any.
  53845. * Then emit `loaded` event and set `hasLoaded`.
  53846. */
  53847. load: {
  53848. value: function (cb, childFilter) {
  53849. var children;
  53850. var childrenLoaded;
  53851. var self = this;
  53852. if (this.hasLoaded) { return; }
  53853. // Default to waiting for all nodes.
  53854. childFilter = childFilter || isNode;
  53855. // Wait for children to load (if any), then load.
  53856. children = this.getChildren();
  53857. childrenLoaded = children.filter(childFilter).map(function (child) {
  53858. return new Promise(function waitForLoaded (resolve) {
  53859. if (child.hasLoaded) { return resolve(); }
  53860. child.addEventListener('loaded', resolve);
  53861. });
  53862. });
  53863. Promise.all(childrenLoaded).then(function emitLoaded () {
  53864. self.hasLoaded = true;
  53865. if (cb) { cb(); }
  53866. self.emit('loaded', undefined, false);
  53867. }).catch(function (err) {
  53868. error('Failure loading node: ', err);
  53869. });
  53870. },
  53871. writable: true
  53872. },
  53873. getChildren: {
  53874. value: function () {
  53875. return Array.prototype.slice.call(this.children, 0);
  53876. }
  53877. },
  53878. /**
  53879. * Unregister old mixins and listeners.
  53880. * Register new mixins and listeners.
  53881. * Registering means to update `this.mixinEls` with listeners.
  53882. */
  53883. updateMixins: {
  53884. value: (function () {
  53885. var newMixinIdArray = [];
  53886. var oldMixinIdArray = [];
  53887. var mixinIds = {};
  53888. return function (newMixins, oldMixins) {
  53889. var i;
  53890. var newMixinIds;
  53891. var oldMixinIds;
  53892. newMixinIdArray.length = 0;
  53893. oldMixinIdArray.length = 0;
  53894. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  53895. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  53896. mixinIds.newMixinIds = newMixinIds;
  53897. mixinIds.oldMixinIds = oldMixinIds;
  53898. // Unregister old mixins.
  53899. for (i = 0; i < oldMixinIds.length; i++) {
  53900. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  53901. this.unregisterMixin(oldMixinIds[i]);
  53902. }
  53903. }
  53904. // Register new mixins.
  53905. this.computedMixinStr = '';
  53906. this.mixinEls.length = 0;
  53907. for (i = 0; i < newMixinIds.length; i++) {
  53908. this.registerMixin(document.getElementById(newMixinIds[i]));
  53909. }
  53910. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  53911. // update.
  53912. if (this.computedMixinStr) {
  53913. this.computedMixinStr = this.computedMixinStr.trim();
  53914. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  53915. this.computedMixinStr);
  53916. }
  53917. return mixinIds;
  53918. };
  53919. })()
  53920. },
  53921. /**
  53922. * From mixin ID, add mixin element to `mixinEls`.
  53923. *
  53924. * @param {Element} mixinEl
  53925. */
  53926. registerMixin: {
  53927. value: function (mixinEl) {
  53928. var compositedMixinIds;
  53929. var i;
  53930. var mixin;
  53931. if (!mixinEl) { return; }
  53932. // Register composited mixins (if mixin has mixins).
  53933. mixin = mixinEl.getAttribute('mixin');
  53934. if (mixin) {
  53935. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  53936. for (i = 0; i < compositedMixinIds.length; i++) {
  53937. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  53938. }
  53939. }
  53940. // Register mixin.
  53941. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  53942. this.mixinEls.push(mixinEl);
  53943. }
  53944. },
  53945. setAttribute: {
  53946. value: function (attr, newValue) {
  53947. if (attr === 'mixin') { this.updateMixins(newValue); }
  53948. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  53949. }
  53950. },
  53951. unregisterMixin: {
  53952. value: function (mixinId) {
  53953. var i;
  53954. var mixinEls = this.mixinEls;
  53955. var mixinEl;
  53956. for (i = 0; i < mixinEls.length; ++i) {
  53957. mixinEl = mixinEls[i];
  53958. if (mixinId === mixinEl.id) {
  53959. mixinEls.splice(i, 1);
  53960. break;
  53961. }
  53962. }
  53963. }
  53964. },
  53965. /**
  53966. * Emit a DOM event.
  53967. *
  53968. * @param {string} name - Name of event.
  53969. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  53970. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  53971. * @param {object} [extraData] - Extra data to pass to the event, if any.
  53972. */
  53973. emit: {
  53974. value: (function () {
  53975. var data = {};
  53976. return function (name, detail, bubbles, extraData) {
  53977. if (bubbles === undefined) { bubbles = true; }
  53978. data.bubbles = !!bubbles;
  53979. data.detail = detail;
  53980. // If extra data is present, we need to create a new object.
  53981. if (extraData) { data = utils.extend({}, extraData, data); }
  53982. this.dispatchEvent(new CustomEvent(name, data));
  53983. };
  53984. })(),
  53985. writable: window.debug
  53986. }
  53987. })
  53988. });
  53989. },{"../utils/":203,"./a-register-element":128}],128:[function(_dereq_,module,exports){
  53990. /*
  53991. ------------------------------------------------------------
  53992. ------------- WARNING WARNING WARNING WARNING --------------
  53993. ------------------------------------------------------------
  53994. This module wraps registerElement to deal with components that inherit from
  53995. `ANode` and `AEntity`. It's a pass through in any other case.
  53996. It wraps some of the prototype methods of the created element to make sure
  53997. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  53998. are also invoked. The method in the base prototype is always called before the one
  53999. in the derived prototype.
  54000. */
  54001. // Polyfill `document.registerElement`.
  54002. _dereq_('document-register-element');
  54003. var ANode; // Must declare before AEntity. Initialized at the bottom.
  54004. var AEntity;
  54005. var knownTags = module.exports.knownTags = {};
  54006. function addTagName (tagName) {
  54007. knownTags[tagName.toLowerCase()] = true;
  54008. }
  54009. /**
  54010. * Return whether the element type is one of our known registered ones.
  54011. *
  54012. * @param {string} node - The name of the tag to register.
  54013. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  54014. */
  54015. module.exports.isNode = function (node) {
  54016. return node.tagName.toLowerCase() in knownTags || node.isNode;
  54017. };
  54018. /**
  54019. * @param {string} tagName - The name of the tag to register.
  54020. * @param {object} obj - The prototype of the new element.
  54021. * @returns {object} The prototype of the new element.
  54022. */
  54023. module.exports.registerElement = function (tagName, obj) {
  54024. var proto = Object.getPrototypeOf(obj.prototype);
  54025. var newObj = obj;
  54026. var isANode = ANode && proto === ANode.prototype;
  54027. var isAEntity = AEntity && proto === AEntity.prototype;
  54028. if (isANode || isAEntity) { addTagName(tagName); }
  54029. // Wrap if element inherits from `ANode`.
  54030. if (isANode) {
  54031. newObj = wrapANodeMethods(obj.prototype);
  54032. newObj = {prototype: Object.create(proto, newObj)};
  54033. }
  54034. // Wrap if element inherits from `AEntity`.
  54035. if (isAEntity) {
  54036. newObj = wrapAEntityMethods(obj.prototype);
  54037. newObj = {prototype: Object.create(proto, newObj)};
  54038. }
  54039. // Give all functions their proper name.
  54040. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  54041. var propVal = newObj.prototype[propName];
  54042. if (typeof propVal === 'function') {
  54043. propVal.displayName = propName;
  54044. }
  54045. });
  54046. return document.registerElement(tagName, newObj);
  54047. };
  54048. /**
  54049. * Wrap some obj methods to call those on `ANode` base prototype.
  54050. *
  54051. * @param {object} obj - Object that contains the methods that will be wrapped.
  54052. * @return {object} An object with the same properties as the input parameter but
  54053. * with some of methods wrapped.
  54054. */
  54055. function wrapANodeMethods (obj) {
  54056. var newObj = {};
  54057. var ANodeMethods = [
  54058. 'attachedCallback',
  54059. 'attributeChangedCallback',
  54060. 'createdCallback',
  54061. 'detachedCallback'
  54062. ];
  54063. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  54064. copyProperties(obj, newObj);
  54065. return newObj;
  54066. }
  54067. /**
  54068. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  54069. *
  54070. * @param {object} obj - The objects that contains the methods that will be wrapped.
  54071. * @return {object} - An object with the same properties as the input parameter but
  54072. * with some of methods wrapped.
  54073. */
  54074. function wrapAEntityMethods (obj) {
  54075. var newObj = {};
  54076. var ANodeMethods = [
  54077. 'attachedCallback',
  54078. 'attributeChangedCallback',
  54079. 'createdCallback',
  54080. 'detachedCallback'
  54081. ];
  54082. var AEntityMethods = [
  54083. 'attachedCallback',
  54084. 'attributeChangedCallback',
  54085. 'createdCallback',
  54086. 'detachedCallback'
  54087. ];
  54088. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  54089. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  54090. // Copies the remaining properties into the new object.
  54091. copyProperties(obj, newObj);
  54092. return newObj;
  54093. }
  54094. /**
  54095. * Wrap a list a methods to ensure that those in the base prototype are called
  54096. * before the derived one.
  54097. *
  54098. * @param {object} targetObj - Object that will contain the wrapped methods.
  54099. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  54100. * @param {object} derivedObject - Object that inherits from the baseObj.
  54101. * @param {object} baseObj - Object that derivedObj inherits from.
  54102. */
  54103. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  54104. methodList.forEach(function (methodName) {
  54105. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  54106. });
  54107. }
  54108. module.exports.wrapMethods = wrapMethods;
  54109. /**
  54110. * Wrap one method to ensure that the one in the base prototype is called before
  54111. * the one in the derived one.
  54112. *
  54113. * @param {object} obj - Object that will contain the wrapped method.
  54114. * @param {string} methodName - The name of the method that will be wrapped.
  54115. * @param {object} derivedObject - Object that inherits from the baseObj.
  54116. * @param {object} baseObj - Object that derivedObj inherits from.
  54117. */
  54118. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  54119. var derivedMethod = derivedObj[methodName];
  54120. var baseMethod = baseObj[methodName];
  54121. // Derived prototype does not define method, no need to wrap.
  54122. if (!derivedMethod || !baseMethod) { return; }
  54123. // Derived prototype doesn't override the one in the base one, no need to wrap.
  54124. if (derivedMethod === baseMethod) { return; }
  54125. // Wrap to ensure the base method is called before the one in the derived prototype.
  54126. obj[methodName] = {
  54127. value: function wrappedMethod () {
  54128. baseMethod.apply(this, arguments);
  54129. return derivedMethod.apply(this, arguments);
  54130. },
  54131. writable: window.debug
  54132. };
  54133. }
  54134. /**
  54135. * It copies the properties from source to destination object if they don't
  54136. * exist already.
  54137. *
  54138. * @param {object} source - The object where properties are copied from.
  54139. * @param {type} destination - The object where properties are copied to.
  54140. */
  54141. function copyProperties (source, destination) {
  54142. var props = Object.getOwnPropertyNames(source);
  54143. props.forEach(function (prop) {
  54144. var desc;
  54145. if (!destination[prop]) {
  54146. desc = Object.getOwnPropertyDescriptor(source, prop);
  54147. destination[prop] = {value: source[prop], writable: desc.writable};
  54148. }
  54149. });
  54150. }
  54151. ANode = _dereq_('./a-node');
  54152. AEntity = _dereq_('./a-entity');
  54153. },{"./a-entity":125,"./a-node":127,"document-register-element":12}],129:[function(_dereq_,module,exports){
  54154. /* global Node */
  54155. var schema = _dereq_('./schema');
  54156. var scenes = _dereq_('./scene/scenes');
  54157. var systems = _dereq_('./system');
  54158. var utils = _dereq_('../utils/');
  54159. var components = module.exports.components = {}; // Keep track of registered components.
  54160. var parseProperties = schema.parseProperties;
  54161. var parseProperty = schema.parseProperty;
  54162. var processSchema = schema.process;
  54163. var isSingleProp = schema.isSingleProperty;
  54164. var stringifyProperties = schema.stringifyProperties;
  54165. var stringifyProperty = schema.stringifyProperty;
  54166. var styleParser = utils.styleParser;
  54167. var warn = utils.debug('core:component:warn');
  54168. var aframeScript = document.currentScript;
  54169. var upperCaseRegExp = new RegExp('[A-Z]+');
  54170. // Object pools by component, created upon registration.
  54171. var objectPools = {};
  54172. /**
  54173. * Component class definition.
  54174. *
  54175. * Components configure appearance, modify behavior, or add functionality to
  54176. * entities. The behavior and appearance of an entity can be changed at runtime
  54177. * by adding, removing, or updating components. Entities do not share instances
  54178. * of components.
  54179. *
  54180. * @member {object} el - Reference to the entity element.
  54181. * @member {string} attrValue - Value of the corresponding HTML attribute.
  54182. * @member {object} data - Component data populated by parsing the
  54183. * mapped attribute of the component plus applying defaults and mixins.
  54184. */
  54185. var Component = module.exports.Component = function (el, attrValue, id) {
  54186. var self = this;
  54187. this.el = el;
  54188. this.id = id;
  54189. this.attrName = this.name + (id ? '__' + id : '');
  54190. this.evtDetail = {id: this.id, name: this.name};
  54191. this.initialized = false;
  54192. this.isSingleProperty = isSingleProp(this.schema);
  54193. this.isSinglePropertyObject = this.isSingleProperty &&
  54194. isObject(parseProperty(undefined, this.schema)) &&
  54195. !(this.schema.default instanceof window.HTMLElement);
  54196. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  54197. this.el.components[this.attrName] = this;
  54198. this.objectPool = objectPools[this.name];
  54199. const events = this.events;
  54200. this.events = {};
  54201. eventsBind(this, events);
  54202. // Store component data from previous update call.
  54203. this.attrValue = undefined;
  54204. if (this.isObjectBased) {
  54205. this.nextData = this.objectPool.use();
  54206. // Drop any properties added by dynamic schemas in previous use
  54207. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  54208. this.oldData = this.objectPool.use();
  54209. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  54210. this.previousOldData = this.objectPool.use();
  54211. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  54212. this.parsingAttrValue = this.objectPool.use();
  54213. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  54214. } else {
  54215. this.nextData = undefined;
  54216. this.oldData = undefined;
  54217. this.previousOldData = undefined;
  54218. this.parsingAttrValue = undefined;
  54219. }
  54220. // Last value passed to updateProperties.
  54221. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  54222. el.emit('componentchanged', self.evtDetail, false);
  54223. }, 200);
  54224. this.updateProperties(attrValue);
  54225. };
  54226. Component.prototype = {
  54227. /**
  54228. * Contains the type schema and defaults for the data values.
  54229. * Data is coerced into the types of the values of the defaults.
  54230. */
  54231. schema: {},
  54232. /**
  54233. * Init handler. Similar to attachedCallback.
  54234. * Called during component initialization and is only run once.
  54235. * Components can use this to set initial state.
  54236. */
  54237. init: function () { /* no-op */ },
  54238. /**
  54239. * Map of event names to binded event handlers that will be lifecycle-handled.
  54240. * Will be detached on pause / remove.
  54241. * Will be attached on play.
  54242. */
  54243. events: {},
  54244. /**
  54245. * Update handler. Similar to attributeChangedCallback.
  54246. * Called whenever component's data changes.
  54247. * Also called on component initialization when the component receives initial data.
  54248. *
  54249. * @param {object} prevData - Previous attributes of the component.
  54250. */
  54251. update: function (prevData) { /* no-op */ },
  54252. updateSchema: undefined,
  54253. /**
  54254. * Tick handler.
  54255. * Called on each tick of the scene render loop.
  54256. * Affected by play and pause.
  54257. *
  54258. * @param {number} time - Scene tick time.
  54259. * @param {number} timeDelta - Difference in current render time and previous render time.
  54260. */
  54261. tick: undefined,
  54262. /**
  54263. * Tock handler.
  54264. * Called on each tock of the scene render loop.
  54265. * Affected by play and pause.
  54266. *
  54267. * @param {number} time - Scene tick time.
  54268. * @param {number} timeDelta - Difference in current render time and previous render time.
  54269. * @param {object} camera - Camera used to render the last frame.
  54270. */
  54271. tock: undefined,
  54272. /**
  54273. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  54274. */
  54275. play: function () { /* no-op */ },
  54276. /**
  54277. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  54278. */
  54279. pause: function () { /* no-op */ },
  54280. /**
  54281. * Remove handler. Similar to detachedCallback.
  54282. * Called whenever component is removed from the entity (i.e., removeAttribute).
  54283. * Components can use this to reset behavior on the entity.
  54284. */
  54285. remove: function () { /* no-op */ },
  54286. /**
  54287. * Parses each property based on property type.
  54288. * If component is single-property, then parses the single property value.
  54289. *
  54290. * @param {string} value - HTML attribute value.
  54291. * @param {boolean} silent - Suppress warning messages.
  54292. * @returns {object} Component data.
  54293. */
  54294. parse: function (value, silent) {
  54295. var schema = this.schema;
  54296. if (this.isSingleProperty) { return parseProperty(value, schema); }
  54297. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  54298. },
  54299. /**
  54300. * Stringify properties if necessary.
  54301. *
  54302. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  54303. * value (e.g., selector, vec3 property types).
  54304. *
  54305. * @param {object} data - Complete component data.
  54306. * @returns {string}
  54307. */
  54308. stringify: function (data) {
  54309. var schema = this.schema;
  54310. if (typeof data === 'string') { return data; }
  54311. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  54312. data = stringifyProperties(data, schema);
  54313. return styleParser.stringify(data);
  54314. },
  54315. /**
  54316. * Update the cache of the pre-parsed attribute value.
  54317. *
  54318. * @param {string} value - New data.
  54319. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  54320. */
  54321. updateCachedAttrValue: function (value, clobber) {
  54322. var newAttrValue;
  54323. var tempObject;
  54324. var property;
  54325. if (value === undefined) { return; }
  54326. // If null value is the new attribute value, make the attribute value falsy.
  54327. if (value === null) {
  54328. if (this.isObjectBased && this.attrValue) {
  54329. this.objectPool.recycle(this.attrValue);
  54330. }
  54331. this.attrValue = undefined;
  54332. return;
  54333. }
  54334. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  54335. // If value is an object, copy it to our pooled newAttrValue object to use to update
  54336. // the attrValue.
  54337. tempObject = this.objectPool.use();
  54338. newAttrValue = utils.extend(tempObject, value);
  54339. } else {
  54340. newAttrValue = this.parseAttrValueForCache(value);
  54341. }
  54342. // Merge new data with previous `attrValue` if updating and not clobbering.
  54343. if (this.isObjectBased && !clobber && this.attrValue) {
  54344. for (property in this.attrValue) {
  54345. if (newAttrValue[property] === undefined) {
  54346. newAttrValue[property] = this.attrValue[property];
  54347. }
  54348. }
  54349. }
  54350. // Update attrValue.
  54351. if (this.isObjectBased && !this.attrValue) {
  54352. this.attrValue = this.objectPool.use();
  54353. }
  54354. utils.objectPool.clearObject(this.attrValue);
  54355. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  54356. utils.objectPool.clearObject(tempObject);
  54357. },
  54358. /**
  54359. * Given an HTML attribute value parses the string based on the component schema.
  54360. * To avoid double parsings of strings into strings we store the original instead
  54361. * of the parsed one
  54362. *
  54363. * @param {string} value - HTML attribute value
  54364. */
  54365. parseAttrValueForCache: function (value) {
  54366. var parsedValue;
  54367. if (typeof value !== 'string') { return value; }
  54368. if (this.isSingleProperty) {
  54369. parsedValue = this.schema.parse(value);
  54370. /**
  54371. * To avoid bogus double parsings. Cached values will be parsed when building
  54372. * component data. For instance when parsing a src id to its url, we want to cache
  54373. * original string and not the parsed one (#monster -> models/monster.dae)
  54374. * so when building data we parse the expected value.
  54375. */
  54376. if (typeof parsedValue === 'string') { parsedValue = value; }
  54377. } else {
  54378. // Parse using the style parser to avoid double parsing of individual properties.
  54379. utils.objectPool.clearObject(this.parsingAttrValue);
  54380. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  54381. }
  54382. return parsedValue;
  54383. },
  54384. /**
  54385. * Write cached attribute data to the entity DOM element.
  54386. *
  54387. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  54388. * default components.
  54389. */
  54390. flushToDOM: function (isDefault) {
  54391. var attrValue = isDefault ? this.data : this.attrValue;
  54392. if (attrValue === null || attrValue === undefined) { return; }
  54393. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  54394. this.stringify(attrValue));
  54395. },
  54396. /**
  54397. * Apply new component data if data has changed (from setAttribute).
  54398. *
  54399. * @param {string} attrValue - HTML attribute value.
  54400. * If undefined, use the cached attribute value and continue updating properties.
  54401. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  54402. */
  54403. updateProperties: function (attrValue, clobber) {
  54404. var el = this.el;
  54405. // Just cache the attribute if the entity has not loaded
  54406. // Components are not initialized until the entity has loaded
  54407. if (!el.hasLoaded) {
  54408. this.updateCachedAttrValue(attrValue);
  54409. return;
  54410. }
  54411. // Parse the attribute value.
  54412. // Cache current attrValue for future updates. Updates `this.attrValue`.
  54413. // `null` means no value on purpose, do not set a default value, let mixins take over.
  54414. if (attrValue !== null) {
  54415. attrValue = this.parseAttrValueForCache(attrValue);
  54416. }
  54417. // Cache current attrValue for future updates.
  54418. this.updateCachedAttrValue(attrValue, clobber);
  54419. if (this.initialized) {
  54420. this.updateComponent(attrValue, clobber);
  54421. this.callUpdateHandler();
  54422. } else {
  54423. this.initComponent();
  54424. }
  54425. },
  54426. initComponent: function () {
  54427. var el = this.el;
  54428. var initialOldData;
  54429. // Build data.
  54430. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  54431. this.data = this.buildData(this.attrValue);
  54432. // Component is being already initialized.
  54433. if (el.initializingComponents[this.name]) { return; }
  54434. // Prevent infinite loop in case of init method setting same component on the entity.
  54435. el.initializingComponents[this.name] = true;
  54436. // Initialize component.
  54437. this.init();
  54438. this.initialized = true;
  54439. delete el.initializingComponents[this.name];
  54440. // Store current data as previous data for future updates.
  54441. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  54442. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  54443. // Pass undefined to rest of types.
  54444. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  54445. this.update(initialOldData);
  54446. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  54447. // Play the component if the entity is playing.
  54448. if (el.isPlaying) { this.play(); }
  54449. el.emit('componentinitialized', this.evtDetail, false);
  54450. },
  54451. /**
  54452. * @param attrValue - Passed argument from setAttribute.
  54453. */
  54454. updateComponent: function (attrValue, clobber) {
  54455. var key;
  54456. var mayNeedSchemaUpdate;
  54457. if (clobber) {
  54458. // Clobber. Rebuild.
  54459. if (this.updateSchema) {
  54460. this.updateSchema(this.buildData(this.attrValue, true, true));
  54461. }
  54462. this.data = this.buildData(this.attrValue, true, false);
  54463. return;
  54464. }
  54465. // Apply new value to this.data in place since direct update.
  54466. if (this.isSingleProperty) {
  54467. if (this.isObjectBased) {
  54468. parseProperty(attrValue, this.schema);
  54469. }
  54470. // Single-property (already parsed).
  54471. this.data = attrValue;
  54472. return;
  54473. }
  54474. parseProperties(attrValue, this.schema, true, this.name);
  54475. // Check if we need to update schema.
  54476. if (this.schemaChangeKeys.length) {
  54477. for (key in attrValue) {
  54478. if (this.schema[key].schemaChange) {
  54479. mayNeedSchemaUpdate = true;
  54480. break;
  54481. }
  54482. }
  54483. }
  54484. if (mayNeedSchemaUpdate) {
  54485. // Rebuild data if need schema update.
  54486. if (this.updateSchema) {
  54487. this.updateSchema(this.buildData(this.attrValue, true, true));
  54488. }
  54489. this.data = this.buildData(this.attrValue, true, false);
  54490. return;
  54491. }
  54492. // Normal update.
  54493. for (key in attrValue) {
  54494. if (attrValue[key] === undefined) { continue; }
  54495. this.data[key] = attrValue[key];
  54496. }
  54497. },
  54498. /**
  54499. * Check if component should fire update and fire update lifecycle handler.
  54500. */
  54501. callUpdateHandler: function () {
  54502. var hasComponentChanged;
  54503. // Store the previous old data before we calculate the new oldData.
  54504. if (this.previousOldData instanceof Object) {
  54505. utils.objectPool.clearObject(this.previousOldData);
  54506. }
  54507. if (this.isObjectBased) {
  54508. copyData(this.previousOldData, this.oldData);
  54509. } else {
  54510. this.previousOldData = this.oldData;
  54511. }
  54512. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  54513. // Don't update if properties haven't changed.
  54514. // Always update rotation, position, scale.
  54515. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  54516. // Store current data as previous data for future updates.
  54517. // Reuse `this.oldData` object to try not to allocate another one.
  54518. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  54519. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  54520. // Update component with the previous old data.
  54521. this.update(this.previousOldData);
  54522. this.throttledEmitComponentChanged();
  54523. },
  54524. handleMixinUpdate: function () {
  54525. this.data = this.buildData(this.attrValue);
  54526. this.callUpdateHandler();
  54527. },
  54528. /**
  54529. * Reset value of a property to the property's default value.
  54530. * If single-prop component, reset value to component's default value.
  54531. *
  54532. * @param {string} propertyName - Name of property to reset.
  54533. */
  54534. resetProperty: function (propertyName) {
  54535. if (this.isObjectBased) {
  54536. if (!(propertyName in this.attrValue)) { return; }
  54537. delete this.attrValue[propertyName];
  54538. this.data[propertyName] = this.schema[propertyName].default;
  54539. } else {
  54540. this.attrValue = this.schema.default;
  54541. this.data = this.schema.default;
  54542. }
  54543. this.updateProperties(this.attrValue);
  54544. },
  54545. /**
  54546. * Extend schema of component given a partial schema.
  54547. *
  54548. * Some components might want to mutate their schema based on certain properties.
  54549. * e.g., Material component changes its schema based on `shader` to account for different
  54550. * uniforms
  54551. *
  54552. * @param {object} schemaAddon - Schema chunk that extend base schema.
  54553. */
  54554. extendSchema: function (schemaAddon) {
  54555. var extendedSchema;
  54556. // Clone base schema.
  54557. extendedSchema = utils.extend({}, components[this.name].schema);
  54558. // Extend base schema with new schema chunk.
  54559. utils.extend(extendedSchema, schemaAddon);
  54560. this.schema = processSchema(extendedSchema);
  54561. this.el.emit('schemachanged', this.evtDetail);
  54562. },
  54563. /**
  54564. * Build component data from the current state of the entity.data.
  54565. *
  54566. * Precedence:
  54567. * 1. Defaults data
  54568. * 2. Mixin data.
  54569. * 3. Attribute data.
  54570. *
  54571. * Finally coerce the data to the types of the defaults.
  54572. *
  54573. * @param {object} newData - Element new data.
  54574. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  54575. * @param {boolean} silent - Suppress warning messages.
  54576. * @return {object} The component data
  54577. */
  54578. buildData: function (newData, clobber, silent) {
  54579. var componentDefined;
  54580. var data;
  54581. var defaultValue;
  54582. var key;
  54583. var mixinData;
  54584. var nextData = this.nextData;
  54585. var schema = this.schema;
  54586. var i;
  54587. var mixinEls = this.el.mixinEls;
  54588. var previousData;
  54589. // Whether component has a defined value. For arrays, treat empty as not defined.
  54590. componentDefined = newData && newData.constructor === Array
  54591. ? newData.length
  54592. : newData !== undefined && newData !== null;
  54593. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  54594. // 1. Gather default values (lowest precendence).
  54595. if (this.isSingleProperty) {
  54596. if (this.isObjectBased) {
  54597. // If object-based single-prop, then copy over the data to our pooled object.
  54598. data = copyData(nextData, schema.default);
  54599. } else {
  54600. // If is plain single-prop, copy by value the default.
  54601. data = isObjectOrArray(schema.default)
  54602. ? utils.clone(schema.default)
  54603. : schema.default;
  54604. }
  54605. } else {
  54606. // Preserve previously set properties if clobber not enabled.
  54607. previousData = !clobber && this.attrValue;
  54608. // Clone default value if object so components don't share object
  54609. data = previousData instanceof Object
  54610. ? copyData(nextData, previousData)
  54611. : nextData;
  54612. // Apply defaults.
  54613. for (key in schema) {
  54614. defaultValue = schema[key].default;
  54615. if (data[key] !== undefined) { continue; }
  54616. // Clone default value if object so components don't share object
  54617. data[key] = isObjectOrArray(defaultValue)
  54618. ? utils.clone(defaultValue)
  54619. : defaultValue;
  54620. }
  54621. }
  54622. // 2. Gather mixin values.
  54623. for (i = 0; i < mixinEls.length; i++) {
  54624. mixinData = mixinEls[i].getAttribute(this.attrName);
  54625. if (!mixinData) { continue; }
  54626. data = extendProperties(data, mixinData, this.isObjectBased);
  54627. }
  54628. // 3. Gather attribute values (highest precendence).
  54629. if (componentDefined) {
  54630. if (this.isSingleProperty) {
  54631. // If object-based, copy the value to not modify the original.
  54632. if (isObject(newData)) {
  54633. copyData(this.parsingAttrValue, newData);
  54634. return parseProperty(this.parsingAttrValue, schema);
  54635. }
  54636. return parseProperty(newData, schema);
  54637. }
  54638. data = extendProperties(data, newData, this.isObjectBased);
  54639. } else {
  54640. // Parse and coerce using the schema.
  54641. if (this.isSingleProperty) { return parseProperty(data, schema); }
  54642. }
  54643. return parseProperties(data, schema, undefined, this.name, silent);
  54644. },
  54645. /**
  54646. * Attach events from component-defined events map.
  54647. */
  54648. eventsAttach: function () {
  54649. var eventName;
  54650. // Safety detach to prevent double-registration.
  54651. this.eventsDetach();
  54652. for (eventName in this.events) {
  54653. this.el.addEventListener(eventName, this.events[eventName]);
  54654. }
  54655. },
  54656. /**
  54657. * Detach events from component-defined events map.
  54658. */
  54659. eventsDetach: function () {
  54660. var eventName;
  54661. for (eventName in this.events) {
  54662. this.el.removeEventListener(eventName, this.events[eventName]);
  54663. }
  54664. },
  54665. /**
  54666. * Release and free memory.
  54667. */
  54668. destroy: function () {
  54669. this.objectPool.recycle(this.attrValue);
  54670. this.objectPool.recycle(this.oldData);
  54671. this.objectPool.recycle(this.parsingAttrValue);
  54672. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  54673. }
  54674. };
  54675. function eventsBind (component, events) {
  54676. var eventName;
  54677. for (eventName in events) {
  54678. component.events[eventName] = events[eventName].bind(component);
  54679. }
  54680. }
  54681. // For testing.
  54682. if (window.debug) {
  54683. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  54684. }
  54685. /**
  54686. * Register a component to A-Frame.
  54687. *
  54688. * @param {string} name - Component name.
  54689. * @param {object} definition - Component schema and lifecycle method handlers.
  54690. * @returns {object} Component.
  54691. */
  54692. module.exports.registerComponent = function (name, definition) {
  54693. var NewComponent;
  54694. var propertyName;
  54695. var proto = {};
  54696. var schema;
  54697. var schemaIsSingleProp;
  54698. // Warning if component is statically registered after the scene.
  54699. if (document.currentScript && document.currentScript !== aframeScript) {
  54700. scenes.forEach(function checkPosition (sceneEl) {
  54701. // Okay to register component after the scene at runtime.
  54702. if (sceneEl.hasLoaded) { return; }
  54703. // Check that component is declared before the scene.
  54704. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  54705. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  54706. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  54707. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  54708. 'such that the component is available to entities during scene initialization.');
  54709. // For testing.
  54710. if (window.debug) { registrationOrderWarnings[name] = true; }
  54711. });
  54712. }
  54713. if (upperCaseRegExp.test(name) === true) {
  54714. warn('The component name `' + name + '` contains uppercase characters, but ' +
  54715. 'HTML will ignore the capitalization of attribute names. ' +
  54716. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  54717. }
  54718. if (name.indexOf('__') !== -1) {
  54719. throw new Error('The component name `' + name + '` is not allowed. ' +
  54720. 'The sequence __ (double underscore) is reserved to specify an id' +
  54721. ' for multiple components of the same type');
  54722. }
  54723. // Format definition object to prototype object.
  54724. Object.keys(definition).forEach(function (key) {
  54725. proto[key] = {
  54726. value: definition[key],
  54727. writable: true
  54728. };
  54729. });
  54730. if (components[name]) {
  54731. throw new Error('The component `' + name + '` has been already registered. ' +
  54732. 'Check that you are not loading two versions of the same component ' +
  54733. 'or two different components of the same name.');
  54734. }
  54735. NewComponent = function (el, attr, id) {
  54736. Component.call(this, el, attr, id);
  54737. };
  54738. NewComponent.prototype = Object.create(Component.prototype, proto);
  54739. NewComponent.prototype.name = name;
  54740. NewComponent.prototype.isPositionRotationScale =
  54741. name === 'position' || name === 'rotation' || name === 'scale';
  54742. NewComponent.prototype.constructor = NewComponent;
  54743. NewComponent.prototype.system = systems && systems.systems[name];
  54744. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  54745. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  54746. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  54747. NewComponent.prototype.name));
  54748. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  54749. // Keep track of keys that may potentially change the schema.
  54750. if (!schemaIsSingleProp) {
  54751. NewComponent.prototype.schemaChangeKeys = [];
  54752. for (propertyName in schema) {
  54753. if (schema[propertyName].schemaChange) {
  54754. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  54755. }
  54756. }
  54757. }
  54758. // Create object pool for class of components.
  54759. objectPools[name] = utils.objectPool.createPool();
  54760. components[name] = {
  54761. Component: NewComponent,
  54762. dependencies: NewComponent.prototype.dependencies,
  54763. isSingleProp: schemaIsSingleProp,
  54764. multiple: NewComponent.prototype.multiple,
  54765. name: name,
  54766. parse: NewComponent.prototype.parse,
  54767. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  54768. schema: schema,
  54769. stringify: NewComponent.prototype.stringify,
  54770. type: NewComponent.prototype.type
  54771. };
  54772. return NewComponent;
  54773. };
  54774. /**
  54775. * Clone component data.
  54776. * Clone only the properties that are plain objects while keeping a reference for the rest.
  54777. *
  54778. * @param data - Component data to clone.
  54779. * @returns Cloned data.
  54780. */
  54781. function copyData (dest, sourceData) {
  54782. var parsedProperty;
  54783. var key;
  54784. for (key in sourceData) {
  54785. if (sourceData[key] === undefined) { continue; }
  54786. parsedProperty = sourceData[key];
  54787. dest[key] = isObjectOrArray(parsedProperty)
  54788. ? utils.clone(parsedProperty)
  54789. : parsedProperty;
  54790. }
  54791. return dest;
  54792. }
  54793. /**
  54794. * Object extending with checking for single-property schema.
  54795. *
  54796. * @param dest - Destination object or value.
  54797. * @param source - Source object or value
  54798. * @param {boolean} isObjectBased - Whether values are objects.
  54799. * @returns Overridden object or value.
  54800. */
  54801. function extendProperties (dest, source, isObjectBased) {
  54802. var key;
  54803. if (isObjectBased && source.constructor === Object) {
  54804. for (key in source) {
  54805. if (source[key] === undefined) { continue; }
  54806. if (source[key] && source[key].constructor === Object) {
  54807. dest[key] = utils.clone(source[key]);
  54808. } else {
  54809. dest[key] = source[key];
  54810. }
  54811. }
  54812. return dest;
  54813. }
  54814. return source;
  54815. }
  54816. /**
  54817. * Checks if a component has defined a method that needs to run every frame.
  54818. */
  54819. function hasBehavior (component) {
  54820. return component.tick || component.tock;
  54821. }
  54822. /**
  54823. * Wrapper for defined pause method.
  54824. * Pause component by removing tick behavior and calling user's pause method.
  54825. *
  54826. * @param pauseMethod {function}
  54827. */
  54828. function wrapPause (pauseMethod) {
  54829. return function pause () {
  54830. var sceneEl = this.el.sceneEl;
  54831. if (!this.isPlaying) { return; }
  54832. pauseMethod.call(this);
  54833. this.isPlaying = false;
  54834. this.eventsDetach();
  54835. // Remove tick behavior.
  54836. if (!hasBehavior(this)) { return; }
  54837. sceneEl.removeBehavior(this);
  54838. };
  54839. }
  54840. /**
  54841. * Wrapper for defined play method.
  54842. * Play component by adding tick behavior and calling user's play method.
  54843. *
  54844. * @param playMethod {function}
  54845. */
  54846. function wrapPlay (playMethod) {
  54847. return function play () {
  54848. var sceneEl = this.el.sceneEl;
  54849. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  54850. if (!this.initialized || !shouldPlay) { return; }
  54851. playMethod.call(this);
  54852. this.isPlaying = true;
  54853. this.eventsAttach();
  54854. // Add tick behavior.
  54855. if (!hasBehavior(this)) { return; }
  54856. sceneEl.addBehavior(this);
  54857. };
  54858. }
  54859. function isObject (value) {
  54860. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  54861. }
  54862. function isObjectOrArray (value) {
  54863. return value && (value.constructor === Object || value.constructor === Array) &&
  54864. !(value instanceof window.HTMLElement);
  54865. }
  54866. },{"../utils/":203,"./scene/scenes":136,"./schema":138,"./system":140}],130:[function(_dereq_,module,exports){
  54867. var schema = _dereq_('./schema');
  54868. var processSchema = schema.process;
  54869. var geometries = module.exports.geometries = {}; // Registered geometries.
  54870. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  54871. var THREE = _dereq_('../lib/three');
  54872. /**
  54873. * Geometry class definition.
  54874. *
  54875. * Geometries extend the geometry component API to create and register geometry types.
  54876. */
  54877. var Geometry = module.exports.Geometry = function () {};
  54878. Geometry.prototype = {
  54879. /**
  54880. * Contains the type schema and defaults for the data values.
  54881. * Data is coerced into the types of the values of the defaults.
  54882. */
  54883. schema: {},
  54884. /**
  54885. * Init handler. Similar to attachedCallback.
  54886. * Called during shader initialization and is only run once.
  54887. */
  54888. init: function (data) {
  54889. this.geometry = new THREE.Geometry();
  54890. return this.geometry;
  54891. },
  54892. /**
  54893. * Update handler. Similar to attributeChangedCallback.
  54894. * Called whenever the associated geometry data changes.
  54895. *
  54896. * @param {object} data - New geometry data.
  54897. */
  54898. update: function (data) { /* no-op */ }
  54899. };
  54900. /**
  54901. * Registers a geometry to A-Frame.
  54902. *
  54903. * @param {string} name - Geometry name.
  54904. * @param {object} definition - Geometry property and methods.
  54905. * @returns {object} Geometry.
  54906. */
  54907. module.exports.registerGeometry = function (name, definition) {
  54908. var NewGeometry;
  54909. var proto = {};
  54910. // Format definition object to prototype object.
  54911. Object.keys(definition).forEach(function expandDefinition (key) {
  54912. proto[key] = {
  54913. value: definition[key],
  54914. writable: true
  54915. };
  54916. });
  54917. if (geometries[name]) {
  54918. throw new Error('The geometry `' + name + '` has been already registered');
  54919. }
  54920. NewGeometry = function () { Geometry.call(this); };
  54921. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  54922. NewGeometry.prototype.name = name;
  54923. NewGeometry.prototype.constructor = NewGeometry;
  54924. geometries[name] = {
  54925. Geometry: NewGeometry,
  54926. schema: processSchema(NewGeometry.prototype.schema)
  54927. };
  54928. geometryNames.push(name);
  54929. return NewGeometry;
  54930. };
  54931. },{"../lib/three":177,"./schema":138}],131:[function(_dereq_,module,exports){
  54932. var coordinates = _dereq_('../utils/coordinates');
  54933. var debug = _dereq_('debug');
  54934. var error = debug('core:propertyTypes:warn');
  54935. var warn = debug('core:propertyTypes:warn');
  54936. var propertyTypes = module.exports.propertyTypes = {};
  54937. var nonCharRegex = /[,> .[\]:]/;
  54938. var urlRegex = /\url\((.+)\)/;
  54939. // Built-in property types.
  54940. registerPropertyType('audio', '', assetParse);
  54941. registerPropertyType('array', [], arrayParse, arrayStringify);
  54942. registerPropertyType('asset', '', assetParse);
  54943. registerPropertyType('boolean', false, boolParse);
  54944. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  54945. registerPropertyType('int', 0, intParse);
  54946. registerPropertyType('number', 0, numberParse);
  54947. registerPropertyType('map', '', assetParse);
  54948. registerPropertyType('model', '', assetParse);
  54949. registerPropertyType('selector', null, selectorParse, selectorStringify);
  54950. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  54951. registerPropertyType('src', '', srcParse);
  54952. registerPropertyType('string', '', defaultParse, defaultStringify);
  54953. registerPropertyType('time', 0, intParse);
  54954. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  54955. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  54956. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  54957. /**
  54958. * Register a parser for re-use such that when someone uses `type` in the schema,
  54959. * `schema.process` will set the property `parse` and `stringify`.
  54960. *
  54961. * @param {string} type - Type name.
  54962. * @param [defaultValue=null] -
  54963. * Default value to use if component does not define default value.
  54964. * @param {function} [parse=defaultParse] - Parse string function.
  54965. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  54966. */
  54967. function registerPropertyType (type, defaultValue, parse, stringify) {
  54968. if ('type' in propertyTypes) {
  54969. error('Property type ' + type + ' is already registered.');
  54970. return;
  54971. }
  54972. propertyTypes[type] = {
  54973. default: defaultValue,
  54974. parse: parse || defaultParse,
  54975. stringify: stringify || defaultStringify
  54976. };
  54977. }
  54978. module.exports.registerPropertyType = registerPropertyType;
  54979. function arrayParse (value) {
  54980. if (Array.isArray(value)) { return value; }
  54981. if (!value || typeof value !== 'string') { return []; }
  54982. return value.split(',').map(trim);
  54983. function trim (str) { return str.trim(); }
  54984. }
  54985. function arrayStringify (value) {
  54986. return value.join(', ');
  54987. }
  54988. /**
  54989. * For general assets.
  54990. *
  54991. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  54992. * just string.
  54993. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  54994. * just string.
  54995. */
  54996. function assetParse (value) {
  54997. var el;
  54998. var parsedUrl;
  54999. // If an element was provided (e.g. canvas or video), just return it.
  55000. if (typeof value !== 'string') { return value; }
  55001. // Wrapped `url()` in case of data URI.
  55002. parsedUrl = value.match(urlRegex);
  55003. if (parsedUrl) { return parsedUrl[1]; }
  55004. // ID.
  55005. if (value.charAt(0) === '#') {
  55006. el = document.getElementById(value.substring(1));
  55007. if (el) {
  55008. // Pass through media elements. If we have the elements, we don't have to call
  55009. // three.js loaders which would re-request the assets.
  55010. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  55011. return el;
  55012. }
  55013. return el.getAttribute('src');
  55014. }
  55015. warn('"' + value + '" asset not found.');
  55016. return;
  55017. }
  55018. // Non-wrapped url().
  55019. return value;
  55020. }
  55021. function defaultParse (value) {
  55022. return value;
  55023. }
  55024. function defaultStringify (value) {
  55025. if (value === null) { return 'null'; }
  55026. return value.toString();
  55027. }
  55028. function boolParse (value) {
  55029. return value !== 'false' && value !== false;
  55030. }
  55031. function intParse (value) {
  55032. return parseInt(value, 10);
  55033. }
  55034. function numberParse (value) {
  55035. return parseFloat(value, 10);
  55036. }
  55037. function selectorParse (value) {
  55038. if (!value) { return null; }
  55039. if (typeof value !== 'string') { return value; }
  55040. if (value[0] === '#' && !nonCharRegex.test(value)) {
  55041. // When selecting element by ID only, use getElementById for better performance.
  55042. // Don't match like #myId .child.
  55043. return document.getElementById(value.substring(1));
  55044. }
  55045. return document.querySelector(value);
  55046. }
  55047. function selectorAllParse (value) {
  55048. if (!value) { return null; }
  55049. if (typeof value !== 'string') { return value; }
  55050. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  55051. }
  55052. function selectorStringify (value) {
  55053. if (value.getAttribute) {
  55054. return '#' + value.getAttribute('id');
  55055. }
  55056. return defaultStringify(value);
  55057. }
  55058. function selectorAllStringify (value) {
  55059. if (value instanceof Array) {
  55060. return value.map(function (element) {
  55061. return '#' + element.getAttribute('id');
  55062. }).join(', ');
  55063. }
  55064. return defaultStringify(value);
  55065. }
  55066. function srcParse (value) {
  55067. warn('`src` property type is deprecated. Use `asset` instead.');
  55068. return assetParse(value);
  55069. }
  55070. function vecParse (value) {
  55071. return coordinates.parse(value, this.default);
  55072. }
  55073. /**
  55074. * Validate the default values in a schema to match their type.
  55075. *
  55076. * @param {string} type - Property type name.
  55077. * @param defaultVal - Property type default value.
  55078. * @returns {boolean} Whether default value is accurate given the type.
  55079. */
  55080. function isValidDefaultValue (type, defaultVal) {
  55081. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  55082. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  55083. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  55084. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  55085. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  55086. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  55087. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  55088. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  55089. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  55090. if (type === 'selector' && typeof defaultVal !== 'string' &&
  55091. defaultVal !== null) { return false; }
  55092. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  55093. defaultVal !== null) { return false; }
  55094. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  55095. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  55096. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  55097. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  55098. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  55099. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  55100. return true;
  55101. }
  55102. module.exports.isValidDefaultValue = isValidDefaultValue;
  55103. /**
  55104. * Checks if default coordinates are valid.
  55105. *
  55106. * @param possibleCoordinates
  55107. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  55108. * @returns {boolean} Whether coordinates are parsed correctly.
  55109. */
  55110. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  55111. if (possibleCoordinates === null) { return true; }
  55112. if (typeof possibleCoordinates !== 'object') { return false; }
  55113. if (Object.keys(possibleCoordinates).length !== dimensions) {
  55114. return false;
  55115. } else {
  55116. var x = possibleCoordinates.x;
  55117. var y = possibleCoordinates.y;
  55118. var z = possibleCoordinates.z;
  55119. var w = possibleCoordinates.w;
  55120. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  55121. if (dimensions > 2 && typeof z !== 'number') { return false; }
  55122. if (dimensions > 3 && typeof w !== 'number') { return false; }
  55123. }
  55124. return true;
  55125. }
  55126. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  55127. },{"../utils/coordinates":198,"debug":8}],132:[function(_dereq_,module,exports){
  55128. /* global Promise, screen, CustomEvent */
  55129. var initMetaTags = _dereq_('./metaTags').inject;
  55130. var initWakelock = _dereq_('./wakelock');
  55131. var loadingScreen = _dereq_('./loadingScreen');
  55132. var re = _dereq_('../a-register-element');
  55133. var scenes = _dereq_('./scenes');
  55134. var systems = _dereq_('../system').systems;
  55135. var THREE = _dereq_('../../lib/three');
  55136. var utils = _dereq_('../../utils/');
  55137. // Require after.
  55138. var AEntity = _dereq_('../a-entity');
  55139. var ANode = _dereq_('../a-node');
  55140. var initPostMessageAPI = _dereq_('./postMessage');
  55141. var bind = utils.bind;
  55142. var isIOS = utils.device.isIOS();
  55143. var isMobile = utils.device.isMobile();
  55144. var isWebXRAvailable = utils.device.isWebXRAvailable;
  55145. var registerElement = re.registerElement;
  55146. var warn = utils.debug('core:a-scene:warn');
  55147. /**
  55148. * Scene element, holds all entities.
  55149. *
  55150. * @member {array} behaviors - Component instances that have registered themselves to be
  55151. updated on every tick.
  55152. * @member {object} camera - three.js Camera object.
  55153. * @member {object} canvas
  55154. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  55155. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  55156. * @member {object} object3D - Root three.js Scene object.
  55157. * @member {object} renderer
  55158. * @member {bool} renderStarted
  55159. * @member {object} systems - Registered instantiated systems.
  55160. * @member {number} time
  55161. */
  55162. module.exports.AScene = registerElement('a-scene', {
  55163. prototype: Object.create(AEntity.prototype, {
  55164. createdCallback: {
  55165. value: function () {
  55166. this.clock = new THREE.Clock();
  55167. this.isIOS = isIOS;
  55168. this.isMobile = isMobile;
  55169. this.hasWebXR = isWebXRAvailable;
  55170. this.isAR = false;
  55171. this.isScene = true;
  55172. this.object3D = new THREE.Scene();
  55173. var self = this;
  55174. this.object3D.onAfterRender = function (renderer, scene, camera) {
  55175. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  55176. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  55177. };
  55178. this.resize = bind(this.resize, this);
  55179. this.render = bind(this.render, this);
  55180. this.systems = {};
  55181. this.systemNames = [];
  55182. this.time = this.delta = 0;
  55183. this.behaviors = {tick: [], tock: []};
  55184. this.hasLoaded = false;
  55185. this.isPlaying = false;
  55186. this.originalHTML = this.innerHTML;
  55187. // Default components.
  55188. this.setAttribute('inspector', '');
  55189. this.setAttribute('keyboard-shortcuts', '');
  55190. this.setAttribute('screenshot', '');
  55191. this.setAttribute('vr-mode-ui', '');
  55192. this.setAttribute('device-orientation-permission-ui', '');
  55193. }
  55194. },
  55195. addFullScreenStyles: {
  55196. value: function () {
  55197. document.documentElement.classList.add('a-fullscreen');
  55198. }
  55199. },
  55200. removeFullScreenStyles: {
  55201. value: function () {
  55202. document.documentElement.classList.remove('a-fullscreen');
  55203. }
  55204. },
  55205. attachedCallback: {
  55206. value: function () {
  55207. var self = this;
  55208. var embedded = this.hasAttribute('embedded');
  55209. // Renderer initialization
  55210. setupCanvas(this);
  55211. this.setupRenderer();
  55212. this.resize();
  55213. if (!embedded) { this.addFullScreenStyles(); }
  55214. initPostMessageAPI(this);
  55215. initMetaTags(this);
  55216. initWakelock(this);
  55217. // Handler to exit VR (e.g., Oculus Browser back button).
  55218. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  55219. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  55220. // Bind functions.
  55221. this.enterVRBound = function () { self.enterVR(); };
  55222. this.exitVRBound = function () { self.exitVR(); };
  55223. this.exitVRTrueBound = function () { self.exitVR(true); };
  55224. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  55225. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  55226. if (!isWebXRAvailable) {
  55227. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  55228. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  55229. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  55230. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  55231. // Register for mouse restricted events while in VR
  55232. // (e.g. mouse no longer available on desktop 2D view)
  55233. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  55234. // Register for mouse unrestricted events while in VR
  55235. // (e.g. mouse once again available on desktop 2D view)
  55236. window.addEventListener('vrdisplaypointerunrestricted',
  55237. this.pointerUnrestrictedBound);
  55238. }
  55239. window.addEventListener('sessionend', this.resize);
  55240. // Camera set up by camera system.
  55241. this.addEventListener('cameraready', function () {
  55242. self.attachedCallbackPostCamera();
  55243. });
  55244. this.initSystems();
  55245. }
  55246. },
  55247. attachedCallbackPostCamera: {
  55248. value: function () {
  55249. var resize;
  55250. var self = this;
  55251. window.addEventListener('load', resize);
  55252. window.addEventListener('resize', function () {
  55253. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  55254. // where the window does not contain the correct viewport size
  55255. // after an orientation change. The window size is correct if the operation
  55256. // is postponed a few milliseconds.
  55257. // self.resize can be called directly once the bug above is fixed.
  55258. if (self.isIOS) {
  55259. setTimeout(self.resize, 100);
  55260. } else {
  55261. self.resize();
  55262. }
  55263. });
  55264. this.play();
  55265. // Add to scene index.
  55266. scenes.push(this);
  55267. },
  55268. writable: window.debug
  55269. },
  55270. /**
  55271. * Initialize all systems.
  55272. */
  55273. initSystems: {
  55274. value: function () {
  55275. var name;
  55276. // Initialize camera system first.
  55277. this.initSystem('camera');
  55278. for (name in systems) {
  55279. if (name === 'camera') { continue; }
  55280. this.initSystem(name);
  55281. }
  55282. }
  55283. },
  55284. /**
  55285. * Initialize a system.
  55286. */
  55287. initSystem: {
  55288. value: function (name) {
  55289. if (this.systems[name]) { return; }
  55290. this.systems[name] = new systems[name](this);
  55291. this.systemNames.push(name);
  55292. }
  55293. },
  55294. /**
  55295. * Shut down scene on detach.
  55296. */
  55297. detachedCallback: {
  55298. value: function () {
  55299. // Remove from scene index.
  55300. var sceneIndex = scenes.indexOf(this);
  55301. scenes.splice(sceneIndex, 1);
  55302. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  55303. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  55304. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  55305. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  55306. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  55307. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  55308. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  55309. window.removeEventListener('sessionend', this.resize);
  55310. }
  55311. },
  55312. /**
  55313. * Add ticks and tocks.
  55314. *
  55315. * @param {object} behavior - A component.
  55316. */
  55317. addBehavior: {
  55318. value: function (behavior) {
  55319. var behaviorArr;
  55320. var behaviors = this.behaviors;
  55321. var behaviorType;
  55322. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  55323. for (behaviorType in behaviors) {
  55324. if (!behavior[behaviorType]) { continue; }
  55325. behaviorArr = this.behaviors[behaviorType];
  55326. if (behaviorArr.indexOf(behavior) === -1) {
  55327. behaviorArr.push(behavior);
  55328. }
  55329. }
  55330. }
  55331. },
  55332. /**
  55333. * For tests.
  55334. */
  55335. getPointerLockElement: {
  55336. value: function () {
  55337. return document.pointerLockElement;
  55338. },
  55339. writable: window.debug
  55340. },
  55341. /**
  55342. * For tests.
  55343. */
  55344. checkHeadsetConnected: {
  55345. value: utils.device.checkHeadsetConnected,
  55346. writable: window.debug
  55347. },
  55348. enterAR: {
  55349. value: function () {
  55350. if (!this.hasWebXR) {
  55351. throw new Error('Failed to enter AR mode, WebXR not supported.');
  55352. }
  55353. this.enterVR(true);
  55354. }
  55355. },
  55356. /**
  55357. * Call `requestPresent` if WebVR or WebVR polyfill.
  55358. * Call `requestFullscreen` on desktop.
  55359. * Handle events, states, fullscreen styles.
  55360. *
  55361. * @param {bool?} useAR - if true, try immersive-ar mode
  55362. * @returns {Promise}
  55363. */
  55364. enterVR: {
  55365. value: function (useAR) {
  55366. var self = this;
  55367. var vrDisplay;
  55368. var vrManager = self.renderer.xr;
  55369. // Don't enter VR if already in VR.
  55370. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  55371. // Has VR.
  55372. if (this.checkHeadsetConnected() || this.isMobile) {
  55373. vrManager.enabled = true;
  55374. if (this.hasWebXR) {
  55375. // XR API.
  55376. if (this.xrSession) {
  55377. this.xrSession.removeEventListener('end', this.exitVRBound);
  55378. }
  55379. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  55380. vrManager.setReferenceSpaceType(refspace);
  55381. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  55382. var xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  55383. navigator.xr.requestSession(xrMode, xrInit).then(
  55384. function requestSuccess (xrSession) {
  55385. self.xrSession = xrSession;
  55386. vrManager.setSession(xrSession);
  55387. xrSession.addEventListener('end', self.exitVRBound);
  55388. if (useAR) {
  55389. self.addState('ar-mode');
  55390. }
  55391. enterVRSuccess();
  55392. });
  55393. } else {
  55394. vrDisplay = utils.device.getVRDisplay();
  55395. vrManager.setDevice(vrDisplay);
  55396. if (vrDisplay.isPresenting &&
  55397. !window.hasNativeWebVRImplementation) {
  55398. enterVRSuccess();
  55399. return Promise.resolve();
  55400. }
  55401. var rendererSystem = this.getAttribute('renderer');
  55402. var presentationAttributes = {
  55403. highRefreshRate: rendererSystem.highRefreshRate,
  55404. foveationLevel: rendererSystem.foveationLevel
  55405. };
  55406. return vrDisplay.requestPresent([{
  55407. source: this.canvas,
  55408. attributes: presentationAttributes
  55409. }]).then(enterVRSuccess, enterVRFailure);
  55410. }
  55411. return Promise.resolve();
  55412. }
  55413. // No VR.
  55414. enterVRSuccess();
  55415. return Promise.resolve();
  55416. // Callback that happens on enter VR success or enter fullscreen (any API).
  55417. function enterVRSuccess () {
  55418. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  55419. // the first requestPresent could be called from ondisplayactivate and there is no way
  55420. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  55421. // for the actual requestPresent. Need to make sure there are no issues with firing the
  55422. // vrdisplaypresentchange multiple times.
  55423. var event;
  55424. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  55425. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  55426. window.dispatchEvent(event);
  55427. }
  55428. self.addState('vr-mode');
  55429. self.emit('enter-vr', {target: self});
  55430. // Lock to landscape orientation on mobile.
  55431. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  55432. screen.orientation.lock('landscape');
  55433. }
  55434. self.addFullScreenStyles();
  55435. // On mobile, the polyfill handles fullscreen.
  55436. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  55437. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  55438. // connected.
  55439. if (!self.isMobile && !self.checkHeadsetConnected()) {
  55440. requestFullscreen(self.canvas);
  55441. }
  55442. self.renderer.setAnimationLoop(self.render);
  55443. self.resize();
  55444. }
  55445. function enterVRFailure (err) {
  55446. if (err && err.message) {
  55447. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  55448. } else {
  55449. throw new Error('Failed to enter VR mode (`requestPresent`).');
  55450. }
  55451. }
  55452. },
  55453. writable: true
  55454. },
  55455. /**
  55456. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  55457. * Handle events, states, fullscreen styles.
  55458. *
  55459. * @returns {Promise}
  55460. */
  55461. exitVR: {
  55462. value: function () {
  55463. var self = this;
  55464. var vrDisplay;
  55465. var vrManager = this.renderer.xr;
  55466. // Don't exit VR if not in VR.
  55467. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  55468. // Handle exiting VR if not yet already and in a headset or polyfill.
  55469. if (this.checkHeadsetConnected() || this.isMobile) {
  55470. vrManager.enabled = false;
  55471. vrDisplay = utils.device.getVRDisplay();
  55472. if (this.hasWebXR) {
  55473. this.xrSession.removeEventListener('end', this.exitVRBound);
  55474. // Capture promise to avoid errors.
  55475. this.xrSession.end().then(function () {}, function () {});
  55476. this.xrSession = undefined;
  55477. vrManager.setSession(null);
  55478. } else {
  55479. if (vrDisplay.isPresenting) {
  55480. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  55481. }
  55482. }
  55483. } else {
  55484. exitFullscreen();
  55485. }
  55486. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  55487. exitVRSuccess();
  55488. return Promise.resolve();
  55489. function exitVRSuccess () {
  55490. self.removeState('vr-mode');
  55491. self.removeState('ar-mode');
  55492. // Lock to landscape orientation on mobile.
  55493. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  55494. screen.orientation.unlock();
  55495. }
  55496. // Exiting VR in embedded mode, no longer need fullscreen styles.
  55497. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  55498. self.resize();
  55499. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  55500. self.renderer.setPixelRatio(window.devicePixelRatio);
  55501. self.emit('exit-vr', {target: self});
  55502. }
  55503. function exitVRFailure (err) {
  55504. if (err && err.message) {
  55505. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  55506. } else {
  55507. throw new Error('Failed to exit VR mode (`exitPresent`).');
  55508. }
  55509. }
  55510. },
  55511. writable: true
  55512. },
  55513. pointerRestricted: {
  55514. value: function () {
  55515. if (this.canvas) {
  55516. var pointerLockElement = this.getPointerLockElement();
  55517. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  55518. // Recreate pointer lock on the canvas, if taken on another element.
  55519. document.exitPointerLock();
  55520. }
  55521. if (this.canvas.requestPointerLock) {
  55522. this.canvas.requestPointerLock();
  55523. }
  55524. }
  55525. }
  55526. },
  55527. pointerUnrestricted: {
  55528. value: function () {
  55529. var pointerLockElement = this.getPointerLockElement();
  55530. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  55531. document.exitPointerLock();
  55532. }
  55533. }
  55534. },
  55535. /**
  55536. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  55537. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  55538. */
  55539. onVRPresentChange: {
  55540. value: function (evt) {
  55541. // Polyfill places display inside the detail property
  55542. var display = evt.display || evt.detail.display;
  55543. // Entering VR.
  55544. if (display && display.isPresenting) {
  55545. this.enterVR();
  55546. return;
  55547. }
  55548. // Exiting VR.
  55549. this.exitVR();
  55550. }
  55551. },
  55552. /**
  55553. * Wraps Entity.getAttribute to take into account for systems.
  55554. * If system exists, then return system data rather than possible component data.
  55555. */
  55556. getAttribute: {
  55557. value: function (attr) {
  55558. var system = this.systems[attr];
  55559. if (system) { return system.data; }
  55560. return AEntity.prototype.getAttribute.call(this, attr);
  55561. }
  55562. },
  55563. /**
  55564. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  55565. * what `getAttribute` is now. Now legacy code.
  55566. */
  55567. getComputedAttribute: {
  55568. value: function (attr) {
  55569. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  55570. this.getAttribute(attr);
  55571. }
  55572. },
  55573. /**
  55574. * Wraps Entity.getDOMAttribute to take into account for systems.
  55575. * If system exists, then return system data rather than possible component data.
  55576. */
  55577. getDOMAttribute: {
  55578. value: function (attr) {
  55579. var system = this.systems[attr];
  55580. if (system) { return system.data; }
  55581. return AEntity.prototype.getDOMAttribute.call(this, attr);
  55582. }
  55583. },
  55584. /**
  55585. * Wrap Entity.setAttribute to take into account for systems.
  55586. * If system exists, then skip component initialization checks and do a normal
  55587. * setAttribute.
  55588. */
  55589. setAttribute: {
  55590. value: function (attr, value, componentPropValue) {
  55591. var system = this.systems[attr];
  55592. if (system) {
  55593. ANode.prototype.setAttribute.call(this, attr, value);
  55594. system.updateProperties(value);
  55595. return;
  55596. }
  55597. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  55598. }
  55599. },
  55600. /**
  55601. * @param {object} behavior - A component.
  55602. */
  55603. removeBehavior: {
  55604. value: function (behavior) {
  55605. var behaviorArr;
  55606. var behaviorType;
  55607. var behaviors = this.behaviors;
  55608. var index;
  55609. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  55610. // array.
  55611. for (behaviorType in behaviors) {
  55612. if (!behavior[behaviorType]) { continue; }
  55613. behaviorArr = this.behaviors[behaviorType];
  55614. index = behaviorArr.indexOf(behavior);
  55615. if (index !== -1) { behaviorArr.splice(index, 1); }
  55616. }
  55617. }
  55618. },
  55619. resize: {
  55620. value: function () {
  55621. var camera = this.camera;
  55622. var canvas = this.canvas;
  55623. var embedded;
  55624. var isVRPresenting;
  55625. var size;
  55626. var isPresenting = this.renderer.xr.isPresenting;
  55627. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  55628. // Do not update renderer, if a camera or a canvas have not been injected.
  55629. // In VR mode, three handles canvas resize based on the dimensions returned by
  55630. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  55631. // the window size, therefore should not be overwritten with the window's width and
  55632. // height, // except when in fullscreen mode.
  55633. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  55634. return;
  55635. }
  55636. // Update camera.
  55637. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  55638. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  55639. camera.aspect = size.width / size.height;
  55640. camera.updateProjectionMatrix();
  55641. // Notify renderer of size change.
  55642. this.renderer.setSize(size.width, size.height, false);
  55643. this.emit('rendererresize', null, false);
  55644. },
  55645. writable: true
  55646. },
  55647. setupRenderer: {
  55648. value: function () {
  55649. var self = this;
  55650. var renderer;
  55651. var rendererAttr;
  55652. var rendererAttrString;
  55653. var rendererConfig;
  55654. rendererConfig = {
  55655. alpha: true,
  55656. antialias: !isMobile,
  55657. canvas: this.canvas,
  55658. logarithmicDepthBuffer: false,
  55659. powerPreference: 'high-performance'
  55660. };
  55661. this.maxCanvasSize = {height: 1920, width: 1920};
  55662. if (this.hasAttribute('renderer')) {
  55663. rendererAttrString = this.getAttribute('renderer');
  55664. rendererAttr = utils.styleParser.parse(rendererAttrString);
  55665. if (rendererAttr.precision) {
  55666. rendererConfig.precision = rendererAttr.precision + 'p';
  55667. }
  55668. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  55669. rendererConfig.antialias = rendererAttr.antialias === 'true';
  55670. }
  55671. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  55672. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  55673. }
  55674. if (rendererAttr.alpha) {
  55675. rendererConfig.alpha = rendererAttr.alpha === 'true';
  55676. }
  55677. this.maxCanvasSize = {
  55678. width: rendererAttr.maxCanvasWidth
  55679. ? parseInt(rendererAttr.maxCanvasWidth)
  55680. : this.maxCanvasSize.width,
  55681. height: rendererAttr.maxCanvasHeight
  55682. ? parseInt(rendererAttr.maxCanvasHeight)
  55683. : this.maxCanvasSize.height
  55684. };
  55685. }
  55686. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  55687. renderer.setPixelRatio(window.devicePixelRatio);
  55688. renderer.sortObjects = false;
  55689. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  55690. this.addEventListener('camera-set-active', function () {
  55691. renderer.xr.setPoseTarget(self.camera.el.object3D);
  55692. });
  55693. loadingScreen.setup(this, getCanvasSize);
  55694. },
  55695. writable: window.debug
  55696. },
  55697. /**
  55698. * Handler attached to elements to help scene know when to kick off.
  55699. * Scene waits for all entities to load.
  55700. */
  55701. play: {
  55702. value: function () {
  55703. var self = this;
  55704. var sceneEl = this;
  55705. if (this.renderStarted) {
  55706. AEntity.prototype.play.call(this);
  55707. return;
  55708. }
  55709. this.addEventListener('loaded', function () {
  55710. var renderer = this.renderer;
  55711. var vrDisplay;
  55712. var vrManager = this.renderer.xr;
  55713. AEntity.prototype.play.call(this); // .play() *before* render.
  55714. // WebXR Immersive navigation handler.
  55715. if (this.hasWebXR && navigator.xr && navigator.xr.addEventListener) {
  55716. navigator.xr.addEventListener('sessiongranted', function () { sceneEl.enterVR(); });
  55717. }
  55718. if (sceneEl.renderStarted) { return; }
  55719. sceneEl.resize();
  55720. // Kick off render loop.
  55721. if (sceneEl.renderer) {
  55722. if (window.performance) { window.performance.mark('render-started'); }
  55723. loadingScreen.remove();
  55724. vrDisplay = utils.device.getVRDisplay();
  55725. if (vrDisplay && vrDisplay.isPresenting) {
  55726. vrManager.setDevice(vrDisplay);
  55727. vrManager.enabled = true;
  55728. sceneEl.enterVR();
  55729. }
  55730. renderer.setAnimationLoop(this.render);
  55731. sceneEl.renderStarted = true;
  55732. sceneEl.emit('renderstart');
  55733. }
  55734. });
  55735. // setTimeout to wait for all nodes to attach and run their callbacks.
  55736. setTimeout(function () {
  55737. AEntity.prototype.load.call(self);
  55738. });
  55739. }
  55740. },
  55741. /**
  55742. * Wrap `updateComponent` to not initialize the component if the component has a system
  55743. * (aframevr/aframe#2365).
  55744. */
  55745. updateComponent: {
  55746. value: function (componentName) {
  55747. if (componentName in systems) { return; }
  55748. AEntity.prototype.updateComponent.apply(this, arguments);
  55749. }
  55750. },
  55751. /**
  55752. * Behavior-updater meant to be called from scene render.
  55753. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  55754. * needing to render.
  55755. */
  55756. tick: {
  55757. value: function (time, timeDelta) {
  55758. var i;
  55759. var systems = this.systems;
  55760. // Components.
  55761. for (i = 0; i < this.behaviors.tick.length; i++) {
  55762. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  55763. this.behaviors.tick[i].tick(time, timeDelta);
  55764. }
  55765. // Systems.
  55766. for (i = 0; i < this.systemNames.length; i++) {
  55767. if (!systems[this.systemNames[i]].tick) { continue; }
  55768. systems[this.systemNames[i]].tick(time, timeDelta);
  55769. }
  55770. }
  55771. },
  55772. /**
  55773. * Behavior-updater meant to be called after scene render for post processing purposes.
  55774. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  55775. * needing to render.
  55776. */
  55777. tock: {
  55778. value: function (time, timeDelta, camera) {
  55779. var i;
  55780. var systems = this.systems;
  55781. // Components.
  55782. for (i = 0; i < this.behaviors.tock.length; i++) {
  55783. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  55784. this.behaviors.tock[i].tock(time, timeDelta, camera);
  55785. }
  55786. // Systems.
  55787. for (i = 0; i < this.systemNames.length; i++) {
  55788. if (!systems[this.systemNames[i]].tock) { continue; }
  55789. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  55790. }
  55791. }
  55792. },
  55793. /**
  55794. * The render loop.
  55795. *
  55796. * Updates animations.
  55797. * Updates behaviors.
  55798. * Renders with request animation frame.
  55799. */
  55800. render: {
  55801. value: function (time, frame) {
  55802. var renderer = this.renderer;
  55803. this.frame = frame;
  55804. this.delta = this.clock.getDelta() * 1000;
  55805. this.time = this.clock.elapsedTime * 1000;
  55806. if (this.isPlaying) { this.tick(this.time, this.delta); }
  55807. var savedBackground = null;
  55808. if (this.is('ar-mode')) {
  55809. // In AR mode, don't render the default background. Hide it, then
  55810. // restore it again after rendering.
  55811. savedBackground = this.object3D.background;
  55812. this.object3D.background = null;
  55813. }
  55814. renderer.render(this.object3D, this.camera);
  55815. if (savedBackground) {
  55816. this.object3D.background = savedBackground;
  55817. }
  55818. },
  55819. writable: true
  55820. }
  55821. })
  55822. });
  55823. /**
  55824. * Return the canvas size where the scene will be rendered.
  55825. * Will be always the window size except when the scene is embedded.
  55826. * The parent size (less than max size) will be returned in that case.
  55827. *
  55828. * @param {object} canvasEl - the canvas element
  55829. * @param {boolean} embedded - Is the scene embedded?
  55830. * @param {object} max - Max size parameters
  55831. * @param {boolean} isVR - If in VR
  55832. */
  55833. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  55834. if (embedded) {
  55835. return {
  55836. height: canvasEl.parentElement.offsetHeight,
  55837. width: canvasEl.parentElement.offsetWidth
  55838. };
  55839. }
  55840. return getMaxSize(maxSize, isVR);
  55841. }
  55842. /**
  55843. * Return the canvas size. Will be the window size unless that size is greater than the
  55844. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  55845. * maintaining aspect ratio
  55846. *
  55847. * @param {object} maxSize - Max size parameters (width and height).
  55848. * @param {boolean} isVR - If in VR.
  55849. * @returns {object} Width and height.
  55850. */
  55851. function getMaxSize (maxSize, isVR) {
  55852. var aspectRatio;
  55853. var size;
  55854. var pixelRatio = window.devicePixelRatio;
  55855. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  55856. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  55857. return size;
  55858. }
  55859. if (size.width * pixelRatio < maxSize.width &&
  55860. size.height * pixelRatio < maxSize.height) {
  55861. return size;
  55862. }
  55863. aspectRatio = size.width / size.height;
  55864. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  55865. size.width = Math.round(maxSize.width / pixelRatio);
  55866. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  55867. }
  55868. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  55869. size.height = Math.round(maxSize.height / pixelRatio);
  55870. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  55871. }
  55872. return size;
  55873. }
  55874. function requestFullscreen (canvas) {
  55875. var requestFullscreen =
  55876. canvas.requestFullscreen ||
  55877. canvas.webkitRequestFullscreen ||
  55878. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  55879. canvas.msRequestFullscreen;
  55880. // Hide navigation buttons on Android.
  55881. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  55882. }
  55883. function exitFullscreen () {
  55884. var fullscreenEl =
  55885. document.fullscreenElement ||
  55886. document.webkitFullscreenElement ||
  55887. document.mozFullScreenElement;
  55888. if (!fullscreenEl) { return; }
  55889. if (document.exitFullscreen) {
  55890. document.exitFullscreen();
  55891. } else if (document.mozCancelFullScreen) {
  55892. document.mozCancelFullScreen();
  55893. } else if (document.webkitExitFullscreen) {
  55894. document.webkitExitFullscreen();
  55895. }
  55896. }
  55897. function setupCanvas (sceneEl) {
  55898. var canvasEl;
  55899. canvasEl = document.createElement('canvas');
  55900. canvasEl.classList.add('a-canvas');
  55901. // Mark canvas as provided/injected by A-Frame.
  55902. canvasEl.dataset.aframeCanvas = true;
  55903. sceneEl.appendChild(canvasEl);
  55904. document.addEventListener('fullscreenchange', onFullScreenChange);
  55905. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  55906. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  55907. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  55908. // Prevent overscroll on mobile.
  55909. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  55910. // Set canvas on scene.
  55911. sceneEl.canvas = canvasEl;
  55912. sceneEl.emit('render-target-loaded', {target: canvasEl});
  55913. // For unknown reasons a synchronous resize does not work on desktop when
  55914. // entering/exiting fullscreen.
  55915. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  55916. function onFullScreenChange () {
  55917. var fullscreenEl =
  55918. document.fullscreenElement ||
  55919. document.mozFullScreenElement ||
  55920. document.webkitFullscreenElement;
  55921. // No fullscren element === exit fullscreen
  55922. if (!fullscreenEl) { sceneEl.exitVR(); }
  55923. document.activeElement.blur();
  55924. document.body.focus();
  55925. }
  55926. }
  55927. module.exports.setupCanvas = setupCanvas; // For testing.
  55928. },{"../../lib/three":177,"../../utils/":203,"../a-entity":125,"../a-node":127,"../a-register-element":128,"../system":140,"./loadingScreen":133,"./metaTags":134,"./postMessage":135,"./scenes":136,"./wakelock":137}],133:[function(_dereq_,module,exports){
  55929. /* global THREE */
  55930. var utils = _dereq_('../../utils/');
  55931. var styleParser = utils.styleParser;
  55932. var sceneEl;
  55933. var titleEl;
  55934. var getSceneCanvasSize;
  55935. var ATTR_NAME = 'loading-screen';
  55936. var LOADER_TITLE_CLASS = 'a-loader-title';
  55937. module.exports.setup = function setup (el, getCanvasSize) {
  55938. sceneEl = el;
  55939. getSceneCanvasSize = getCanvasSize;
  55940. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  55941. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  55942. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  55943. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  55944. var loaderScene;
  55945. var sphereGeometry;
  55946. var sphereMaterial;
  55947. var sphereMesh1;
  55948. var sphereMesh2;
  55949. var sphereMesh3;
  55950. var camera;
  55951. var clock;
  55952. var time;
  55953. var render;
  55954. if (!loaderEnabled) { return; }
  55955. // Setup Scene.
  55956. loaderScene = new THREE.Scene();
  55957. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  55958. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  55959. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  55960. sphereMesh2 = sphereMesh1.clone();
  55961. sphereMesh3 = sphereMesh1.clone();
  55962. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  55963. clock = new THREE.Clock();
  55964. time = 0;
  55965. render = function () {
  55966. sceneEl.renderer.render(loaderScene, camera);
  55967. time = clock.getElapsedTime() % 4;
  55968. sphereMesh1.visible = time >= 1;
  55969. sphereMesh2.visible = time >= 2;
  55970. sphereMesh3.visible = time >= 3;
  55971. };
  55972. loaderScene.background = new THREE.Color(backgroundColor);
  55973. loaderScene.add(camera);
  55974. sphereMesh1.position.set(-1, 0, -15);
  55975. sphereMesh2.position.set(0, 0, -15);
  55976. sphereMesh3.position.set(1, 0, -15);
  55977. camera.add(sphereMesh1);
  55978. camera.add(sphereMesh2);
  55979. camera.add(sphereMesh3);
  55980. setupTitle();
  55981. // Delay 200ms to avoid loader flashes.
  55982. setTimeout(function () {
  55983. if (sceneEl.hasLoaded) { return; }
  55984. resize(camera);
  55985. titleEl.style.display = 'block';
  55986. window.addEventListener('resize', function () { resize(camera); });
  55987. sceneEl.renderer.setAnimationLoop(render);
  55988. }, 200);
  55989. };
  55990. module.exports.remove = function remove () {
  55991. window.removeEventListener('resize', resize);
  55992. if (!titleEl) { return; }
  55993. // Hide title.
  55994. titleEl.style.display = 'none';
  55995. };
  55996. function resize (camera) {
  55997. var embedded = sceneEl.hasAttribute('embedded');
  55998. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  55999. camera.aspect = size.width / size.height;
  56000. camera.updateProjectionMatrix();
  56001. // Notify renderer of size change.
  56002. sceneEl.renderer.setSize(size.width, size.height, false);
  56003. }
  56004. function setupTitle () {
  56005. titleEl = document.createElement('div');
  56006. titleEl.className = LOADER_TITLE_CLASS;
  56007. titleEl.innerHTML = document.title;
  56008. titleEl.style.display = 'none';
  56009. sceneEl.appendChild(titleEl);
  56010. }
  56011. },{"../../utils/":203}],134:[function(_dereq_,module,exports){
  56012. var constants = _dereq_('../../constants/');
  56013. var extend = _dereq_('../../utils').extend;
  56014. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  56015. 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'}),
  56016. // W3C-standardised meta tags.
  56017. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  56018. Meta({name: 'theme-color', content: 'black'})
  56019. ];
  56020. var MOBILE_IOS_HEAD_TAGS = [
  56021. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  56022. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  56023. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  56024. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  56025. ];
  56026. function Meta (attrs) {
  56027. return {
  56028. tagName: 'meta',
  56029. attributes: attrs,
  56030. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  56031. };
  56032. }
  56033. function Link (attrs) {
  56034. return {
  56035. tagName: 'link',
  56036. attributes: attrs,
  56037. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  56038. };
  56039. }
  56040. /**
  56041. * Injects the necessary metatags in the document for mobile support:
  56042. * 1. Prevent the user to zoom in the document.
  56043. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  56044. * values and the canvas is properly scaled.
  56045. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  56046. * iOS.
  56047. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  56048. *
  56049. * @param {object} scene - Scene element
  56050. * @returns {Array}
  56051. */
  56052. module.exports.inject = function injectHeadTags (scene) {
  56053. var headEl = document.head;
  56054. var headScriptEl = headEl.querySelector('script');
  56055. var tag;
  56056. var headTags = [];
  56057. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  56058. if (scene.isIOS) {
  56059. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  56060. }
  56061. return headTags;
  56062. function createAndInjectTag (tagObj) {
  56063. if (!tagObj || tagObj.exists()) { return; }
  56064. tag = createTag(tagObj);
  56065. if (!tag) { return; }
  56066. if (headScriptEl) {
  56067. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  56068. } else {
  56069. headEl.appendChild(tag);
  56070. }
  56071. headTags.push(tag);
  56072. }
  56073. };
  56074. function createTag (tagObj) {
  56075. if (!tagObj || !tagObj.tagName) { return; }
  56076. var meta = document.createElement(tagObj.tagName);
  56077. meta.setAttribute(constants.AFRAME_INJECTED, '');
  56078. return extend(meta, tagObj.attributes);
  56079. }
  56080. },{"../../constants/":121,"../../utils":203}],135:[function(_dereq_,module,exports){
  56081. var bind = _dereq_('../../utils/bind');
  56082. var isIframed = _dereq_('../../utils/').isIframed;
  56083. /**
  56084. * Provides a post message API for scenes contained
  56085. * in an iframe.
  56086. */
  56087. module.exports = function initPostMessageAPI (scene) {
  56088. // Handles fullscreen behavior when inside an iframe.
  56089. if (!isIframed()) { return; }
  56090. // postMessage API handler
  56091. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  56092. };
  56093. function postMessageAPIHandler (event) {
  56094. var scene = this;
  56095. if (!event.data) { return; }
  56096. switch (event.data.type) {
  56097. case 'vr': {
  56098. switch (event.data.data) {
  56099. case 'enter':
  56100. scene.enterVR();
  56101. break;
  56102. case 'exit':
  56103. scene.exitVR();
  56104. break;
  56105. }
  56106. }
  56107. }
  56108. }
  56109. },{"../../utils/":203,"../../utils/bind":197}],136:[function(_dereq_,module,exports){
  56110. /*
  56111. Scene index for keeping track of created scenes.
  56112. */
  56113. module.exports = [];
  56114. },{}],137:[function(_dereq_,module,exports){
  56115. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  56116. module.exports = function initWakelock (scene) {
  56117. if (!scene.isMobile) { return; }
  56118. var wakelock = scene.wakelock = new Wakelock();
  56119. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  56120. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  56121. };
  56122. },{"../../../vendor/wakelock/wakelock":217}],138:[function(_dereq_,module,exports){
  56123. var utils = _dereq_('../utils/');
  56124. var PropertyTypes = _dereq_('./propertyTypes');
  56125. var debug = utils.debug;
  56126. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  56127. var propertyTypes = PropertyTypes.propertyTypes;
  56128. var warn = debug('core:schema:warn');
  56129. /**
  56130. * A schema is classified as a schema for a single property if:
  56131. * - `type` is defined on the schema as a string.
  56132. * - OR `default` is defined on the schema, as a reserved keyword.
  56133. * - OR schema is empty.
  56134. */
  56135. function isSingleProperty (schema) {
  56136. if ('type' in schema) {
  56137. return typeof schema.type === 'string';
  56138. }
  56139. return 'default' in schema;
  56140. }
  56141. module.exports.isSingleProperty = isSingleProperty;
  56142. /**
  56143. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  56144. *
  56145. * @param {object} schema
  56146. * @param {string} componentName
  56147. * @returns {object} Schema.
  56148. */
  56149. module.exports.process = function (schema, componentName) {
  56150. var propName;
  56151. // For single property schema, run processPropDefinition over the whole schema.
  56152. if (isSingleProperty(schema)) {
  56153. return processPropertyDefinition(schema, componentName);
  56154. }
  56155. // For multi-property schema, run processPropDefinition over each property definition.
  56156. for (propName in schema) {
  56157. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  56158. }
  56159. return schema;
  56160. };
  56161. /**
  56162. * Inject default value, parser, stringifier for single property.
  56163. *
  56164. * @param {object} propDefinition
  56165. * @param {string} componentName
  56166. */
  56167. function processPropertyDefinition (propDefinition, componentName) {
  56168. var defaultVal = propDefinition.default;
  56169. var isCustomType;
  56170. var propType;
  56171. var typeName = propDefinition.type;
  56172. // Type inference.
  56173. if (!propDefinition.type) {
  56174. if (defaultVal !== undefined &&
  56175. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  56176. // Type inference.
  56177. typeName = typeof defaultVal;
  56178. } else if (Array.isArray(defaultVal)) {
  56179. typeName = 'array';
  56180. } else {
  56181. // Fall back to string.
  56182. typeName = 'string';
  56183. }
  56184. } else if (propDefinition.type === 'bool') {
  56185. typeName = 'boolean';
  56186. } else if (propDefinition.type === 'float') {
  56187. typeName = 'number';
  56188. }
  56189. propType = propertyTypes[typeName];
  56190. if (!propType) {
  56191. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  56192. }
  56193. // Fill in parse and stringify using property types.
  56194. isCustomType = !!propDefinition.parse;
  56195. propDefinition.parse = propDefinition.parse || propType.parse;
  56196. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  56197. // Fill in type name.
  56198. propDefinition.type = typeName;
  56199. // Check that default value exists.
  56200. if ('default' in propDefinition) {
  56201. // Check that default values are valid.
  56202. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  56203. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  56204. '` in component `' + componentName + '`');
  56205. }
  56206. } else {
  56207. // Fill in default value.
  56208. propDefinition.default = propType.default;
  56209. }
  56210. return propDefinition;
  56211. }
  56212. module.exports.processPropertyDefinition = processPropertyDefinition;
  56213. /**
  56214. * Parse propData using schema. Use default values if not existing in propData.
  56215. *
  56216. * @param {object} propData - Unparsed properties.
  56217. * @param {object} schema - Property types definition.
  56218. * @param {boolean} getPartialData - Whether to return full component data or just the data
  56219. * with keys in `propData`.
  56220. * @param {string } componentName - Name of the component, used for the property warning.
  56221. * @param {boolean} silent - Suppress warning messages.
  56222. */
  56223. module.exports.parseProperties = (function () {
  56224. var propNames = [];
  56225. return function (propData, schema, getPartialData, componentName, silent) {
  56226. var i;
  56227. var propName;
  56228. var propDefinition;
  56229. var propValue;
  56230. propNames.length = 0;
  56231. for (propName in (getPartialData ? propData : schema)) {
  56232. if (getPartialData && propData[propName] === undefined) { continue; }
  56233. propNames.push(propName);
  56234. }
  56235. if (propData === null || typeof propData !== 'object') { return propData; }
  56236. // Validation errors.
  56237. for (propName in propData) {
  56238. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  56239. warn('Unknown property `' + propName +
  56240. '` for component/system `' + componentName + '`.');
  56241. }
  56242. }
  56243. for (i = 0; i < propNames.length; i++) {
  56244. propName = propNames[i];
  56245. propDefinition = schema[propName];
  56246. propValue = propData[propName];
  56247. if (!(schema[propName])) { return; }
  56248. propData[propName] = parseProperty(propValue, propDefinition);
  56249. }
  56250. return propData;
  56251. };
  56252. })();
  56253. /**
  56254. * Deserialize a single property.
  56255. */
  56256. function parseProperty (value, propDefinition) {
  56257. // Use default value if value is falsy.
  56258. if (value === undefined || value === null || value === '') {
  56259. value = propDefinition.default;
  56260. if (Array.isArray(value)) { value = value.slice(); }
  56261. }
  56262. // Invoke property type parser.
  56263. return propDefinition.parse(value, propDefinition.default);
  56264. }
  56265. module.exports.parseProperty = parseProperty;
  56266. /**
  56267. * Serialize a group of properties.
  56268. */
  56269. module.exports.stringifyProperties = function (propData, schema) {
  56270. var propName;
  56271. var propDefinition;
  56272. var propValue;
  56273. var stringifiedData = {};
  56274. var value;
  56275. for (propName in propData) {
  56276. propDefinition = schema[propName];
  56277. propValue = propData[propName];
  56278. value = propValue;
  56279. if (typeof value === 'object') {
  56280. value = stringifyProperty(propValue, propDefinition);
  56281. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  56282. }
  56283. stringifiedData[propName] = value;
  56284. }
  56285. return stringifiedData;
  56286. };
  56287. /**
  56288. * Serialize a single property.
  56289. */
  56290. function stringifyProperty (value, propDefinition) {
  56291. // This function stringifies but it's used in a context where
  56292. // there's always second stringification pass. By returning the original
  56293. // value when it's not an object we save one unnecessary call
  56294. // to JSON.stringify.
  56295. if (typeof value !== 'object') { return value; }
  56296. // if there's no schema for the property we use standar JSON stringify
  56297. if (!propDefinition || value === null) { return JSON.stringify(value); }
  56298. return propDefinition.stringify(value);
  56299. }
  56300. module.exports.stringifyProperty = stringifyProperty;
  56301. },{"../utils/":203,"./propertyTypes":131}],139:[function(_dereq_,module,exports){
  56302. var schema = _dereq_('./schema');
  56303. var processSchema = schema.process;
  56304. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  56305. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  56306. var THREE = _dereq_('../lib/three');
  56307. var utils = _dereq_('../utils');
  56308. // A-Frame properties to three.js uniform types.
  56309. var propertyToThreeMapping = {
  56310. array: 'v3',
  56311. color: 'v3',
  56312. int: 'i',
  56313. number: 'f',
  56314. map: 't',
  56315. time: 'f',
  56316. vec2: 'v2',
  56317. vec3: 'v3',
  56318. vec4: 'v4'
  56319. };
  56320. /**
  56321. * Shader class definition.
  56322. *
  56323. * Shaders extend the material component API so you can create your own library
  56324. * of customized materials
  56325. *
  56326. */
  56327. var Shader = module.exports.Shader = function () {};
  56328. Shader.prototype = {
  56329. /**
  56330. * Contains the type schema and defaults for the data values.
  56331. * Data is coerced into the types of the values of the defaults.
  56332. */
  56333. schema: {},
  56334. vertexShader:
  56335. 'void main() {' +
  56336. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  56337. '}',
  56338. fragmentShader:
  56339. 'void main() {' +
  56340. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  56341. '}',
  56342. /**
  56343. * Init handler. Similar to attachedCallback.
  56344. * Called during shader initialization and is only run once.
  56345. */
  56346. init: function (data) {
  56347. this.attributes = this.initVariables(data, 'attribute');
  56348. this.uniforms = this.initVariables(data, 'uniform');
  56349. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  56350. // attributes: this.attributes,
  56351. uniforms: this.uniforms,
  56352. vertexShader: this.vertexShader,
  56353. fragmentShader: this.fragmentShader
  56354. });
  56355. return this.material;
  56356. },
  56357. initVariables: function (data, type) {
  56358. var key;
  56359. var schema = this.schema;
  56360. var variables = {};
  56361. var varType;
  56362. for (key in schema) {
  56363. if (schema[key].is !== type) { continue; }
  56364. varType = propertyToThreeMapping[schema[key].type];
  56365. variables[key] = {
  56366. type: varType,
  56367. value: undefined // Let updateVariables handle setting these.
  56368. };
  56369. }
  56370. return variables;
  56371. },
  56372. /**
  56373. * Update handler. Similar to attributeChangedCallback.
  56374. * Called whenever the associated material data changes.
  56375. *
  56376. * @param {object} data - New material data.
  56377. */
  56378. update: function (data) {
  56379. this.updateVariables(data, 'attribute');
  56380. this.updateVariables(data, 'uniform');
  56381. },
  56382. updateVariables: function (data, type) {
  56383. var key;
  56384. var materialKey;
  56385. var schema = this.schema;
  56386. var variables;
  56387. variables = type === 'uniform' ? this.uniforms : this.attributes;
  56388. for (key in data) {
  56389. if (!schema[key] || schema[key].is !== type) { continue; }
  56390. if (schema[key].type === 'map') {
  56391. // If data unchanged, get out early.
  56392. if (!variables[key] || variables[key].value === data[key]) { continue; }
  56393. // Special handling is needed for textures.
  56394. materialKey = '_texture_' + key;
  56395. // We can't actually set the variable correctly until we've loaded the texture.
  56396. this.setMapOnTextureLoad(variables, key, materialKey);
  56397. // Kick off the texture update now that handler is added.
  56398. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  56399. continue;
  56400. }
  56401. variables[key].value = this.parseValue(schema[key].type, data[key]);
  56402. variables[key].needsUpdate = true;
  56403. }
  56404. },
  56405. parseValue: function (type, value) {
  56406. var color;
  56407. switch (type) {
  56408. case 'vec2': {
  56409. return new THREE.Vector2(value.x, value.y);
  56410. }
  56411. case 'vec3': {
  56412. return new THREE.Vector3(value.x, value.y, value.z);
  56413. }
  56414. case 'vec4': {
  56415. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  56416. }
  56417. case 'color': {
  56418. color = new THREE.Color(value);
  56419. return new THREE.Vector3(color.r, color.g, color.b);
  56420. }
  56421. case 'map': {
  56422. return THREE.ImageUtils.loadTexture(value);
  56423. }
  56424. default: {
  56425. return value;
  56426. }
  56427. }
  56428. },
  56429. setMapOnTextureLoad: function (variables, key, materialKey) {
  56430. var self = this;
  56431. this.el.addEventListener('materialtextureloaded', function () {
  56432. variables[key].value = self.material[materialKey];
  56433. variables[key].needsUpdate = true;
  56434. });
  56435. }
  56436. };
  56437. /**
  56438. * Registers a shader to A-Frame.
  56439. *
  56440. * @param {string} name - shader name.
  56441. * @param {object} definition - shader property and methods.
  56442. * @returns {object} Shader.
  56443. */
  56444. module.exports.registerShader = function (name, definition) {
  56445. var NewShader;
  56446. var proto = {};
  56447. // Format definition object to prototype object.
  56448. Object.keys(definition).forEach(function (key) {
  56449. proto[key] = {
  56450. value: definition[key],
  56451. writable: true
  56452. };
  56453. });
  56454. if (shaders[name]) {
  56455. throw new Error('The shader ' + name + ' has been already registered');
  56456. }
  56457. NewShader = function () { Shader.call(this); };
  56458. NewShader.prototype = Object.create(Shader.prototype, proto);
  56459. NewShader.prototype.name = name;
  56460. NewShader.prototype.constructor = NewShader;
  56461. shaders[name] = {
  56462. Shader: NewShader,
  56463. schema: processSchema(NewShader.prototype.schema)
  56464. };
  56465. shaderNames.push(name);
  56466. return NewShader;
  56467. };
  56468. },{"../lib/three":177,"../utils":203,"./schema":138}],140:[function(_dereq_,module,exports){
  56469. var components = _dereq_('./component');
  56470. var schema = _dereq_('./schema');
  56471. var utils = _dereq_('../utils/');
  56472. var parseProperties = schema.parseProperties;
  56473. var parseProperty = schema.parseProperty;
  56474. var processSchema = schema.process;
  56475. var isSingleProp = schema.isSingleProperty;
  56476. var styleParser = utils.styleParser;
  56477. var systems = module.exports.systems = {}; // Keep track of registered systems.
  56478. /**
  56479. * System class definition.
  56480. *
  56481. * Systems provide global scope and services to a group of instantiated components of the
  56482. * same class. They can also help abstract logic away from components such that components
  56483. * only have to worry about data.
  56484. *
  56485. * For example, a physics component that creates a physics world that oversees
  56486. * all entities with a physics or rigid body component.
  56487. *
  56488. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  56489. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  56490. * setAttribute behavior).
  56491. *
  56492. * @member {string} name - Name that system is registered under.
  56493. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  56494. */
  56495. var System = module.exports.System = function (sceneEl) {
  56496. var component = components && components.components[this.name];
  56497. // Set reference to scene.
  56498. this.el = sceneEl;
  56499. this.sceneEl = sceneEl;
  56500. // Set reference to matching component (if exists).
  56501. if (component) { component.Component.prototype.system = this; }
  56502. // Process system configuration.
  56503. this.buildData();
  56504. this.init();
  56505. this.update({});
  56506. };
  56507. System.prototype = {
  56508. /**
  56509. * Schema to configure system.
  56510. */
  56511. schema: {},
  56512. /**
  56513. * Init handler. Called during scene initialization and is only run once.
  56514. * Systems can use this to set initial state.
  56515. */
  56516. init: function () { /* no-op */ },
  56517. /**
  56518. * Update handler. Called during scene attribute updates.
  56519. * Systems can use this to dynamically update their state.
  56520. */
  56521. update: function (oldData) { /* no-op */ },
  56522. /**
  56523. * Build data and call update handler.
  56524. *
  56525. * @private
  56526. */
  56527. updateProperties: function (rawData) {
  56528. var oldData = this.data;
  56529. if (!Object.keys(schema).length) { return; }
  56530. this.buildData(rawData);
  56531. this.update(oldData);
  56532. },
  56533. /**
  56534. * Parse data.
  56535. */
  56536. buildData: function (rawData) {
  56537. var schema = this.schema;
  56538. if (!Object.keys(schema).length) { return; }
  56539. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  56540. if (isSingleProp(schema)) {
  56541. this.data = parseProperty(rawData, schema);
  56542. } else {
  56543. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  56544. }
  56545. },
  56546. /**
  56547. * Tick handler.
  56548. * Called on each tick of the scene render loop.
  56549. * Affected by play and pause.
  56550. *
  56551. * @param {number} time - Scene tick time.
  56552. * @param {number} timeDelta - Difference in current render time and previous render time.
  56553. */
  56554. tick: undefined,
  56555. /**
  56556. * Tock handler.
  56557. * Called on each tock of the scene render loop.
  56558. * Affected by play and pause.
  56559. *
  56560. * @param {number} time - Scene tick time.
  56561. * @param {number} timeDelta - Difference in current render time and previous render time.
  56562. */
  56563. tock: undefined,
  56564. /**
  56565. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  56566. */
  56567. play: function () { /* no-op */ },
  56568. /**
  56569. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  56570. */
  56571. pause: function () { /* no-op */ }
  56572. };
  56573. /**
  56574. * Registers a system to A-Frame.
  56575. *
  56576. * @param {string} name - Component name.
  56577. * @param {object} definition - Component property and methods.
  56578. * @returns {object} Component.
  56579. */
  56580. module.exports.registerSystem = function (name, definition) {
  56581. var i;
  56582. var NewSystem;
  56583. var proto = {};
  56584. var scenes = utils.findAllScenes(document);
  56585. // Format definition object to prototype object.
  56586. Object.keys(definition).forEach(function (key) {
  56587. proto[key] = {
  56588. value: definition[key],
  56589. writable: true
  56590. };
  56591. });
  56592. if (systems[name]) {
  56593. throw new Error('The system `' + name + '` has been already registered. ' +
  56594. 'Check that you are not loading two versions of the same system ' +
  56595. 'or two different systems of the same name.');
  56596. }
  56597. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  56598. NewSystem.prototype = Object.create(System.prototype, proto);
  56599. NewSystem.prototype.name = name;
  56600. NewSystem.prototype.constructor = NewSystem;
  56601. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  56602. systems[name] = NewSystem;
  56603. // Initialize systems for existing scenes
  56604. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  56605. };
  56606. },{"../utils/":203,"./component":129,"./schema":138}],141:[function(_dereq_,module,exports){
  56607. _dereq_('./pivot');
  56608. },{"./pivot":142}],142:[function(_dereq_,module,exports){
  56609. var registerComponent = _dereq_('../../core/component').registerComponent;
  56610. var THREE = _dereq_('../../lib/three');
  56611. var originalPosition = new THREE.Vector3();
  56612. var originalRotation = new THREE.Vector3();
  56613. /**
  56614. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  56615. */
  56616. registerComponent('pivot', {
  56617. dependencies: ['position'],
  56618. schema: {type: 'vec3'},
  56619. init: function () {
  56620. var data = this.data;
  56621. var el = this.el;
  56622. var originalParent = el.object3D.parent;
  56623. var originalGroup = el.object3D;
  56624. var outerGroup = new THREE.Group();
  56625. originalPosition.copy(originalGroup.position);
  56626. originalRotation.copy(originalGroup.rotation);
  56627. // Detach current group from parent.
  56628. originalParent.remove(originalGroup);
  56629. outerGroup.add(originalGroup);
  56630. // Set new group as the outer group.
  56631. originalParent.add(outerGroup);
  56632. // Set outer group as new object3D.
  56633. el.object3D = outerGroup;
  56634. // Apply pivot to original group.
  56635. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  56636. // Offset the pivot so that world position not affected.
  56637. // And restore position onto outer group.
  56638. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  56639. data.z + originalPosition.z);
  56640. // Transfer rotation to outer group.
  56641. outerGroup.rotation.copy(originalGroup.rotation);
  56642. originalGroup.rotation.set(0, 0, 0);
  56643. }
  56644. });
  56645. },{"../../core/component":129,"../../lib/three":177}],143:[function(_dereq_,module,exports){
  56646. /**
  56647. * Common mesh defaults, mappings, and transforms.
  56648. */
  56649. var components = _dereq_('../../core/component').components;
  56650. var shaders = _dereq_('../../core/shader').shaders;
  56651. var utils = _dereq_('../../utils/');
  56652. var materialMappings = {};
  56653. Object.keys(components.material.schema).forEach(addMapping);
  56654. Object.keys(shaders.standard.schema).forEach(addMapping);
  56655. function addMapping (prop) {
  56656. // To hyphenated.
  56657. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  56658. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  56659. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  56660. materialMappings[htmlAttrName] = 'material.' + prop;
  56661. }
  56662. module.exports = function getMeshMixin () {
  56663. return {
  56664. defaultComponents: {material: {}},
  56665. mappings: utils.extend({}, materialMappings)
  56666. };
  56667. };
  56668. },{"../../core/component":129,"../../core/shader":139,"../../utils/":203}],144:[function(_dereq_,module,exports){
  56669. _dereq_('./primitives/a-camera');
  56670. _dereq_('./primitives/a-cursor');
  56671. _dereq_('./primitives/a-curvedimage');
  56672. _dereq_('./primitives/a-gltf-model');
  56673. _dereq_('./primitives/a-image');
  56674. _dereq_('./primitives/a-light');
  56675. _dereq_('./primitives/a-link');
  56676. _dereq_('./primitives/a-obj-model');
  56677. _dereq_('./primitives/a-sky');
  56678. _dereq_('./primitives/a-sound');
  56679. _dereq_('./primitives/a-text');
  56680. _dereq_('./primitives/a-video');
  56681. _dereq_('./primitives/a-videosphere');
  56682. _dereq_('./primitives/meshPrimitives');
  56683. },{"./primitives/a-camera":146,"./primitives/a-cursor":147,"./primitives/a-curvedimage":148,"./primitives/a-gltf-model":149,"./primitives/a-image":150,"./primitives/a-light":151,"./primitives/a-link":152,"./primitives/a-obj-model":153,"./primitives/a-sky":154,"./primitives/a-sound":155,"./primitives/a-text":156,"./primitives/a-video":157,"./primitives/a-videosphere":158,"./primitives/meshPrimitives":159}],145:[function(_dereq_,module,exports){
  56684. var AEntity = _dereq_('../../core/a-entity');
  56685. var components = _dereq_('../../core/component').components;
  56686. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  56687. var utils = _dereq_('../../utils/');
  56688. var debug = utils.debug;
  56689. var setComponentProperty = utils.entity.setComponentProperty;
  56690. var log = debug('extras:primitives:debug');
  56691. var warn = debug('extras:primitives:warn');
  56692. var primitives = module.exports.primitives = {};
  56693. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  56694. name = name.toLowerCase();
  56695. log('Registering <%s>', name);
  56696. // Deprecation warning for defaultAttributes usage.
  56697. if (definition.defaultAttributes) {
  56698. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  56699. }
  56700. var primitive = registerElement(name, {
  56701. prototype: Object.create(AEntity.prototype, {
  56702. defaultComponentsFromPrimitive: {
  56703. value: definition.defaultComponents || definition.defaultAttributes || {}
  56704. },
  56705. deprecated: {value: definition.deprecated || null},
  56706. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  56707. mappings: {value: definition.mappings || {}},
  56708. createdCallback: {
  56709. value: function () {
  56710. if (definition.deprecated) { console.warn(definition.deprecated); }
  56711. this.resolveMappingCollisions();
  56712. }
  56713. },
  56714. /**
  56715. * If a mapping collides with a registered component name
  56716. * it renames the mapping to componentname-property
  56717. */
  56718. resolveMappingCollisions: {
  56719. value: function () {
  56720. var mappings = this.mappings;
  56721. var self = this;
  56722. Object.keys(mappings).forEach(function resolveCollision (key) {
  56723. var newAttribute;
  56724. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  56725. if (components[key]) {
  56726. newAttribute = mappings[key].replace('.', '-');
  56727. mappings[newAttribute] = mappings[key];
  56728. delete mappings[key];
  56729. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  56730. 'The attribute ' + key + ' has the same name as a registered component and' +
  56731. ' has been renamed to ' + newAttribute);
  56732. }
  56733. });
  56734. }
  56735. },
  56736. getExtraComponents: {
  56737. value: function () {
  56738. var attr;
  56739. var data;
  56740. var i;
  56741. var mapping;
  56742. var mixins;
  56743. var path;
  56744. var self = this;
  56745. // Gather component data from default components.
  56746. data = utils.clone(this.defaultComponentsFromPrimitive);
  56747. // Factor in mixins to overwrite default components.
  56748. mixins = this.getAttribute('mixin');
  56749. if (mixins) {
  56750. mixins = mixins.trim().split(' ');
  56751. mixins.forEach(function applyMixin (mixinId) {
  56752. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  56753. Object.keys(mixinComponents).forEach(function setComponent (name) {
  56754. data[name] = extend(data[name], mixinComponents[name]);
  56755. });
  56756. });
  56757. }
  56758. // Gather component data from mappings.
  56759. for (i = 0; i < this.attributes.length; i++) {
  56760. attr = this.attributes[i];
  56761. mapping = this.mappings[attr.name];
  56762. if (mapping) {
  56763. path = utils.entity.getComponentPropertyPath(mapping);
  56764. if (path.constructor === Array) {
  56765. data[path[0]] = data[path[0]] || {};
  56766. data[path[0]][path[1]] = attr.value.trim();
  56767. } else {
  56768. data[path] = attr.value.trim();
  56769. }
  56770. continue;
  56771. }
  56772. }
  56773. return data;
  56774. /**
  56775. * For the base to be extensible, both objects must be pure JavaScript objects.
  56776. * The function assumes that base is undefined, or null or a pure object.
  56777. */
  56778. function extend (base, extension) {
  56779. if (isUndefined(base)) {
  56780. return copy(extension);
  56781. }
  56782. if (isUndefined(extension)) {
  56783. return copy(base);
  56784. }
  56785. if (isPureObject(base) && isPureObject(extension)) {
  56786. return utils.extendDeep(base, extension);
  56787. }
  56788. return copy(extension);
  56789. }
  56790. function isUndefined (value) {
  56791. return typeof value === 'undefined';
  56792. }
  56793. function copy (value) {
  56794. if (isPureObject(value)) {
  56795. return utils.extendDeep({}, value);
  56796. }
  56797. return value;
  56798. }
  56799. function isPureObject (value) {
  56800. return value !== null && value.constructor === Object;
  56801. }
  56802. }
  56803. },
  56804. /**
  56805. * Sync to attribute to component property whenever mapped attribute changes.
  56806. * If attribute is mapped to a component property, set the component property using
  56807. * the attribute value.
  56808. */
  56809. attributeChangedCallback: {
  56810. value: function (attr, oldVal, value) {
  56811. var componentName = this.mappings[attr];
  56812. if (attr in this.deprecatedMappings) {
  56813. console.warn(this.deprecatedMappings[attr]);
  56814. }
  56815. if (!attr || !componentName) { return; }
  56816. // Set value.
  56817. setComponentProperty(this, componentName, value);
  56818. }
  56819. }
  56820. })
  56821. });
  56822. // Store.
  56823. primitives[name] = primitive;
  56824. return primitive;
  56825. };
  56826. /**
  56827. * Add component mappings using schema.
  56828. */
  56829. function addComponentMapping (componentName, mappings) {
  56830. var schema = components[componentName].schema;
  56831. Object.keys(schema).map(function (prop) {
  56832. // Hyphenate where there is camelCase.
  56833. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  56834. // If there is a mapping collision, prefix with component name and hyphen.
  56835. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  56836. mappings[attrName] = componentName + '.' + prop;
  56837. });
  56838. }
  56839. /**
  56840. * Helper to define a primitive, building mappings using a component schema.
  56841. */
  56842. function definePrimitive (tagName, defaultComponents, mappings) {
  56843. // If no initial mappings provided, start from empty map.
  56844. mappings = mappings || {};
  56845. // From the default components, add mapping automagically.
  56846. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  56847. addComponentMapping(componentName, mappings);
  56848. });
  56849. // Register the primitive.
  56850. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  56851. defaultComponents: defaultComponents,
  56852. mappings: mappings
  56853. }));
  56854. }
  56855. module.exports.definePrimitive = definePrimitive;
  56856. },{"../../core/a-entity":125,"../../core/a-register-element":128,"../../core/component":129,"../../utils/":203}],146:[function(_dereq_,module,exports){
  56857. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56858. registerPrimitive('a-camera', {
  56859. defaultComponents: {
  56860. 'camera': {},
  56861. 'look-controls': {},
  56862. 'wasd-controls': {},
  56863. 'position': {x: 0, y: 1.6, z: 0}
  56864. },
  56865. mappings: {
  56866. active: 'camera.active',
  56867. far: 'camera.far',
  56868. fov: 'camera.fov',
  56869. 'look-controls-enabled': 'look-controls.enabled',
  56870. near: 'camera.near',
  56871. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  56872. 'wasd-controls-enabled': 'wasd-controls.enabled',
  56873. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  56874. zoom: 'camera.zoom'
  56875. }
  56876. });
  56877. },{"../primitives":145}],147:[function(_dereq_,module,exports){
  56878. var getMeshMixin = _dereq_('../getMeshMixin');
  56879. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56880. var utils = _dereq_('../../../utils/');
  56881. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  56882. defaultComponents: {
  56883. cursor: {},
  56884. geometry: {
  56885. primitive: 'ring',
  56886. radiusOuter: 0.016,
  56887. radiusInner: 0.01,
  56888. segmentsTheta: 32
  56889. },
  56890. material: {
  56891. color: '#000',
  56892. shader: 'flat',
  56893. opacity: 0.8
  56894. },
  56895. position: {
  56896. x: 0,
  56897. y: 0,
  56898. z: -1
  56899. }
  56900. },
  56901. mappings: {
  56902. far: 'raycaster.far',
  56903. fuse: 'cursor.fuse',
  56904. 'fuse-timeout': 'cursor.fuseTimeout',
  56905. interval: 'raycaster.interval',
  56906. objects: 'raycaster.objects'
  56907. }
  56908. }));
  56909. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],148:[function(_dereq_,module,exports){
  56910. var getMeshMixin = _dereq_('../getMeshMixin');
  56911. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56912. var utils = _dereq_('../../../utils/');
  56913. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  56914. defaultComponents: {
  56915. geometry: {
  56916. height: 1,
  56917. primitive: 'cylinder',
  56918. radius: 2,
  56919. segmentsRadial: 48,
  56920. thetaLength: 270,
  56921. openEnded: true,
  56922. thetaStart: 0
  56923. },
  56924. material: {
  56925. color: '#FFF',
  56926. shader: 'flat',
  56927. side: 'double',
  56928. transparent: true,
  56929. repeat: '-1 1'
  56930. }
  56931. },
  56932. mappings: {
  56933. height: 'geometry.height',
  56934. 'open-ended': 'geometry.openEnded',
  56935. radius: 'geometry.radius',
  56936. segments: 'geometry.segmentsRadial',
  56937. start: 'geometry.thetaStart',
  56938. 'theta-length': 'geometry.thetaLength',
  56939. 'theta-start': 'geometry.thetaStart',
  56940. 'width': 'geometry.thetaLength'
  56941. }
  56942. }));
  56943. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],149:[function(_dereq_,module,exports){
  56944. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56945. registerPrimitive('a-gltf-model', {
  56946. mappings: {
  56947. src: 'gltf-model'
  56948. }
  56949. });
  56950. },{"../primitives":145}],150:[function(_dereq_,module,exports){
  56951. var getMeshMixin = _dereq_('../getMeshMixin');
  56952. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56953. var utils = _dereq_('../../../utils/');
  56954. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  56955. defaultComponents: {
  56956. geometry: {
  56957. primitive: 'plane'
  56958. },
  56959. material: {
  56960. color: '#FFF',
  56961. shader: 'flat',
  56962. side: 'double',
  56963. transparent: true
  56964. }
  56965. },
  56966. mappings: {
  56967. height: 'geometry.height',
  56968. width: 'geometry.width'
  56969. }
  56970. }));
  56971. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],151:[function(_dereq_,module,exports){
  56972. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56973. registerPrimitive('a-light', {
  56974. defaultComponents: {
  56975. light: {}
  56976. },
  56977. mappings: {
  56978. angle: 'light.angle',
  56979. color: 'light.color',
  56980. 'ground-color': 'light.groundColor',
  56981. decay: 'light.decay',
  56982. distance: 'light.distance',
  56983. intensity: 'light.intensity',
  56984. penumbra: 'light.penumbra',
  56985. type: 'light.type',
  56986. target: 'light.target'
  56987. }
  56988. });
  56989. },{"../primitives":145}],152:[function(_dereq_,module,exports){
  56990. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56991. registerPrimitive('a-link', {
  56992. defaultComponents: {
  56993. link: {
  56994. visualAspectEnabled: true
  56995. }
  56996. },
  56997. mappings: {
  56998. href: 'link.href',
  56999. image: 'link.image',
  57000. title: 'link.title'
  57001. }
  57002. });
  57003. },{"../primitives":145}],153:[function(_dereq_,module,exports){
  57004. var meshMixin = _dereq_('../getMeshMixin')();
  57005. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57006. var utils = _dereq_('../../../utils/');
  57007. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  57008. defaultComponents: {
  57009. 'obj-model': {}
  57010. },
  57011. mappings: {
  57012. src: 'obj-model.obj',
  57013. mtl: 'obj-model.mtl'
  57014. }
  57015. }));
  57016. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],154:[function(_dereq_,module,exports){
  57017. var getMeshMixin = _dereq_('../getMeshMixin');
  57018. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57019. var utils = _dereq_('../../../utils/');
  57020. var meshPrimitives = _dereq_('./meshPrimitives');
  57021. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  57022. defaultComponents: {
  57023. geometry: {
  57024. primitive: 'sphere',
  57025. radius: 500,
  57026. segmentsWidth: 64,
  57027. segmentsHeight: 32
  57028. },
  57029. material: {
  57030. color: '#FFF',
  57031. side: 'back',
  57032. shader: 'flat',
  57033. npot: true
  57034. },
  57035. scale: '-1 1 1'
  57036. },
  57037. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  57038. }));
  57039. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145,"./meshPrimitives":159}],155:[function(_dereq_,module,exports){
  57040. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57041. registerPrimitive('a-sound', {
  57042. defaultComponents: {
  57043. sound: {}
  57044. },
  57045. mappings: {
  57046. src: 'sound.src',
  57047. on: 'sound.on',
  57048. autoplay: 'sound.autoplay',
  57049. loop: 'sound.loop',
  57050. volume: 'sound.volume'
  57051. }
  57052. });
  57053. },{"../primitives":145}],156:[function(_dereq_,module,exports){
  57054. // <a-text> using `definePrimitive` helper.
  57055. var definePrimitive = _dereq_('../primitives').definePrimitive;
  57056. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  57057. },{"../primitives":145}],157:[function(_dereq_,module,exports){
  57058. var getMeshMixin = _dereq_('../getMeshMixin');
  57059. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57060. var utils = _dereq_('../../../utils/');
  57061. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  57062. defaultComponents: {
  57063. geometry: {
  57064. primitive: 'plane'
  57065. },
  57066. material: {
  57067. color: '#FFF',
  57068. shader: 'flat',
  57069. side: 'double',
  57070. transparent: true
  57071. }
  57072. },
  57073. mappings: {
  57074. height: 'geometry.height',
  57075. width: 'geometry.width'
  57076. }
  57077. }));
  57078. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],158:[function(_dereq_,module,exports){
  57079. var getMeshMixin = _dereq_('../getMeshMixin');
  57080. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57081. var utils = _dereq_('../../../utils/');
  57082. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  57083. defaultComponents: {
  57084. geometry: {
  57085. primitive: 'sphere',
  57086. radius: 500,
  57087. segmentsWidth: 64,
  57088. segmentsHeight: 32
  57089. },
  57090. material: {
  57091. color: '#FFF',
  57092. shader: 'flat',
  57093. side: 'back',
  57094. npot: true
  57095. },
  57096. scale: '-1 1 1'
  57097. },
  57098. mappings: {
  57099. radius: 'geometry.radius',
  57100. 'segments-height': 'geometry.segmentsHeight',
  57101. 'segments-width': 'geometry.segmentsWidth'
  57102. }
  57103. }));
  57104. },{"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],159:[function(_dereq_,module,exports){
  57105. /**
  57106. * Automated mesh primitive registration.
  57107. */
  57108. var getMeshMixin = _dereq_('../getMeshMixin');
  57109. var geometries = _dereq_('../../../core/geometry').geometries;
  57110. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  57111. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  57112. var utils = _dereq_('../../../utils/');
  57113. // For testing.
  57114. var meshPrimitives = module.exports = {};
  57115. // Generate primitive for each geometry type.
  57116. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  57117. var geometry = geometries[geometryName];
  57118. var geometryHyphened = unCamelCase(geometryName);
  57119. // Generate mappings.
  57120. var mappings = {};
  57121. Object.keys(geometry.schema).forEach(function createMapping (property) {
  57122. mappings[unCamelCase(property)] = 'geometry.' + property;
  57123. });
  57124. // Register.
  57125. var tagName = 'a-' + geometryHyphened;
  57126. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  57127. defaultComponents: {geometry: {primitive: geometryName}},
  57128. mappings: mappings
  57129. }));
  57130. meshPrimitives[tagName] = primitive;
  57131. });
  57132. /**
  57133. * camelCase to hyphened-string.
  57134. */
  57135. function unCamelCase (str) {
  57136. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  57137. }
  57138. },{"../../../core/geometry":130,"../../../utils/":203,"../getMeshMixin":143,"../primitives":145}],160:[function(_dereq_,module,exports){
  57139. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57140. var THREE = _dereq_('../lib/three');
  57141. registerGeometry('box', {
  57142. schema: {
  57143. depth: {default: 1, min: 0},
  57144. height: {default: 1, min: 0},
  57145. width: {default: 1, min: 0},
  57146. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  57147. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  57148. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  57149. },
  57150. init: function (data) {
  57151. this.geometry = new THREE.BoxGeometry(
  57152. data.width, data.height, data.depth,
  57153. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  57154. }
  57155. });
  57156. },{"../core/geometry":130,"../lib/three":177}],161:[function(_dereq_,module,exports){
  57157. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57158. var THREE = _dereq_('../lib/three');
  57159. var degToRad = THREE.Math.degToRad;
  57160. registerGeometry('circle', {
  57161. schema: {
  57162. radius: {default: 1, min: 0},
  57163. segments: {default: 32, min: 3, type: 'int'},
  57164. thetaLength: {default: 360, min: 0},
  57165. thetaStart: {default: 0}
  57166. },
  57167. init: function (data) {
  57168. this.geometry = new THREE.CircleGeometry(
  57169. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  57170. }
  57171. });
  57172. },{"../core/geometry":130,"../lib/three":177}],162:[function(_dereq_,module,exports){
  57173. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57174. var THREE = _dereq_('../lib/three');
  57175. var degToRad = THREE.Math.degToRad;
  57176. registerGeometry('cone', {
  57177. schema: {
  57178. height: {default: 1, min: 0},
  57179. openEnded: {default: false},
  57180. radiusBottom: {default: 1, min: 0},
  57181. radiusTop: {default: 0.01, min: 0},
  57182. segmentsHeight: {default: 18, min: 1, type: 'int'},
  57183. segmentsRadial: {default: 36, min: 3, type: 'int'},
  57184. thetaLength: {default: 360, min: 0},
  57185. thetaStart: {default: 0}
  57186. },
  57187. init: function (data) {
  57188. this.geometry = new THREE.CylinderGeometry(
  57189. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  57190. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  57191. degToRad(data.thetaLength));
  57192. }
  57193. });
  57194. },{"../core/geometry":130,"../lib/three":177}],163:[function(_dereq_,module,exports){
  57195. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57196. var THREE = _dereq_('../lib/three');
  57197. var degToRad = THREE.Math.degToRad;
  57198. registerGeometry('cylinder', {
  57199. schema: {
  57200. height: {default: 1, min: 0},
  57201. openEnded: {default: false},
  57202. radius: {default: 1, min: 0},
  57203. segmentsHeight: {default: 18, min: 1, type: 'int'},
  57204. segmentsRadial: {default: 36, min: 3, type: 'int'},
  57205. thetaLength: {default: 360, min: 0},
  57206. thetaStart: {default: 0}
  57207. },
  57208. init: function (data) {
  57209. this.geometry = new THREE.CylinderGeometry(
  57210. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  57211. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  57212. }
  57213. });
  57214. },{"../core/geometry":130,"../lib/three":177}],164:[function(_dereq_,module,exports){
  57215. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57216. var THREE = _dereq_('../lib/three');
  57217. registerGeometry('dodecahedron', {
  57218. schema: {
  57219. detail: {default: 0, min: 0, max: 5, type: 'int'},
  57220. radius: {default: 1, min: 0}
  57221. },
  57222. init: function (data) {
  57223. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  57224. }
  57225. });
  57226. },{"../core/geometry":130,"../lib/three":177}],165:[function(_dereq_,module,exports){
  57227. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57228. var THREE = _dereq_('../lib/three');
  57229. registerGeometry('icosahedron', {
  57230. schema: {
  57231. detail: {default: 0, min: 0, max: 5, type: 'int'},
  57232. radius: {default: 1, min: 0}
  57233. },
  57234. init: function (data) {
  57235. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  57236. }
  57237. });
  57238. },{"../core/geometry":130,"../lib/three":177}],166:[function(_dereq_,module,exports){
  57239. _dereq_('./box.js');
  57240. _dereq_('./circle.js');
  57241. _dereq_('./cone.js');
  57242. _dereq_('./cylinder.js');
  57243. _dereq_('./dodecahedron.js');
  57244. _dereq_('./icosahedron.js');
  57245. _dereq_('./octahedron.js');
  57246. _dereq_('./plane.js');
  57247. _dereq_('./ring.js');
  57248. _dereq_('./sphere.js');
  57249. _dereq_('./tetrahedron.js');
  57250. _dereq_('./torus.js');
  57251. _dereq_('./torusKnot.js');
  57252. _dereq_('./triangle.js');
  57253. },{"./box.js":160,"./circle.js":161,"./cone.js":162,"./cylinder.js":163,"./dodecahedron.js":164,"./icosahedron.js":165,"./octahedron.js":167,"./plane.js":168,"./ring.js":169,"./sphere.js":170,"./tetrahedron.js":171,"./torus.js":172,"./torusKnot.js":173,"./triangle.js":174}],167:[function(_dereq_,module,exports){
  57254. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57255. var THREE = _dereq_('../lib/three');
  57256. registerGeometry('octahedron', {
  57257. schema: {
  57258. detail: {default: 0, min: 0, max: 5, type: 'int'},
  57259. radius: {default: 1, min: 0}
  57260. },
  57261. init: function (data) {
  57262. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  57263. }
  57264. });
  57265. },{"../core/geometry":130,"../lib/three":177}],168:[function(_dereq_,module,exports){
  57266. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57267. var THREE = _dereq_('../lib/three');
  57268. registerGeometry('plane', {
  57269. schema: {
  57270. height: {default: 1, min: 0},
  57271. width: {default: 1, min: 0},
  57272. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  57273. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  57274. },
  57275. init: function (data) {
  57276. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  57277. }
  57278. });
  57279. },{"../core/geometry":130,"../lib/three":177}],169:[function(_dereq_,module,exports){
  57280. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57281. var THREE = _dereq_('../lib/three');
  57282. var degToRad = THREE.Math.degToRad;
  57283. registerGeometry('ring', {
  57284. schema: {
  57285. radiusInner: {default: 0.8, min: 0},
  57286. radiusOuter: {default: 1.2, min: 0},
  57287. segmentsPhi: {default: 10, min: 1, type: 'int'},
  57288. segmentsTheta: {default: 32, min: 3, type: 'int'},
  57289. thetaLength: {default: 360, min: 0},
  57290. thetaStart: {default: 0}
  57291. },
  57292. init: function (data) {
  57293. this.geometry = new THREE.RingGeometry(
  57294. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  57295. degToRad(data.thetaStart), degToRad(data.thetaLength));
  57296. }
  57297. });
  57298. },{"../core/geometry":130,"../lib/three":177}],170:[function(_dereq_,module,exports){
  57299. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57300. var THREE = _dereq_('../lib/three');
  57301. var degToRad = THREE.Math.degToRad;
  57302. registerGeometry('sphere', {
  57303. schema: {
  57304. radius: {default: 1, min: 0},
  57305. phiLength: {default: 360},
  57306. phiStart: {default: 0, min: 0},
  57307. thetaLength: {default: 180, min: 0},
  57308. thetaStart: {default: 0},
  57309. segmentsHeight: {default: 18, min: 2, type: 'int'},
  57310. segmentsWidth: {default: 36, min: 3, type: 'int'}
  57311. },
  57312. init: function (data) {
  57313. this.geometry = new THREE.SphereGeometry(
  57314. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  57315. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  57316. }
  57317. });
  57318. },{"../core/geometry":130,"../lib/three":177}],171:[function(_dereq_,module,exports){
  57319. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57320. var THREE = _dereq_('../lib/three');
  57321. registerGeometry('tetrahedron', {
  57322. schema: {
  57323. detail: {default: 0, min: 0, max: 5, type: 'int'},
  57324. radius: {default: 1, min: 0}
  57325. },
  57326. init: function (data) {
  57327. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  57328. }
  57329. });
  57330. },{"../core/geometry":130,"../lib/three":177}],172:[function(_dereq_,module,exports){
  57331. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57332. var THREE = _dereq_('../lib/three');
  57333. var degToRad = THREE.Math.degToRad;
  57334. registerGeometry('torus', {
  57335. schema: {
  57336. arc: {default: 360},
  57337. radius: {default: 1, min: 0},
  57338. radiusTubular: {default: 0.2, min: 0},
  57339. segmentsRadial: {default: 36, min: 2, type: 'int'},
  57340. segmentsTubular: {default: 32, min: 3, type: 'int'}
  57341. },
  57342. init: function (data) {
  57343. this.geometry = new THREE.TorusGeometry(
  57344. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  57345. degToRad(data.arc));
  57346. }
  57347. });
  57348. },{"../core/geometry":130,"../lib/three":177}],173:[function(_dereq_,module,exports){
  57349. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57350. var THREE = _dereq_('../lib/three');
  57351. registerGeometry('torusKnot', {
  57352. schema: {
  57353. p: {default: 2, min: 1},
  57354. q: {default: 3, min: 1},
  57355. radius: {default: 1, min: 0},
  57356. radiusTubular: {default: 0.2, min: 0},
  57357. segmentsRadial: {default: 8, min: 3, type: 'int'},
  57358. segmentsTubular: {default: 100, min: 3, type: 'int'}
  57359. },
  57360. init: function (data) {
  57361. this.geometry = new THREE.TorusKnotGeometry(
  57362. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  57363. data.p, data.q);
  57364. }
  57365. });
  57366. },{"../core/geometry":130,"../lib/three":177}],174:[function(_dereq_,module,exports){
  57367. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  57368. var THREE = _dereq_('../lib/three');
  57369. var quaternion = new THREE.Quaternion();
  57370. var rotateVector = new THREE.Vector3(0, 0, 1);
  57371. var uvMinVector = new THREE.Vector2();
  57372. var uvMaxVector = new THREE.Vector2();
  57373. var uvScaleVector = new THREE.Vector2();
  57374. registerGeometry('triangle', {
  57375. schema: {
  57376. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  57377. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  57378. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  57379. },
  57380. init: function (data) {
  57381. var geometry;
  57382. var normal;
  57383. var triangle;
  57384. var uvA;
  57385. var uvB;
  57386. var uvC;
  57387. triangle = new THREE.Triangle();
  57388. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  57389. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  57390. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  57391. normal = triangle.getNormal(new THREE.Vector3());
  57392. // Rotate the 3D triangle to be parallel to XY plane.
  57393. quaternion.setFromUnitVectors(normal, rotateVector);
  57394. uvA = triangle.a.clone().applyQuaternion(quaternion);
  57395. uvB = triangle.b.clone().applyQuaternion(quaternion);
  57396. uvC = triangle.c.clone().applyQuaternion(quaternion);
  57397. // Compute UVs.
  57398. // Normalize x/y values of UV so they are within 0 to 1.
  57399. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  57400. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  57401. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  57402. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  57403. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  57404. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  57405. geometry = this.geometry = new THREE.Geometry();
  57406. geometry.vertices.push(triangle.a);
  57407. geometry.vertices.push(triangle.b);
  57408. geometry.vertices.push(triangle.c);
  57409. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  57410. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  57411. }
  57412. });
  57413. },{"../core/geometry":130,"../lib/three":177}],175:[function(_dereq_,module,exports){
  57414. // Polyfill `Promise`.
  57415. window.Promise = window.Promise || _dereq_('promise-polyfill');
  57416. // WebVR polyfill
  57417. // Check before the polyfill runs.
  57418. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  57419. !!window.navigator.getVRDevices;
  57420. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  57421. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  57422. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  57423. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  57424. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  57425. // Only for iOS on versions older than 10.
  57426. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  57427. var WebVRPolyfill = _dereq_('webvr-polyfill');
  57428. var polyfillConfig = {
  57429. BUFFER_SCALE: bufferScale,
  57430. CARDBOARD_UI_DISABLED: true,
  57431. ROTATE_INSTRUCTIONS_DISABLED: true,
  57432. MOBILE_WAKE_LOCK: !!window.cordova
  57433. };
  57434. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  57435. }
  57436. var utils = _dereq_('./utils/');
  57437. var debug = utils.debug;
  57438. if (utils.isIE11) {
  57439. // Polyfill `CustomEvent`.
  57440. _dereq_('custom-event-polyfill');
  57441. // Polyfill String.startsWith.
  57442. _dereq_('../vendor/starts-with-polyfill');
  57443. }
  57444. var error = debug('A-Frame:error');
  57445. var warn = debug('A-Frame:warn');
  57446. if (window.document.currentScript && window.document.currentScript.parentNode !==
  57447. window.document.head && !window.debug) {
  57448. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  57449. 'ensure everything for A-Frame is properly registered before they are used from ' +
  57450. 'HTML.');
  57451. }
  57452. // Error if not using a server.
  57453. if (!window.cordova && window.location.protocol === 'file:') {
  57454. error(
  57455. 'This HTML file is currently being served via the file:// protocol. ' +
  57456. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  57457. 'Please use a local or hosted server: ' +
  57458. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  57459. }
  57460. _dereq_('present'); // Polyfill `performance.now()`.
  57461. // CSS.
  57462. if (utils.device.isBrowserEnvironment) {
  57463. _dereq_('./style/aframe.css');
  57464. _dereq_('./style/rStats.css');
  57465. }
  57466. // Required before `AEntity` so that all components are registered.
  57467. var AScene = _dereq_('./core/scene/a-scene').AScene;
  57468. var components = _dereq_('./core/component').components;
  57469. var registerComponent = _dereq_('./core/component').registerComponent;
  57470. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  57471. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  57472. var registerShader = _dereq_('./core/shader').registerShader;
  57473. var registerSystem = _dereq_('./core/system').registerSystem;
  57474. var shaders = _dereq_('./core/shader').shaders;
  57475. var systems = _dereq_('./core/system').systems;
  57476. // Exports THREE to window so three.js can be used without alteration.
  57477. var THREE = window.THREE = _dereq_('./lib/three');
  57478. var pkg = _dereq_('../package');
  57479. _dereq_('./components/index'); // Register standard components.
  57480. _dereq_('./geometries/index'); // Register standard geometries.
  57481. _dereq_('./shaders/index'); // Register standard shaders.
  57482. _dereq_('./systems/index'); // Register standard systems.
  57483. var ANode = _dereq_('./core/a-node');
  57484. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  57485. _dereq_('./core/a-assets');
  57486. _dereq_('./core/a-cubemap');
  57487. _dereq_('./core/a-mixin');
  57488. // Extras.
  57489. _dereq_('./extras/components/');
  57490. _dereq_('./extras/primitives/');
  57491. console.log('A-Frame Version: 1.0.4 (Date 2020-10-08, Commit #2d7bee0d)');
  57492. console.log('THREE Version (https://github.com/supermedium/three.js):',
  57493. pkg.dependencies['super-three']);
  57494. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  57495. module.exports = window.AFRAME = {
  57496. AComponent: _dereq_('./core/component').Component,
  57497. AEntity: AEntity,
  57498. ANode: ANode,
  57499. ANIME: _dereq_('super-animejs'),
  57500. AScene: AScene,
  57501. components: components,
  57502. coreComponents: Object.keys(components),
  57503. geometries: _dereq_('./core/geometry').geometries,
  57504. registerComponent: registerComponent,
  57505. registerElement: _dereq_('./core/a-register-element').registerElement,
  57506. registerGeometry: registerGeometry,
  57507. registerPrimitive: registerPrimitive,
  57508. registerShader: registerShader,
  57509. registerSystem: registerSystem,
  57510. primitives: {
  57511. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  57512. primitives: _dereq_('./extras/primitives/primitives').primitives
  57513. },
  57514. scenes: _dereq_('./core/scene/scenes'),
  57515. schema: _dereq_('./core/schema'),
  57516. shaders: shaders,
  57517. systems: systems,
  57518. THREE: THREE,
  57519. utils: utils,
  57520. version: pkg.version
  57521. };
  57522. },{"../package":72,"../vendor/starts-with-polyfill":215,"./components/index":83,"./core/a-assets":123,"./core/a-cubemap":124,"./core/a-entity":125,"./core/a-mixin":126,"./core/a-node":127,"./core/a-register-element":128,"./core/component":129,"./core/geometry":130,"./core/scene/a-scene":132,"./core/scene/scenes":136,"./core/schema":138,"./core/shader":139,"./core/system":140,"./extras/components/":141,"./extras/primitives/":144,"./extras/primitives/getMeshMixin":143,"./extras/primitives/primitives":145,"./geometries/index":166,"./lib/three":177,"./shaders/index":179,"./style/aframe.css":184,"./style/rStats.css":185,"./systems/index":189,"./utils/":203,"./utils/isIOSOlderThan10":205,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":67}],176:[function(_dereq_,module,exports){
  57523. window.aframeStats = function (scene) {
  57524. var _rS = null;
  57525. var _scene = scene;
  57526. var _values = {
  57527. te: {
  57528. caption: 'Entities'
  57529. },
  57530. lt: {
  57531. caption: 'Load Time'
  57532. }
  57533. };
  57534. var _groups = [ {
  57535. caption: 'A-Frame',
  57536. values: [ 'te', 'lt' ]
  57537. } ];
  57538. function _update () {
  57539. _rS('te').set(getEntityCount());
  57540. if (window.performance.getEntriesByName) {
  57541. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  57542. }
  57543. }
  57544. function getEntityCount () {
  57545. var elements = _scene.querySelectorAll('*');
  57546. Array.prototype.slice.call(elements).filter(function (el) {
  57547. return el.isEntity;
  57548. });
  57549. return elements.length;
  57550. }
  57551. function _start () {}
  57552. function _end () {}
  57553. function _attach (r) {
  57554. _rS = r;
  57555. }
  57556. return {
  57557. update: _update,
  57558. start: _start,
  57559. end: _end,
  57560. attach: _attach,
  57561. values: _values,
  57562. groups: _groups,
  57563. fractions: []
  57564. };
  57565. };
  57566. if (typeof module === 'object') {
  57567. module.exports = {
  57568. aframeStats: window.aframeStats
  57569. };
  57570. }
  57571. },{}],177:[function(_dereq_,module,exports){
  57572. (function (global){
  57573. var THREE = global.THREE = _dereq_('super-three');
  57574. // Allow cross-origin images to be loaded.
  57575. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  57576. // Must be on `THREE.TextureLoader`.
  57577. if (THREE.TextureLoader) {
  57578. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  57579. }
  57580. // This is for images loaded from the model loaders.
  57581. if (THREE.ImageLoader) {
  57582. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  57583. }
  57584. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  57585. if (THREE.Cache) {
  57586. THREE.Cache.enabled = true;
  57587. }
  57588. // TODO: Eventually include these only if they are needed by a component.
  57589. _dereq_('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  57590. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  57591. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  57592. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  57593. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  57594. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  57595. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  57596. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  57597. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  57598. module.exports = THREE;
  57599. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  57600. },{"../../vendor/DeviceOrientationControls":212,"super-three":57,"super-three/examples/js/loaders/DRACOLoader":58,"super-three/examples/js/loaders/GLTFLoader":59,"super-three/examples/js/loaders/MTLLoader":60,"super-three/examples/js/loaders/OBJLoader":61}],178:[function(_dereq_,module,exports){
  57601. var registerShader = _dereq_('../core/shader').registerShader;
  57602. var THREE = _dereq_('../lib/three');
  57603. var utils = _dereq_('../utils/');
  57604. /**
  57605. * Flat shader using THREE.MeshBasicMaterial.
  57606. */
  57607. module.exports.Shader = registerShader('flat', {
  57608. schema: {
  57609. color: {type: 'color'},
  57610. fog: {default: true},
  57611. height: {default: 256},
  57612. offset: {type: 'vec2', default: {x: 0, y: 0}},
  57613. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  57614. src: {type: 'map'},
  57615. width: {default: 512},
  57616. wireframe: {default: false},
  57617. wireframeLinewidth: {default: 2}
  57618. },
  57619. /**
  57620. * Initializes the shader.
  57621. * Adds a reference from the scene to this entity as the camera.
  57622. */
  57623. init: function (data) {
  57624. this.rendererSystem = this.el.sceneEl.systems.renderer;
  57625. this.materialData = {color: new THREE.Color()};
  57626. this.textureSrc = null;
  57627. getMaterialData(data, this.materialData);
  57628. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57629. this.material = new THREE.MeshBasicMaterial(this.materialData);
  57630. utils.material.updateMap(this, data);
  57631. },
  57632. update: function (data) {
  57633. this.updateMaterial(data);
  57634. utils.material.updateMap(this, data);
  57635. },
  57636. /**
  57637. * Updating existing material.
  57638. *
  57639. * @param {object} data - Material component data.
  57640. */
  57641. updateMaterial: function (data) {
  57642. var key;
  57643. getMaterialData(data, this.materialData);
  57644. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57645. for (key in this.materialData) {
  57646. this.material[key] = this.materialData[key];
  57647. }
  57648. }
  57649. });
  57650. /**
  57651. * Builds and normalize material data, normalizing stuff along the way.
  57652. *
  57653. * @param {object} data - Material data.
  57654. * @param {object} materialData - Object to reuse.
  57655. * @returns {object} Updated material data.
  57656. */
  57657. function getMaterialData (data, materialData) {
  57658. materialData.color.set(data.color);
  57659. materialData.fog = data.fog;
  57660. materialData.wireframe = data.wireframe;
  57661. materialData.wireframeLinewidth = data.wireframeLinewidth;
  57662. return materialData;
  57663. }
  57664. },{"../core/shader":139,"../lib/three":177,"../utils/":203}],179:[function(_dereq_,module,exports){
  57665. _dereq_('./flat');
  57666. _dereq_('./standard');
  57667. _dereq_('./sdf');
  57668. _dereq_('./msdf');
  57669. _dereq_('./ios10hls');
  57670. },{"./flat":178,"./ios10hls":180,"./msdf":181,"./sdf":182,"./standard":183}],180:[function(_dereq_,module,exports){
  57671. var registerShader = _dereq_('../core/shader').registerShader;
  57672. /**
  57673. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  57674. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  57675. */
  57676. module.exports.Shader = registerShader('ios10hls', {
  57677. schema: {
  57678. src: {type: 'map', is: 'uniform'},
  57679. opacity: {type: 'number', is: 'uniform', default: 1}
  57680. },
  57681. vertexShader: [
  57682. 'varying vec2 vUV;',
  57683. 'void main(void) {',
  57684. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57685. ' vUV = uv;',
  57686. '}'
  57687. ].join('\n'),
  57688. fragmentShader: [
  57689. 'uniform sampler2D src;',
  57690. 'uniform float opacity;',
  57691. 'varying vec2 vUV;',
  57692. 'void main() {',
  57693. ' vec2 offset = vec2(0, 0);',
  57694. ' vec2 repeat = vec2(1, 1);',
  57695. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  57696. ' gl_FragColor = vec4(color.rgb, opacity);',
  57697. '}'
  57698. ].join('\n')
  57699. });
  57700. },{"../core/shader":139}],181:[function(_dereq_,module,exports){
  57701. var registerShader = _dereq_('../core/shader').registerShader;
  57702. /**
  57703. * Multi-channel signed distance field.
  57704. * Used by text component.
  57705. */
  57706. module.exports.Shader = registerShader('msdf', {
  57707. schema: {
  57708. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  57709. color: {type: 'color', is: 'uniform', default: 'white'},
  57710. map: {type: 'map', is: 'uniform'},
  57711. negate: {type: 'boolean', is: 'uniform', default: true},
  57712. opacity: {type: 'number', is: 'uniform', default: 1.0}
  57713. },
  57714. raw: true,
  57715. vertexShader: [
  57716. '#version 300 es',
  57717. 'in vec2 uv;',
  57718. 'in vec3 position;',
  57719. 'uniform mat4 projectionMatrix;',
  57720. 'uniform mat4 modelViewMatrix;',
  57721. 'out vec2 vUV;',
  57722. 'void main(void) {',
  57723. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57724. ' vUV = uv;',
  57725. '}'
  57726. ].join('\n'),
  57727. fragmentShader: [
  57728. '#version 300 es',
  57729. 'precision highp float;',
  57730. 'uniform bool negate;',
  57731. 'uniform float alphaTest;',
  57732. 'uniform float opacity;',
  57733. 'uniform sampler2D map;',
  57734. 'uniform vec3 color;',
  57735. 'in vec2 vUV;',
  57736. 'out vec4 fragColor;',
  57737. 'float median(float r, float g, float b) {',
  57738. ' return max(min(r, g), min(max(r, g), b));',
  57739. '}',
  57740. // FIXME: Experimentally determined constants.
  57741. '#define BIG_ENOUGH 0.001',
  57742. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  57743. 'void main() {',
  57744. ' vec3 sampleColor = texture(map, vUV).rgb;',
  57745. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  57746. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  57747. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  57748. ' float dscale = 0.353505;',
  57749. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  57750. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  57751. // When texel is too small, blend raw alpha value rather than supersampling.
  57752. // FIXME: Experimentally determined constant.
  57753. ' // Do modified alpha test.',
  57754. ' if (isBigEnough > BIG_ENOUGH) {',
  57755. ' float ratio = BIG_ENOUGH / isBigEnough;',
  57756. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  57757. ' }',
  57758. ' // Do modified alpha test.',
  57759. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  57760. ' fragColor = vec4(color.xyz, alpha * opacity);',
  57761. '}'
  57762. ].join('\n')
  57763. });
  57764. },{"../core/shader":139}],182:[function(_dereq_,module,exports){
  57765. var registerShader = _dereq_('../core/shader').registerShader;
  57766. /**
  57767. * Signed distance field.
  57768. * Used by text component.
  57769. */
  57770. module.exports.Shader = registerShader('sdf', {
  57771. schema: {
  57772. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  57773. color: {type: 'color', is: 'uniform', default: 'white'},
  57774. map: {type: 'map', is: 'uniform'},
  57775. opacity: {type: 'number', is: 'uniform', default: 1.0}
  57776. },
  57777. raw: true,
  57778. vertexShader: [
  57779. '#version 300 es',
  57780. 'in vec2 uv;',
  57781. 'in vec3 position;',
  57782. 'uniform mat4 projectionMatrix;',
  57783. 'uniform mat4 modelViewMatrix;',
  57784. 'out vec2 vUV;',
  57785. 'void main(void) {',
  57786. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57787. ' vUV = uv;',
  57788. '}'
  57789. ].join('\n'),
  57790. fragmentShader: [
  57791. '#version 300 es',
  57792. 'precision highp float;',
  57793. 'uniform float alphaTest;',
  57794. 'uniform float opacity;',
  57795. 'uniform sampler2D map;',
  57796. 'uniform vec3 color;',
  57797. 'in vec2 vUV;',
  57798. 'out vec4 fragColor;',
  57799. '#ifdef GL_OES_standard_derivatives',
  57800. ' float contour(float width, float value) {',
  57801. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  57802. ' }',
  57803. '#else',
  57804. ' float aastep(float value, float afwidth) {',
  57805. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  57806. ' }',
  57807. '#endif',
  57808. // FIXME: Experimentally determined constants.
  57809. '#define BIG_ENOUGH 0.001',
  57810. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  57811. '#define ALL_SMOOTH 0.4',
  57812. '#define ALL_ROUGH 0.02',
  57813. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  57814. 'void main() {',
  57815. // When we have derivatives and can get texel size for supersampling.
  57816. ' #ifdef GL_OES_standard_derivatives',
  57817. ' vec2 uv = vUV;',
  57818. ' vec4 texColor = texture(map, uv);',
  57819. ' float dist = texColor.a;',
  57820. ' float width = fwidth(dist);',
  57821. ' float alpha = contour(dist, width);',
  57822. ' float dscale = 0.353505;',
  57823. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  57824. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  57825. // When texel is too small, blend raw alpha value rather than supersampling.
  57826. // FIXME: experimentally determined constant
  57827. ' if (isBigEnough > BIG_ENOUGH) {',
  57828. ' float ratio = BIG_ENOUGH / isBigEnough;',
  57829. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  57830. ' }',
  57831. // Otherwise do weighted supersampling.
  57832. // FIXME: why this weighting?
  57833. ' if (isBigEnough <= BIG_ENOUGH) {',
  57834. ' vec4 box = vec4 (uv - duv, uv + duv);',
  57835. ' alpha = (alpha + 0.5 * (',
  57836. ' contour(texture(map, box.xy).a, width)',
  57837. ' + contour(texture(map, box.zw).a, width)',
  57838. ' + contour(texture(map, box.xw).a, width)',
  57839. ' + contour(texture(map, box.zy).a, width)',
  57840. ' )) / 3.0;',
  57841. ' }',
  57842. // Do modified alpha test.
  57843. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  57844. ' #else',
  57845. // When we don't have derivatives, use approximations.
  57846. ' vec4 texColor = texture(map, vUV);',
  57847. ' float value = texColor.a;',
  57848. // FIXME: if we understood font pixel dimensions, this could probably be improved
  57849. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  57850. ' float alpha = aastep(value, afwidth);',
  57851. // Use gl_FragCoord.w to guess when we should blend.
  57852. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  57853. ' 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);',
  57854. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  57855. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  57856. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  57857. ' #endif',
  57858. ' fragColor = vec4(color, opacity * alpha);',
  57859. '}'
  57860. ].join('\n')
  57861. });
  57862. },{"../core/shader":139}],183:[function(_dereq_,module,exports){
  57863. var registerShader = _dereq_('../core/shader').registerShader;
  57864. var THREE = _dereq_('../lib/three');
  57865. var utils = _dereq_('../utils/');
  57866. var CubeLoader = new THREE.CubeTextureLoader();
  57867. var texturePromises = {};
  57868. /**
  57869. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  57870. */
  57871. module.exports.Shader = registerShader('standard', {
  57872. schema: {
  57873. ambientOcclusionMap: {type: 'map'},
  57874. ambientOcclusionMapIntensity: {default: 1},
  57875. ambientOcclusionTextureOffset: {type: 'vec2'},
  57876. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57877. color: {type: 'color'},
  57878. displacementMap: {type: 'map'},
  57879. displacementScale: {default: 1},
  57880. displacementBias: {default: 0.5},
  57881. displacementTextureOffset: {type: 'vec2'},
  57882. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57883. emissive: {type: 'color', default: '#000'},
  57884. emissiveIntensity: {default: 1},
  57885. envMap: {default: ''},
  57886. fog: {default: true},
  57887. height: {default: 256},
  57888. metalness: {default: 0.0, min: 0.0, max: 1.0},
  57889. metalnessMap: {type: 'map'},
  57890. metalnessTextureOffset: {type: 'vec2'},
  57891. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57892. normalMap: {type: 'map'},
  57893. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  57894. normalTextureOffset: {type: 'vec2'},
  57895. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57896. offset: {type: 'vec2', default: {x: 0, y: 0}},
  57897. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  57898. roughness: {default: 0.5, min: 0.0, max: 1.0},
  57899. roughnessMap: {type: 'map'},
  57900. roughnessTextureOffset: {type: 'vec2'},
  57901. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57902. sphericalEnvMap: {type: 'map'},
  57903. src: {type: 'map'},
  57904. width: {default: 512},
  57905. wireframe: {default: false},
  57906. wireframeLinewidth: {default: 2}
  57907. },
  57908. /**
  57909. * Initializes the shader.
  57910. * Adds a reference from the scene to this entity as the camera.
  57911. */
  57912. init: function (data) {
  57913. this.rendererSystem = this.el.sceneEl.systems.renderer;
  57914. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  57915. getMaterialData(data, this.materialData);
  57916. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57917. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  57918. this.material = new THREE.MeshStandardMaterial(this.materialData);
  57919. utils.material.updateMap(this, data);
  57920. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  57921. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  57922. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  57923. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  57924. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  57925. this.updateEnvMap(data);
  57926. },
  57927. update: function (data) {
  57928. this.updateMaterial(data);
  57929. utils.material.updateMap(this, data);
  57930. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  57931. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  57932. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  57933. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  57934. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  57935. this.updateEnvMap(data);
  57936. },
  57937. /**
  57938. * Updating existing material.
  57939. *
  57940. * @param {object} data - Material component data.
  57941. * @returns {object} Material.
  57942. */
  57943. updateMaterial: function (data) {
  57944. var key;
  57945. var material = this.material;
  57946. getMaterialData(data, this.materialData);
  57947. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57948. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  57949. for (key in this.materialData) {
  57950. material[key] = this.materialData[key];
  57951. }
  57952. },
  57953. /**
  57954. * Handle environment cubemap. Textures are cached in texturePromises.
  57955. */
  57956. updateEnvMap: function (data) {
  57957. var self = this;
  57958. var material = this.material;
  57959. var envMap = data.envMap;
  57960. var sphericalEnvMap = data.sphericalEnvMap;
  57961. // No envMap defined or already loading.
  57962. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  57963. material.envMap = null;
  57964. material.needsUpdate = true;
  57965. return;
  57966. }
  57967. this.isLoadingEnvMap = true;
  57968. // if a spherical env map is defined then use it.
  57969. if (sphericalEnvMap) {
  57970. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  57971. self.isLoadingEnvMap = false;
  57972. texture.mapping = THREE.SphericalReflectionMapping;
  57973. material.envMap = texture;
  57974. utils.material.handleTextureEvents(self.el, texture);
  57975. material.needsUpdate = true;
  57976. });
  57977. return;
  57978. }
  57979. // Another material is already loading this texture. Wait on promise.
  57980. if (texturePromises[envMap]) {
  57981. texturePromises[envMap].then(function (cube) {
  57982. self.isLoadingEnvMap = false;
  57983. material.envMap = cube;
  57984. utils.material.handleTextureEvents(self.el, cube);
  57985. material.needsUpdate = true;
  57986. });
  57987. return;
  57988. }
  57989. // Material is first to load this texture. Load and resolve texture.
  57990. texturePromises[envMap] = new Promise(function (resolve) {
  57991. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  57992. CubeLoader.load(urls, function (cube) {
  57993. // Texture loaded.
  57994. self.isLoadingEnvMap = false;
  57995. material.envMap = cube;
  57996. utils.material.handleTextureEvents(self.el, cube);
  57997. resolve(cube);
  57998. });
  57999. });
  58000. });
  58001. }
  58002. });
  58003. /**
  58004. * Builds and normalize material data, normalizing stuff along the way.
  58005. *
  58006. * @param {object} data - Material data.
  58007. * @param {object} materialData - Object to use.
  58008. * @returns {object} Updated materialData.
  58009. */
  58010. function getMaterialData (data, materialData) {
  58011. materialData.color.set(data.color);
  58012. materialData.emissive.set(data.emissive);
  58013. materialData.emissiveIntensity = data.emissiveIntensity;
  58014. materialData.fog = data.fog;
  58015. materialData.metalness = data.metalness;
  58016. materialData.roughness = data.roughness;
  58017. materialData.wireframe = data.wireframe;
  58018. materialData.wireframeLinewidth = data.wireframeLinewidth;
  58019. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  58020. if (data.ambientOcclusionMap) {
  58021. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  58022. }
  58023. if (data.displacementMap) {
  58024. materialData.displacementScale = data.displacementScale;
  58025. materialData.displacementBias = data.displacementBias;
  58026. }
  58027. return materialData;
  58028. }
  58029. },{"../core/shader":139,"../lib/three":177,"../utils/":203}],184:[function(_dereq_,module,exports){
  58030. var css = "html.a-fullscreen{bottom:0;left:0;position:fixed;right:0;top:0}html.a-fullscreen body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}html.a-fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;position:fixed!important}html:not(.a-fullscreen) .a-enter-ar,html:not(.a-fullscreen) .a-enter-vr{right:5px;bottom:5px}:-webkit-full-screen{background-color:transparent}.a-hidden{display:none!important}.a-canvas{height:100%;left:0;position:absolute;top:0;width:100%}.a-canvas.a-grab-cursor:hover{cursor:grab;cursor:-moz-grab;cursor:-webkit-grab}canvas.a-canvas.a-mouse-cursor-hover:hover{cursor:pointer}.a-inspector-loader{background-color:#ed3160;position:fixed;left:3px;top:3px;padding:6px 10px;color:#fff;text-decoration:none;font-size:12px;font-family:Roboto,sans-serif;text-align:center;z-index:99999;width:204px}@keyframes dots-1{from{opacity:0}25%{opacity:1}}@keyframes dots-2{from{opacity:0}50%{opacity:1}}@keyframes dots-3{from{opacity:0}75%{opacity:1}}@-webkit-keyframes dots-1{from{opacity:0}25%{opacity:1}}@-webkit-keyframes dots-2{from{opacity:0}50%{opacity:1}}@-webkit-keyframes dots-3{from{opacity:0}75%{opacity:1}}.a-inspector-loader .dots span{animation:dots-1 2s infinite steps(1);-webkit-animation:dots-1 2s infinite steps(1)}.a-inspector-loader .dots span:first-child+span{animation-name:dots-2;-webkit-animation-name:dots-2}.a-inspector-loader .dots span:first-child+span+span{animation-name:dots-3;-webkit-animation-name:dots-3}a-scene{display:block;position:relative;height:100%;width:100%}a-assets,a-scene audio,a-scene img,a-scene video{display:none}.a-enter-vr-modal,.a-orientation-modal{font-family:Consolas,Andale Mono,Courier New,monospace}.a-enter-vr-modal a{border-bottom:1px solid #fff;padding:2px 0;text-decoration:none;transition:.1s color ease-in}.a-enter-vr-modal a:hover{background-color:#fff;color:#111;padding:2px 4px;position:relative;left:-4px}.a-enter-ar,.a-enter-vr{font-family:sans-serif,monospace;font-size:13px;width:100%;font-weight:200;line-height:16px;position:absolute;right:20px;bottom:20px}.a-enter-ar{right:80px}.a-enter-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff;user-select:none;outline:0}.a-enter-vr-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-vrmode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M68.81,21.56H64.23v8.27h4.58a4.13,4.13,0,0,0,3.1-1.09,4.2,4.2,0,0,0,1-3,4.24,4.24,0,0,0-1-3A4.05,4.05,0,0,0,68.81,21.56Z' fill='%23fff'/%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0ZM41.9,46H34L24,16h8l6,21.84,6-21.84H52Zm39.29,0H73.44L68.15,35.39H64.23V46H57V16H68.81q5.32,0,8.34,2.37a8,8,0,0,1,3,6.69,9.68,9.68,0,0,1-1.27,5.18,8.9,8.9,0,0,1-4,3.34l6.26,12.11Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.35)}.a-enter-ar-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-armode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0Zm8,50a8,8,0,0,1-8,8H12a8,8,0,0,1-8-8V12a8,8,0,0,1,8-8H96a8,8,0,0,1,8,8Z' fill='%23fff'/%3E%3Cpath d='M43.35,39.82H32.51L30.45,46H23.88L35,16h5.73L52,46H45.43Zm-9.17-5h7.5L37.91,23.58Z' fill='%23fff'/%3E%3Cpath d='M68.11,35H63.18V46H57V16H68.15q5.31,0,8.2,2.37a8.18,8.18,0,0,1,2.88,6.7,9.22,9.22,0,0,1-1.33,5.12,9.09,9.09,0,0,1-4,3.26l6.49,12.26V46H73.73Zm-4.93-5h5a5.09,5.09,0,0,0,3.6-1.18,4.21,4.21,0,0,0,1.28-3.27,4.56,4.56,0,0,0-1.2-3.34A5,5,0,0,0,68.15,21h-5Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.2)}.a-enter-ar-button,.a-enter-vr-button{background-size:90% 90%;border:0;bottom:0;cursor:pointer;min-width:58px;min-height:34px;padding-right:0;padding-top:0;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999;border-radius:8px;touch-action:manipulation}.a-enter-ar-button{background-size:100% 90%;margin-right:10px;border-radius:7px}.a-enter-ar-button:active,.a-enter-ar-button:hover,.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#ef2d5e}.a-enter-vr-button.resethover{background-color:rgba(0,0,0,.35)}[data-a-enter-vr-no-webvr] .a-enter-vr-button{border-color:#666;opacity:.65}[data-a-enter-vr-no-webvr] .a-enter-vr-button:active,[data-a-enter-vr-no-webvr] .a-enter-vr-button:hover{background-color:rgba(0,0,0,.35);cursor:not-allowed}.a-enter-vr-modal{background-color:#666;border-radius:0;display:none;min-height:32px;margin-right:70px;padding:9px;width:280px;right:2%;position:absolute}.a-enter-vr-modal:after{border-bottom:10px solid transparent;border-left:10px solid #666;border-top:10px solid transparent;display:inline-block;content:'';position:absolute;right:-5px;top:5px;width:0;height:0}.a-enter-vr-modal a,.a-enter-vr-modal p{display:inline}.a-enter-vr-modal p{margin:0}.a-enter-vr-modal p:after{content:' '}[data-a-enter-vr-no-headset].a-enter-vr:hover .a-enter-vr-modal,[data-a-enter-vr-no-webvr].a-enter-vr:hover .a-enter-vr-modal{display:block}.a-orientation-modal{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%2090%2090%22%20enable-background%3D%22new%200%200%2090%2090%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20points%3D%220%2C0%200%2C0%200%2C0%20%22%3E%3C/polygon%3E%3Cg%3E%3Cpath%20d%3D%22M71.545%2C48.145h-31.98V20.743c0-2.627-2.138-4.765-4.765-4.765H18.456c-2.628%2C0-4.767%2C2.138-4.767%2C4.765v42.789%20%20%20c0%2C2.628%2C2.138%2C4.766%2C4.767%2C4.766h5.535v0.959c0%2C2.628%2C2.138%2C4.765%2C4.766%2C4.765h42.788c2.628%2C0%2C4.766-2.137%2C4.766-4.765V52.914%20%20%20C76.311%2C50.284%2C74.173%2C48.145%2C71.545%2C48.145z%20M18.455%2C16.935h16.344c2.1%2C0%2C3.808%2C1.708%2C3.808%2C3.808v27.401H37.25V22.636%20%20%20c0-0.264-0.215-0.478-0.479-0.478H16.482c-0.264%2C0-0.479%2C0.214-0.479%2C0.478v36.585c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h7.507v7.644%20%20%20h-5.534c-2.101%2C0-3.81-1.709-3.81-3.81V20.743C14.645%2C18.643%2C16.354%2C16.935%2C18.455%2C16.935z%20M16.96%2C23.116h19.331v25.031h-7.535%20%20%20c-2.628%2C0-4.766%2C2.139-4.766%2C4.768v5.828h-7.03V23.116z%20M71.545%2C73.064H28.757c-2.101%2C0-3.81-1.708-3.81-3.808V52.914%20%20%20c0-2.102%2C1.709-3.812%2C3.81-3.812h42.788c2.1%2C0%2C3.809%2C1.71%2C3.809%2C3.812v16.343C75.354%2C71.356%2C73.645%2C73.064%2C71.545%2C73.064z%22%3E%3C/path%3E%3Cpath%20d%3D%22M28.919%2C58.424c-1.466%2C0-2.659%2C1.193-2.659%2C2.66c0%2C1.466%2C1.193%2C2.658%2C2.659%2C2.658c1.468%2C0%2C2.662-1.192%2C2.662-2.658%20%20%20C31.581%2C59.617%2C30.387%2C58.424%2C28.919%2C58.424z%20M28.919%2C62.786c-0.939%2C0-1.703-0.764-1.703-1.702c0-0.939%2C0.764-1.704%2C1.703-1.704%20%20%20c0.94%2C0%2C1.705%2C0.765%2C1.705%2C1.704C30.623%2C62.022%2C29.858%2C62.786%2C28.919%2C62.786z%22%3E%3C/path%3E%3Cpath%20d%3D%22M69.654%2C50.461H33.069c-0.264%2C0-0.479%2C0.215-0.479%2C0.479v20.288c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h36.585%20%20%20c0.263%2C0%2C0.477-0.214%2C0.477-0.478V50.939C70.131%2C50.676%2C69.917%2C50.461%2C69.654%2C50.461z%20M69.174%2C51.417V70.75H33.548V51.417H69.174z%22%3E%3C/path%3E%3Cpath%20d%3D%22M45.201%2C30.296c6.651%2C0%2C12.233%2C5.351%2C12.551%2C11.977l-3.033-2.638c-0.193-0.165-0.507-0.142-0.675%2C0.048%20%20%20c-0.174%2C0.198-0.153%2C0.501%2C0.045%2C0.676l3.883%2C3.375c0.09%2C0.075%2C0.198%2C0.115%2C0.312%2C0.115c0.141%2C0%2C0.273-0.061%2C0.362-0.166%20%20%20l3.371-3.877c0.173-0.2%2C0.151-0.502-0.047-0.675c-0.194-0.166-0.508-0.144-0.676%2C0.048l-2.592%2C2.979%20%20%20c-0.18-3.417-1.629-6.605-4.099-9.001c-2.538-2.461-5.877-3.817-9.404-3.817c-0.264%2C0-0.479%2C0.215-0.479%2C0.479%20%20%20C44.72%2C30.083%2C44.936%2C30.296%2C45.201%2C30.296z%22%3E%3C/path%3E%3C/g%3E%3C/svg%3E) center/50% 50% no-repeat rgba(244,244,244,1);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-orientation-modal:after{color:#666;content:\"Insert phone into Cardboard holder.\";display:block;position:absolute;text-align:center;top:70%;transform:translateY(-70%);width:100%}.a-orientation-modal button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%20100%20100%22%20enable-background%3D%22new%200%200%20100%20100%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M55.209%2C50l17.803-17.803c1.416-1.416%2C1.416-3.713%2C0-5.129c-1.416-1.417-3.713-1.417-5.129%2C0L50.08%2C44.872%20%20L32.278%2C27.069c-1.416-1.417-3.714-1.417-5.129%2C0c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129L44.951%2C50L27.149%2C67.803%20%20c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129c0.708%2C0.708%2C1.636%2C1.062%2C2.564%2C1.062c0.928%2C0%2C1.856-0.354%2C2.564-1.062L50.08%2C55.13l17.803%2C17.802%20%20c0.708%2C0.708%2C1.637%2C1.062%2C2.564%2C1.062s1.856-0.354%2C2.564-1.062c1.416-1.416%2C1.416-3.713%2C0-5.129L55.209%2C50z%22%3E%3C/path%3E%3C/svg%3E) no-repeat;border:none;height:50px;text-indent:-9999px;width:50px}.a-loader-title{background-color:rgba(0,0,0,.6);font-family:sans-serif,monospace;text-align:center;font-size:20px;height:50px;font-weight:300;line-height:50px;position:absolute;right:0;left:0;top:0;color:#fff}.a-modal{background:0 0/50% 50% rgba(0,0,0,.6);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-dialog{position:relative;left:50%;top:50%;transform:translate(-50%,-50%);z-index:199995;width:300px;height:200px;background-size:contain;background-color:#fff;font-family:sans-serif,monospace;font-size:20px;border-radius:3px;padding:6px}.a-dialog-text-container{width:100%;height:70%;align-self:flex-start;display:flex;justify-content:center;align-content:center;flex-direction:column}.a-dialog-text{display:inline-block;font-weight:400;font-size:14pt;margin:8px}.a-dialog-buttons-container{display:inline-flex;align-self:flex-end;width:100%;height:30%}.a-dialog-button{cursor:pointer;align-self:center;opacity:.9;height:80%;width:50%;font-size:12pt;margin:4px;border-radius:2px;text-align:center;border:none;display:inline-block;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;box-shadow:0 1px 3px rgba(0,0,0,.1),0 1px 2px rgba(0,0,0,.2);user-select:none}.a-dialog-permission-button:hover{box-shadow:0 7px 14px rgba(0,0,0,.2),0 2px 2px rgba(0,0,0,.2)}.a-dialog-allow-button{background-color:#00ceff}.a-dialog-deny-button{background-color:#ff005b}.a-dialog-ok-button{background-color:#00ceff;width:100%}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  58031. },{"browserify-css":4}],185:[function(_dereq_,module,exports){
  58032. var css = ".rs-base{background-color:#333;color:#fafafa;border-radius:0;font:10px monospace;left:5px;line-height:1em;opacity:.85;overflow:hidden;padding:10px;position:fixed;top:5px;width:300px;z-index:10000}.rs-base div.hidden{display:none}.rs-base h1{color:#fff;cursor:pointer;font-size:1.4em;font-weight:300;margin:0 0 5px;padding:0}.rs-group{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-direction:column-reverse;flex-direction:column-reverse;margin-bottom:5px}.rs-group:last-child{margin-bottom:0}.rs-counter-base{align-items:center;display:-webkit-box;display:-webkit-flex;display:flex;height:10px;-webkit-justify-content:space-between;justify-content:space-between;margin:2px 0}.rs-counter-base.alarm{color:#b70000;text-shadow:0 0 0 #b70000,0 0 1px #fff,0 0 1px #fff,0 0 2px #fff,0 0 2px #fff,0 0 3px #fff,0 0 3px #fff,0 0 4px #fff,0 0 4px #fff}.rs-counter-id{font-weight:300;-webkit-box-ordinal-group:0;-webkit-order:0;order:0;width:54px}.rs-counter-value{font-weight:300;-webkit-box-ordinal-group:1;-webkit-order:1;order:1;text-align:right;width:35px}.rs-canvas{-webkit-box-ordinal-group:2;-webkit-order:2;order:2}@media (min-width:480px){.rs-base{left:20px;top:20px}}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/rStats.css"})); module.exports = css;
  58033. },{"browserify-css":4}],186:[function(_dereq_,module,exports){
  58034. var constants = _dereq_('../constants/');
  58035. var registerSystem = _dereq_('../core/system').registerSystem;
  58036. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  58037. /**
  58038. * Camera system. Manages which camera is active among multiple cameras in scene.
  58039. *
  58040. * @member {object} activeCameraEl - Active camera entity.
  58041. */
  58042. module.exports.System = registerSystem('camera', {
  58043. init: function () {
  58044. this.activeCameraEl = null;
  58045. this.render = this.render.bind(this);
  58046. this.unwrapRender = this.unwrapRender.bind(this);
  58047. this.wrapRender = this.wrapRender.bind(this);
  58048. this.initialCameraFound = false;
  58049. this.numUserCameras = 0;
  58050. this.numUserCamerasChecked = 0;
  58051. this.setupInitialCamera();
  58052. },
  58053. /**
  58054. * Setup initial camera, either searching for camera or
  58055. * creating a default camera if user has not added one during the initial scene traversal.
  58056. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  58057. * loads.
  58058. *
  58059. * Default camera offset height is at average eye level (~1.6m).
  58060. */
  58061. setupInitialCamera: function () {
  58062. var cameraEls;
  58063. var i;
  58064. var sceneEl = this.sceneEl;
  58065. var self = this;
  58066. // Camera already defined or the one defined it is an spectator one.
  58067. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  58068. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  58069. return;
  58070. }
  58071. // Search for initial user-defined camera.
  58072. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  58073. // No user cameras, create default one.
  58074. if (!cameraEls.length) {
  58075. this.createDefaultCamera();
  58076. return;
  58077. }
  58078. this.numUserCameras = cameraEls.length;
  58079. for (i = 0; i < cameraEls.length; i++) {
  58080. cameraEls[i].addEventListener('object3dset', function (evt) {
  58081. if (evt.detail.type !== 'camera') { return; }
  58082. self.checkUserCamera(this);
  58083. });
  58084. // Load camera and wait for camera to initialize.
  58085. if (cameraEls[i].isNode) {
  58086. cameraEls[i].load();
  58087. } else {
  58088. cameraEls[i].addEventListener('nodeready', function () {
  58089. this.load();
  58090. });
  58091. }
  58092. }
  58093. },
  58094. /**
  58095. * Check if a user-defined camera entity is appropriate to be initial camera.
  58096. * (active + non-spectator).
  58097. *
  58098. * Keep track of the number of cameras we checked and whether we found one.
  58099. */
  58100. checkUserCamera: function (cameraEl) {
  58101. var cameraData;
  58102. var sceneEl = this.el.sceneEl;
  58103. this.numUserCamerasChecked++;
  58104. // Already found one.
  58105. if (this.initialCameraFound) { return; }
  58106. // Check if camera is appropriate for being the initial camera.
  58107. cameraData = cameraEl.getAttribute('camera');
  58108. if (!cameraData.active || cameraData.spectator) {
  58109. // No user cameras eligible, create default camera.
  58110. if (this.numUserCamerasChecked === this.numUserCameras) {
  58111. this.createDefaultCamera();
  58112. }
  58113. return;
  58114. }
  58115. this.initialCameraFound = true;
  58116. sceneEl.camera = cameraEl.getObject3D('camera');
  58117. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  58118. },
  58119. createDefaultCamera: function () {
  58120. var defaultCameraEl;
  58121. var sceneEl = this.sceneEl;
  58122. // Set up default camera.
  58123. defaultCameraEl = document.createElement('a-entity');
  58124. defaultCameraEl.setAttribute('camera', {active: true});
  58125. defaultCameraEl.setAttribute('position', {
  58126. x: 0,
  58127. y: constants.DEFAULT_CAMERA_HEIGHT,
  58128. z: 0
  58129. });
  58130. defaultCameraEl.setAttribute('wasd-controls', '');
  58131. defaultCameraEl.setAttribute('look-controls', '');
  58132. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  58133. defaultCameraEl.addEventListener('object3dset', function (evt) {
  58134. if (evt.detail.type !== 'camera') { return; }
  58135. sceneEl.camera = evt.detail.object;
  58136. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  58137. });
  58138. sceneEl.appendChild(defaultCameraEl);
  58139. },
  58140. /**
  58141. * Set a different active camera.
  58142. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  58143. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  58144. * the new camera.
  58145. */
  58146. disableActiveCamera: function () {
  58147. var cameraEls;
  58148. var newActiveCameraEl;
  58149. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  58150. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  58151. newActiveCameraEl.setAttribute('camera', 'active', true);
  58152. },
  58153. /**
  58154. * Set active camera to be used by renderer.
  58155. * Removes the default camera (if present).
  58156. * Disables all other cameras in the scene.
  58157. *
  58158. * @param {Element} newCameraEl - Entity with camera component.
  58159. */
  58160. setActiveCamera: function (newCameraEl) {
  58161. var cameraEl;
  58162. var cameraEls;
  58163. var i;
  58164. var newCamera;
  58165. var previousCamera = this.activeCameraEl;
  58166. var sceneEl = this.sceneEl;
  58167. // Same camera.
  58168. newCamera = newCameraEl.getObject3D('camera');
  58169. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  58170. // Grab the default camera.
  58171. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  58172. var defaultCameraEl = defaultCameraWrapper &&
  58173. defaultCameraWrapper.querySelector('[camera]');
  58174. // Remove default camera if new camera is not the default camera.
  58175. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  58176. // Make new camera active.
  58177. this.activeCameraEl = newCameraEl;
  58178. this.activeCameraEl.play();
  58179. sceneEl.camera = newCamera;
  58180. // Disable current camera
  58181. if (previousCamera) {
  58182. previousCamera.setAttribute('camera', 'active', false);
  58183. }
  58184. // Disable other cameras in the scene
  58185. cameraEls = sceneEl.querySelectorAll('[camera]');
  58186. for (i = 0; i < cameraEls.length; i++) {
  58187. cameraEl = cameraEls[i];
  58188. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  58189. cameraEl.setAttribute('camera', 'active', false);
  58190. cameraEl.pause();
  58191. }
  58192. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  58193. },
  58194. /**
  58195. * Set spectator camera to render the scene on a 2D display.
  58196. *
  58197. * @param {Element} newCameraEl - Entity with camera component.
  58198. */
  58199. setSpectatorCamera: function (newCameraEl) {
  58200. var newCamera;
  58201. var previousCamera = this.spectatorCameraEl;
  58202. var sceneEl = this.sceneEl;
  58203. var spectatorCameraEl;
  58204. // Same camera.
  58205. newCamera = newCameraEl.getObject3D('camera');
  58206. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  58207. // Disable current camera
  58208. if (previousCamera) {
  58209. previousCamera.setAttribute('camera', 'spectator', false);
  58210. }
  58211. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  58212. sceneEl.addEventListener('enter-vr', this.wrapRender);
  58213. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  58214. spectatorCameraEl.setAttribute('camera', 'active', false);
  58215. spectatorCameraEl.play();
  58216. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  58217. },
  58218. /**
  58219. * Disables current spectator camera.
  58220. */
  58221. disableSpectatorCamera: function () {
  58222. this.spectatorCameraEl = undefined;
  58223. },
  58224. /**
  58225. * Wrap the render method of the renderer to render
  58226. * the spectator camera after vrDisplay.submitFrame.
  58227. */
  58228. wrapRender: function () {
  58229. if (!this.spectatorCameraEl || this.originalRender) { return; }
  58230. this.originalRender = this.sceneEl.renderer.render;
  58231. this.sceneEl.renderer.render = this.render;
  58232. },
  58233. unwrapRender: function () {
  58234. if (!this.originalRender) { return; }
  58235. this.sceneEl.renderer.render = this.originalRender;
  58236. this.originalRender = undefined;
  58237. },
  58238. render: function (scene, camera) {
  58239. var isVREnabled;
  58240. var sceneEl = this.sceneEl;
  58241. var spectatorCamera;
  58242. isVREnabled = sceneEl.renderer.xr.enabled;
  58243. this.originalRender.call(sceneEl.renderer, scene, camera);
  58244. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  58245. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  58246. sceneEl.renderer.xr.enabled = false;
  58247. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  58248. sceneEl.renderer.xr.enabled = isVREnabled;
  58249. }
  58250. });
  58251. /**
  58252. * Remove injected default camera from scene, if present.
  58253. *
  58254. * @param {Element} sceneEl
  58255. */
  58256. function removeDefaultCamera (sceneEl) {
  58257. var defaultCamera;
  58258. var camera = sceneEl.camera;
  58259. if (!camera) { return; }
  58260. // Remove default camera if present.
  58261. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  58262. if (!defaultCamera) { return; }
  58263. sceneEl.removeChild(defaultCamera);
  58264. }
  58265. },{"../constants/":121,"../core/system":140}],187:[function(_dereq_,module,exports){
  58266. var geometries = _dereq_('../core/geometry').geometries;
  58267. var registerSystem = _dereq_('../core/system').registerSystem;
  58268. var THREE = _dereq_('../lib/three');
  58269. /**
  58270. * System for geometry component.
  58271. * Handle geometry caching.
  58272. *
  58273. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  58274. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  58275. * know whether to dispose on removal.
  58276. */
  58277. module.exports.System = registerSystem('geometry', {
  58278. init: function () {
  58279. this.cache = {};
  58280. this.cacheCount = {};
  58281. },
  58282. /**
  58283. * Reset cache. Mainly for testing.
  58284. */
  58285. clearCache: function () {
  58286. this.cache = {};
  58287. this.cacheCount = {};
  58288. },
  58289. /**
  58290. * Attempt to retrieve from cache.
  58291. *
  58292. * @returns {Object|null} A geometry if it exists, else null.
  58293. */
  58294. getOrCreateGeometry: function (data) {
  58295. var cache = this.cache;
  58296. var cachedGeometry;
  58297. var hash;
  58298. // Skip all caching logic.
  58299. if (data.skipCache) { return createGeometry(data); }
  58300. // Try to retrieve from cache first.
  58301. hash = this.hash(data);
  58302. cachedGeometry = cache[hash];
  58303. incrementCacheCount(this.cacheCount, hash);
  58304. if (cachedGeometry) { return cachedGeometry; }
  58305. // Create geometry.
  58306. cachedGeometry = createGeometry(data);
  58307. // Cache and return geometry.
  58308. cache[hash] = cachedGeometry;
  58309. return cachedGeometry;
  58310. },
  58311. /**
  58312. * Let system know that an entity is no longer using a geometry.
  58313. */
  58314. unuseGeometry: function (data) {
  58315. var cache = this.cache;
  58316. var cacheCount = this.cacheCount;
  58317. var geometry;
  58318. var hash;
  58319. if (data.skipCache) { return; }
  58320. hash = this.hash(data);
  58321. if (!cache[hash]) { return; }
  58322. decrementCacheCount(cacheCount, hash);
  58323. // Another entity is still using this geometry. No need to do anything.
  58324. if (cacheCount[hash] > 0) { return; }
  58325. // No more entities are using this geometry. Dispose.
  58326. geometry = cache[hash];
  58327. geometry.dispose();
  58328. delete cache[hash];
  58329. delete cacheCount[hash];
  58330. },
  58331. /**
  58332. * Use JSON.stringify to turn component data into hash.
  58333. * Should be deterministic within a single browser engine.
  58334. * If not, then look into json-stable-stringify.
  58335. */
  58336. hash: function (data) {
  58337. return JSON.stringify(data);
  58338. }
  58339. });
  58340. /**
  58341. * Create geometry using component data.
  58342. *
  58343. * @param {object} data - Component data.
  58344. * @returns {object} Geometry.
  58345. */
  58346. function createGeometry (data) {
  58347. var geometryType = data.primitive;
  58348. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  58349. var geometryInstance = new GeometryClass();
  58350. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  58351. geometryInstance.init(data);
  58352. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  58353. }
  58354. /**
  58355. * Decreate count of entity using a geometry.
  58356. */
  58357. function decrementCacheCount (cacheCount, hash) {
  58358. cacheCount[hash]--;
  58359. }
  58360. /**
  58361. * Increase count of entity using a geometry.
  58362. */
  58363. function incrementCacheCount (cacheCount, hash) {
  58364. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  58365. }
  58366. /**
  58367. * Transform geometry to BufferGeometry if `doBuffer`.
  58368. *
  58369. * @param {object} geometry
  58370. * @param {boolean} doBuffer
  58371. * @returns {object} Geometry.
  58372. */
  58373. function toBufferGeometry (geometry, doBuffer) {
  58374. var bufferGeometry;
  58375. if (!doBuffer) { return geometry; }
  58376. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  58377. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  58378. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  58379. return bufferGeometry;
  58380. }
  58381. },{"../core/geometry":130,"../core/system":140,"../lib/three":177}],188:[function(_dereq_,module,exports){
  58382. var registerSystem = _dereq_('../core/system').registerSystem;
  58383. var THREE = _dereq_('../lib/three');
  58384. /**
  58385. * glTF model system.
  58386. *
  58387. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  58388. * provided externally.
  58389. *
  58390. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  58391. */
  58392. module.exports.System = registerSystem('gltf-model', {
  58393. schema: {
  58394. dracoDecoderPath: {default: ''}
  58395. },
  58396. init: function () {
  58397. var path = this.data.dracoDecoderPath;
  58398. this.dracoLoader = new THREE.DRACOLoader();
  58399. this.dracoLoader.setDecoderPath(path);
  58400. },
  58401. update: function () {
  58402. var path;
  58403. if (this.dracoLoader) { return; }
  58404. path = this.data.dracoDecoderPath;
  58405. this.dracoLoader = new THREE.DRACOLoader();
  58406. this.dracoLoader.setDecoderPath(path);
  58407. },
  58408. getDRACOLoader: function () {
  58409. return this.dracoLoader;
  58410. }
  58411. });
  58412. },{"../core/system":140,"../lib/three":177}],189:[function(_dereq_,module,exports){
  58413. _dereq_('./camera');
  58414. _dereq_('./geometry');
  58415. _dereq_('./gltf-model');
  58416. _dereq_('./light');
  58417. _dereq_('./material');
  58418. _dereq_('./renderer');
  58419. _dereq_('./shadow');
  58420. _dereq_('./tracked-controls-webvr');
  58421. _dereq_('./tracked-controls-webxr');
  58422. _dereq_('./webxr');
  58423. },{"./camera":186,"./geometry":187,"./gltf-model":188,"./light":190,"./material":191,"./renderer":192,"./shadow":193,"./tracked-controls-webvr":194,"./tracked-controls-webxr":195,"./webxr":196}],190:[function(_dereq_,module,exports){
  58424. var registerSystem = _dereq_('../core/system').registerSystem;
  58425. var bind = _dereq_('../utils/bind');
  58426. var constants = _dereq_('../constants/');
  58427. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  58428. /**
  58429. * Light system.
  58430. *
  58431. * Prescribes default lighting if not specified (one ambient, one directional).
  58432. * Removes default lighting from the scene when a new light is added.
  58433. *
  58434. * @param {bool} defaultLights - Whether default lighting are defined.
  58435. * @param {bool} userDefinedLights - Whether user lighting is defined.
  58436. */
  58437. module.exports.System = registerSystem('light', {
  58438. schema: {
  58439. defaultLightsEnabled: {default: true}
  58440. },
  58441. init: function () {
  58442. this.defaultLights = false;
  58443. this.userDefinedLights = false;
  58444. // Wait for all entities to fully load before checking for existence of lights.
  58445. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  58446. // will do so asynchronously.
  58447. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  58448. },
  58449. /**
  58450. * Notify scene that light has been added and to remove the default.
  58451. *
  58452. * @param {object} el - element holding the light component.
  58453. */
  58454. registerLight: function (el) {
  58455. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  58456. // User added a light, remove default lights through DOM.
  58457. this.removeDefaultLights();
  58458. this.userDefinedLights = true;
  58459. }
  58460. },
  58461. removeDefaultLights: function () {
  58462. var defaultLights;
  58463. var sceneEl = this.sceneEl;
  58464. if (!this.defaultLights) { return; }
  58465. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  58466. for (var i = 0; i < defaultLights.length; i++) {
  58467. sceneEl.removeChild(defaultLights[i]);
  58468. }
  58469. this.defaultLights = false;
  58470. },
  58471. /**
  58472. * Prescibe default lights to the scene.
  58473. * Does so by injecting markup such that this state is not invisible.
  58474. * These lights are removed if the user adds any lights.
  58475. */
  58476. setupDefaultLights: function () {
  58477. var sceneEl = this.sceneEl;
  58478. var ambientLight;
  58479. var directionalLight;
  58480. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  58481. return;
  58482. }
  58483. ambientLight = document.createElement('a-entity');
  58484. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  58485. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  58486. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  58487. sceneEl.appendChild(ambientLight);
  58488. directionalLight = document.createElement('a-entity');
  58489. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  58490. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  58491. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  58492. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  58493. sceneEl.appendChild(directionalLight);
  58494. this.defaultLights = true;
  58495. }
  58496. });
  58497. },{"../constants/":121,"../core/system":140,"../utils/bind":197}],191:[function(_dereq_,module,exports){
  58498. var registerSystem = _dereq_('../core/system').registerSystem;
  58499. var THREE = _dereq_('../lib/three');
  58500. var utils = _dereq_('../utils/');
  58501. var isHLS = _dereq_('../utils/material').isHLS;
  58502. var bind = utils.bind;
  58503. var debug = utils.debug;
  58504. var error = debug('components:texture:error');
  58505. var TextureLoader = new THREE.TextureLoader();
  58506. var warn = debug('components:texture:warn');
  58507. TextureLoader.setCrossOrigin('anonymous');
  58508. /**
  58509. * System for material component.
  58510. * Handle material registration, updates (for fog), and texture caching.
  58511. *
  58512. * @member {object} materials - Registered materials.
  58513. * @member {object} textureCounts - Number of times each texture is used. Tracked
  58514. * separately from textureCache, because the cache (1) is populated in
  58515. * multiple places, and (2) may be cleared at any time.
  58516. * @member {object} textureCache - Texture cache for:
  58517. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  58518. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  58519. */
  58520. module.exports.System = registerSystem('material', {
  58521. init: function () {
  58522. this.materials = {};
  58523. this.textureCounts = {};
  58524. this.textureCache = {};
  58525. this.sceneEl.addEventListener(
  58526. 'materialtextureloaded',
  58527. bind(this.onMaterialTextureLoaded, this)
  58528. );
  58529. },
  58530. clearTextureCache: function () {
  58531. this.textureCache = {};
  58532. },
  58533. /**
  58534. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  58535. *
  58536. * @param {string, or element} src - Texture URL or element.
  58537. * @param {string} data - Relevant texture data used for caching.
  58538. * @param {function} cb - Callback to pass texture to.
  58539. */
  58540. loadTexture: function (src, data, cb) {
  58541. var self = this;
  58542. // Canvas.
  58543. if (src.tagName === 'CANVAS') {
  58544. this.loadCanvas(src, data, cb);
  58545. return;
  58546. }
  58547. // Video element.
  58548. if (src.tagName === 'VIDEO') {
  58549. if (!src.src && !src.srcObject && !src.childElementCount) {
  58550. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  58551. }
  58552. this.loadVideo(src, data, cb);
  58553. return;
  58554. }
  58555. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  58556. function loadImageCb (src) { self.loadImage(src, data, cb); }
  58557. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  58558. },
  58559. /**
  58560. * High-level function for loading image textures (THREE.Texture).
  58561. *
  58562. * @param {Element|string} src - Texture source.
  58563. * @param {object} data - Texture data.
  58564. * @param {function} cb - Callback to pass texture to.
  58565. */
  58566. loadImage: function (src, data, handleImageTextureLoaded) {
  58567. var hash = this.hash(data);
  58568. var textureCache = this.textureCache;
  58569. // Texture already being loaded or already loaded. Wait on promise.
  58570. if (textureCache[hash]) {
  58571. textureCache[hash].then(handleImageTextureLoaded);
  58572. return;
  58573. }
  58574. // Texture not yet being loaded. Start loading it.
  58575. textureCache[hash] = loadImageTexture(src, data);
  58576. textureCache[hash].then(handleImageTextureLoaded);
  58577. },
  58578. /**
  58579. * High-level function for loading canvas textures (THREE.Texture).
  58580. *
  58581. * @param {Element|string} src - Texture source.
  58582. * @param {object} data - Texture data.
  58583. * @param {function} cb - Callback to pass texture to.
  58584. */
  58585. loadCanvas: function (src, data, cb) {
  58586. var texture;
  58587. texture = new THREE.CanvasTexture(src);
  58588. setTextureProperties(texture, data);
  58589. cb(texture);
  58590. },
  58591. /**
  58592. * Load video texture (THREE.VideoTexture).
  58593. * Which is just an image texture that RAFs + needsUpdate.
  58594. * Note that creating a video texture is synchronous unlike loading an image texture.
  58595. * Made asynchronous to be consistent with image textures.
  58596. *
  58597. * @param {Element|string} src - Texture source.
  58598. * @param {object} data - Texture data.
  58599. * @param {function} cb - Callback to pass texture to.
  58600. */
  58601. loadVideo: function (src, data, cb) {
  58602. var hash;
  58603. var texture;
  58604. var textureCache = this.textureCache;
  58605. var videoEl;
  58606. var videoTextureResult;
  58607. function handleVideoTextureLoaded (result) {
  58608. result.texture.needsUpdate = true;
  58609. cb(result.texture, result.videoEl);
  58610. }
  58611. // Video element provided.
  58612. if (typeof src !== 'string') {
  58613. // Check cache before creating texture.
  58614. videoEl = src;
  58615. hash = this.hashVideo(data, videoEl);
  58616. if (textureCache[hash]) {
  58617. textureCache[hash].then(handleVideoTextureLoaded);
  58618. return;
  58619. }
  58620. // If not in cache, fix up the attributes then start to create the texture.
  58621. fixVideoAttributes(videoEl);
  58622. }
  58623. // Only URL provided. Use video element to create texture.
  58624. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  58625. // Generated video element already cached. Use that.
  58626. hash = this.hashVideo(data, videoEl);
  58627. if (textureCache[hash]) {
  58628. textureCache[hash].then(handleVideoTextureLoaded);
  58629. return;
  58630. }
  58631. // Create new video texture.
  58632. texture = new THREE.VideoTexture(videoEl);
  58633. texture.minFilter = THREE.LinearFilter;
  58634. setTextureProperties(texture, data);
  58635. // If iOS and video is HLS, do some hacks.
  58636. if (this.sceneEl.isIOS &&
  58637. isHLS(videoEl.src || videoEl.getAttribute('src'),
  58638. videoEl.type || videoEl.getAttribute('type'))) {
  58639. // Actually BGRA. Tell shader to correct later.
  58640. texture.format = THREE.RGBAFormat;
  58641. texture.needsCorrectionBGRA = true;
  58642. // Apparently needed for HLS. Tell shader to correct later.
  58643. texture.flipY = false;
  58644. texture.needsCorrectionFlipY = true;
  58645. }
  58646. // Cache as promise to be consistent with image texture caching.
  58647. videoTextureResult = {texture: texture, videoEl: videoEl};
  58648. textureCache[hash] = Promise.resolve(videoTextureResult);
  58649. handleVideoTextureLoaded(videoTextureResult);
  58650. },
  58651. /**
  58652. * Create a hash of the material properties for texture cache key.
  58653. */
  58654. hash: function (data) {
  58655. if (data.src.tagName) {
  58656. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  58657. data = utils.extendDeep({}, data);
  58658. data.src = data.src.src;
  58659. }
  58660. return JSON.stringify(data);
  58661. },
  58662. hashVideo: function (data, videoEl) {
  58663. return calculateVideoCacheHash(data, videoEl);
  58664. },
  58665. /**
  58666. * Keep track of material in case an update trigger is needed (e.g., fog).
  58667. *
  58668. * @param {object} material
  58669. */
  58670. registerMaterial: function (material) {
  58671. this.materials[material.uuid] = material;
  58672. },
  58673. /**
  58674. * Stop tracking material, and dispose of any textures not being used by
  58675. * another material component.
  58676. *
  58677. * @param {object} material
  58678. */
  58679. unregisterMaterial: function (material) {
  58680. delete this.materials[material.uuid];
  58681. // If any textures on this material are no longer in use, dispose of them.
  58682. var textureCounts = this.textureCounts;
  58683. Object.keys(material)
  58684. .filter(function (propName) {
  58685. return material[propName] && material[propName].isTexture;
  58686. })
  58687. .forEach(function (mapName) {
  58688. textureCounts[material[mapName].uuid]--;
  58689. if (textureCounts[material[mapName].uuid] <= 0) {
  58690. material[mapName].dispose();
  58691. }
  58692. });
  58693. },
  58694. /**
  58695. * Trigger update to all registered materials.
  58696. */
  58697. updateMaterials: function (material) {
  58698. var materials = this.materials;
  58699. Object.keys(materials).forEach(function (uuid) {
  58700. materials[uuid].needsUpdate = true;
  58701. });
  58702. },
  58703. /**
  58704. * Track textures used by material components, so that they can be safely
  58705. * disposed when no longer in use. Textures must be registered here, and not
  58706. * through registerMaterial(), because textures may not be attached at the
  58707. * time the material is registered.
  58708. *
  58709. * @param {Event} e
  58710. */
  58711. onMaterialTextureLoaded: function (e) {
  58712. if (!this.textureCounts[e.detail.texture.uuid]) {
  58713. this.textureCounts[e.detail.texture.uuid] = 0;
  58714. }
  58715. this.textureCounts[e.detail.texture.uuid]++;
  58716. }
  58717. });
  58718. /**
  58719. * Calculates consistent hash from a video element using its attributes.
  58720. * If the video element has an ID, use that.
  58721. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  58722. *
  58723. * @param data {object} - Texture data such as repeat.
  58724. * @param videoEl {Element} - Video element.
  58725. * @returns {string}
  58726. */
  58727. function calculateVideoCacheHash (data, videoEl) {
  58728. var i;
  58729. var id = videoEl.getAttribute('id');
  58730. var hash;
  58731. var videoAttributes;
  58732. if (id) { return id; }
  58733. // Calculate hash using sorted video attributes.
  58734. hash = '';
  58735. videoAttributes = data || {};
  58736. for (i = 0; i < videoEl.attributes.length; i++) {
  58737. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  58738. }
  58739. Object.keys(videoAttributes).sort().forEach(function (name) {
  58740. hash += name + ':' + videoAttributes[name] + ';';
  58741. });
  58742. return hash;
  58743. }
  58744. /**
  58745. * Load image texture.
  58746. *
  58747. * @private
  58748. * @param {string|object} src - An <img> element or url to an image file.
  58749. * @param {object} data - Data to set texture properties like `repeat`.
  58750. * @returns {Promise} Resolves once texture is loaded.
  58751. */
  58752. function loadImageTexture (src, data) {
  58753. return new Promise(doLoadImageTexture);
  58754. function doLoadImageTexture (resolve, reject) {
  58755. var isEl = typeof src !== 'string';
  58756. function resolveTexture (texture) {
  58757. setTextureProperties(texture, data);
  58758. texture.needsUpdate = true;
  58759. resolve(texture);
  58760. }
  58761. // Create texture from an element.
  58762. if (isEl) {
  58763. resolveTexture(new THREE.Texture(src));
  58764. return;
  58765. }
  58766. // Request and load texture from src string. THREE will create underlying element.
  58767. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  58768. TextureLoader.load(
  58769. src,
  58770. resolveTexture,
  58771. function () { /* no-op */ },
  58772. function (xhr) {
  58773. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  58774. xhr.statusText);
  58775. }
  58776. );
  58777. }
  58778. }
  58779. /**
  58780. * Set texture properties such as repeat and offset.
  58781. *
  58782. * @param {object} data - With keys like `repeat`.
  58783. */
  58784. function setTextureProperties (texture, data) {
  58785. var offset = data.offset || {x: 0, y: 0};
  58786. var repeat = data.repeat || {x: 1, y: 1};
  58787. var npot = data.npot || false;
  58788. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  58789. // and filters must not use mipmaps (i.e. Nearest or Linear).
  58790. if (npot) {
  58791. texture.wrapS = THREE.ClampToEdgeWrapping;
  58792. texture.wrapT = THREE.ClampToEdgeWrapping;
  58793. texture.magFilter = THREE.LinearFilter;
  58794. texture.minFilter = THREE.LinearFilter;
  58795. }
  58796. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  58797. if (repeat.x !== 1 || repeat.y !== 1) {
  58798. texture.wrapS = THREE.RepeatWrapping;
  58799. texture.wrapT = THREE.RepeatWrapping;
  58800. texture.repeat.set(repeat.x, repeat.y);
  58801. }
  58802. // Don't bother setting offset if it is 0/0.
  58803. if (offset.x !== 0 || offset.y !== 0) {
  58804. texture.offset.set(offset.x, offset.y);
  58805. }
  58806. }
  58807. /**
  58808. * Create video element to be used as a texture.
  58809. *
  58810. * @param {string} src - Url to a video file.
  58811. * @param {number} width - Width of the video.
  58812. * @param {number} height - Height of the video.
  58813. * @returns {Element} Video element.
  58814. */
  58815. function createVideoEl (src, width, height) {
  58816. var videoEl = document.createElement('video');
  58817. videoEl.width = width;
  58818. videoEl.height = height;
  58819. // Support inline videos for iOS webviews.
  58820. videoEl.setAttribute('playsinline', '');
  58821. videoEl.setAttribute('webkit-playsinline', '');
  58822. videoEl.autoplay = true;
  58823. videoEl.loop = true;
  58824. videoEl.crossOrigin = 'anonymous';
  58825. videoEl.addEventListener('error', function () {
  58826. warn('`$s` is not a valid video', src);
  58827. }, true);
  58828. videoEl.src = src;
  58829. return videoEl;
  58830. }
  58831. /**
  58832. * Fixes a video element's attributes to prevent developers from accidentally passing the
  58833. * wrong attribute values to commonly misused video attributes.
  58834. *
  58835. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  58836. * as booleans. Existence of those attributes will mean truthy.
  58837. *
  58838. * For example, translates <video loop="false"> to <video>.
  58839. *
  58840. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  58841. * @param {Element} videoEl - Video element.
  58842. * @returns {Element} Video element with the correct properties updated.
  58843. */
  58844. function fixVideoAttributes (videoEl) {
  58845. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  58846. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  58847. if (videoEl.getAttribute('loop') === 'false') {
  58848. videoEl.removeAttribute('loop');
  58849. }
  58850. if (videoEl.getAttribute('preload') === 'false') {
  58851. videoEl.preload = 'none';
  58852. }
  58853. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  58854. // To support inline videos in iOS webviews.
  58855. videoEl.setAttribute('playsinline', '');
  58856. videoEl.setAttribute('webkit-playsinline', '');
  58857. return videoEl;
  58858. }
  58859. },{"../core/system":140,"../lib/three":177,"../utils/":203,"../utils/material":206}],192:[function(_dereq_,module,exports){
  58860. var registerSystem = _dereq_('../core/system').registerSystem;
  58861. var utils = _dereq_('../utils/');
  58862. var THREE = _dereq_('../lib/three');
  58863. var debug = utils.debug;
  58864. var warn = debug('components:renderer:warn');
  58865. /**
  58866. * Determines state of various renderer properties.
  58867. */
  58868. module.exports.System = registerSystem('renderer', {
  58869. schema: {
  58870. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  58871. highRefreshRate: {default: utils.device.isOculusBrowser()},
  58872. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  58873. maxCanvasWidth: {default: 1920},
  58874. maxCanvasHeight: {default: 1920},
  58875. physicallyCorrectLights: {default: false},
  58876. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  58877. sortObjects: {default: false},
  58878. colorManagement: {default: false},
  58879. gammaOutput: {default: false},
  58880. alpha: {default: true},
  58881. foveationLevel: {default: 0}
  58882. },
  58883. init: function () {
  58884. var data = this.data;
  58885. var sceneEl = this.el;
  58886. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  58887. var renderer = sceneEl.renderer;
  58888. renderer.sortObjects = data.sortObjects;
  58889. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  58890. if (data.colorManagement || data.gammaOutput) {
  58891. renderer.outputEncoding = THREE.sRGBEncoding;
  58892. if (data.gammaOutput) {
  58893. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  58894. }
  58895. }
  58896. if (sceneEl.hasAttribute('antialias')) {
  58897. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  58898. }
  58899. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  58900. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  58901. }
  58902. },
  58903. applyColorCorrection: function (colorOrTexture) {
  58904. if (!this.data.colorManagement || !colorOrTexture) {
  58905. return;
  58906. } else if (colorOrTexture.isColor) {
  58907. colorOrTexture.convertSRGBToLinear();
  58908. } else if (colorOrTexture.isTexture) {
  58909. colorOrTexture.encoding = THREE.sRGBEncoding;
  58910. }
  58911. }
  58912. });
  58913. },{"../core/system":140,"../lib/three":177,"../utils/":203}],193:[function(_dereq_,module,exports){
  58914. var registerSystem = _dereq_('../core/system').registerSystem;
  58915. var THREE = _dereq_('../lib/three');
  58916. var SHADOW_MAP_TYPE_MAP = {
  58917. basic: THREE.BasicShadowMap,
  58918. pcf: THREE.PCFShadowMap,
  58919. pcfsoft: THREE.PCFSoftShadowMap
  58920. };
  58921. /**
  58922. * Shadow system.
  58923. *
  58924. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  58925. * options on the WebGLRenderer for configuring shadow appearance.
  58926. */
  58927. module.exports.System = registerSystem('shadow', {
  58928. schema: {
  58929. enabled: {default: true},
  58930. autoUpdate: {default: true},
  58931. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  58932. },
  58933. init: function () {
  58934. var sceneEl = this.sceneEl;
  58935. var data = this.data;
  58936. this.shadowMapEnabled = false;
  58937. if (!sceneEl.renderer) { return; } // For tests.
  58938. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  58939. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  58940. this.setShadowMapEnabled(this.shadowMapEnabled);
  58941. },
  58942. update: function (prevData) {
  58943. if (prevData.enabled !== this.data.enabled) {
  58944. this.setShadowMapEnabled(this.data.enabled);
  58945. }
  58946. },
  58947. /**
  58948. * Enables/disables the renderer shadow map.
  58949. * @param {boolean} enabled
  58950. */
  58951. setShadowMapEnabled: function (enabled) {
  58952. var renderer = this.sceneEl.renderer;
  58953. this.shadowMapEnabled = this.data.enabled && enabled;
  58954. if (renderer) {
  58955. renderer.shadowMap.enabled = this.shadowMapEnabled;
  58956. }
  58957. }
  58958. });
  58959. },{"../core/system":140,"../lib/three":177}],194:[function(_dereq_,module,exports){
  58960. var registerSystem = _dereq_('../core/system').registerSystem;
  58961. var utils = _dereq_('../utils');
  58962. var isWebXRAvailable = utils.device.isWebXRAvailable;
  58963. /**
  58964. * Tracked controls system.
  58965. * Maintain list with available tracked controllers.
  58966. */
  58967. module.exports.System = registerSystem('tracked-controls-webvr', {
  58968. init: function () {
  58969. var self = this;
  58970. this.controllers = [];
  58971. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  58972. this.updateControllerList();
  58973. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  58974. // Don't use WebVR if WebXR is available?
  58975. if (isWebXRAvailable) { return; }
  58976. if (!navigator.getVRDisplays) { return; }
  58977. this.sceneEl.addEventListener('enter-vr', function () {
  58978. navigator.getVRDisplays().then(function (displays) {
  58979. if (displays.length) { self.vrDisplay = displays[0]; }
  58980. });
  58981. });
  58982. },
  58983. tick: function () {
  58984. if (this.isChrome) {
  58985. // Retrieve new controller handlers with updated state (pose, buttons...)
  58986. this.updateControllerList();
  58987. } else {
  58988. this.throttledUpdateControllerList();
  58989. }
  58990. },
  58991. /**
  58992. * Update controller list.
  58993. */
  58994. updateControllerList: function () {
  58995. var controllers = this.controllers;
  58996. var gamepad;
  58997. var gamepads;
  58998. var i;
  58999. var prevCount;
  59000. gamepads = navigator.getGamepads && navigator.getGamepads();
  59001. if (!gamepads) { return; }
  59002. prevCount = controllers.length;
  59003. controllers.length = 0;
  59004. for (i = 0; i < gamepads.length; ++i) {
  59005. gamepad = gamepads[i];
  59006. if (gamepad && gamepad.pose) {
  59007. controllers.push(gamepad);
  59008. }
  59009. }
  59010. if (controllers.length !== prevCount) {
  59011. this.el.emit('controllersupdated', undefined, false);
  59012. }
  59013. }
  59014. });
  59015. },{"../core/system":140,"../utils":203}],195:[function(_dereq_,module,exports){
  59016. var registerSystem = _dereq_('../core/system').registerSystem;
  59017. var utils = _dereq_('../utils');
  59018. /**
  59019. * Tracked controls system.
  59020. * Maintain list with available tracked controllers.
  59021. */
  59022. module.exports.System = registerSystem('tracked-controls-webxr', {
  59023. init: function () {
  59024. this.controllers = [];
  59025. this.oldControllers = [];
  59026. this.oldControllersLength = 0;
  59027. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  59028. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  59029. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  59030. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  59031. },
  59032. tick: function () {
  59033. this.throttledUpdateControllerList();
  59034. },
  59035. updateReferenceSpace: function () {
  59036. var self = this;
  59037. var xrSession = this.el.xrSession;
  59038. if (!xrSession) {
  59039. this.referenceSpace = undefined;
  59040. this.controllers = [];
  59041. if (this.oldControllersLength > 0) {
  59042. this.oldControllersLength = 0;
  59043. this.el.emit('controllersupdated', undefined, false);
  59044. }
  59045. return;
  59046. }
  59047. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  59048. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  59049. self.referenceSpace = referenceSpace;
  59050. }).catch(function (err) {
  59051. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  59052. refspace,
  59053. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  59054. throw err;
  59055. });
  59056. },
  59057. updateControllerList: function () {
  59058. var xrSession = this.el.xrSession;
  59059. var oldControllers = this.oldControllers;
  59060. var i;
  59061. if (!xrSession) {
  59062. if (this.oldControllersLength === 0) { return; }
  59063. // Broadcast that we now have zero controllers connected if there is
  59064. // no session
  59065. this.oldControllersLength = 0;
  59066. this.controllers = [];
  59067. this.el.emit('controllersupdated', undefined, false);
  59068. return;
  59069. }
  59070. this.controllers = xrSession.inputSources;
  59071. if (this.oldControllersLength === this.controllers.length) {
  59072. var equal = true;
  59073. for (i = 0; i < this.controllers.length; ++i) {
  59074. if (this.controllers[i] === oldControllers[i] &&
  59075. this.controllers[i].gamepad === oldControllers[i].gamepad) { continue; }
  59076. equal = false;
  59077. break;
  59078. }
  59079. if (equal) { return; }
  59080. }
  59081. // Store reference to current controllers
  59082. oldControllers.length = 0;
  59083. for (i = 0; i < this.controllers.length; i++) {
  59084. oldControllers.push(this.controllers[i]);
  59085. }
  59086. this.oldControllersLength = this.controllers.length;
  59087. this.el.emit('controllersupdated', undefined, false);
  59088. }
  59089. });
  59090. },{"../core/system":140,"../utils":203}],196:[function(_dereq_,module,exports){
  59091. var registerSystem = _dereq_('../core/system').registerSystem;
  59092. var utils = _dereq_('../utils/');
  59093. var warn = utils.debug('systems:webxr:warn');
  59094. /**
  59095. * WebXR session initialization and XR module support.
  59096. */
  59097. module.exports.System = registerSystem('webxr', {
  59098. schema: {
  59099. referenceSpaceType: {type: 'string', default: 'local-floor'},
  59100. requiredFeatures: {type: 'array', default: ['local-floor']},
  59101. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  59102. overlayElement: {type: 'selector'}
  59103. },
  59104. update: function () {
  59105. var data = this.data;
  59106. this.sessionConfiguration = {
  59107. requiredFeatures: data.requiredFeatures,
  59108. optionalFeatures: data.optionalFeatures
  59109. };
  59110. this.sessionReferenceSpaceType = data.referenceSpaceType;
  59111. if (data.overlayElement) {
  59112. this.warnIfFeatureNotRequested('dom-overlay');
  59113. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  59114. }
  59115. },
  59116. wasFeatureRequested: function (feature) {
  59117. // Features available by default for immersive sessions don't need to
  59118. // be requested explicitly.
  59119. if (feature === 'viewer' || feature === 'local') return true;
  59120. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  59121. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  59122. return true;
  59123. }
  59124. return false;
  59125. },
  59126. warnIfFeatureNotRequested: function (feature, optIntro) {
  59127. if (!this.wasFeatureRequested(feature)) {
  59128. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  59129. 'webxr system options in requiredFeatures/optionalFeatures.';
  59130. warn((optIntro ? optIntro + ' ' : '') + msg);
  59131. }
  59132. }
  59133. });
  59134. },{"../core/system":140,"../utils/":203}],197:[function(_dereq_,module,exports){
  59135. /**
  59136. * Faster version of Function.prototype.bind
  59137. * @param {Function} fn - Function to wrap.
  59138. * @param {Object} ctx - What to bind as context.
  59139. * @param {...*} arguments - Arguments to pass through.
  59140. */
  59141. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  59142. return (function (prependedArgs) {
  59143. return function bound () {
  59144. // Concat the bound function arguments with those passed to original bind
  59145. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  59146. return fn.apply(ctx, args);
  59147. };
  59148. })(Array.prototype.slice.call(arguments, 2));
  59149. };
  59150. },{}],198:[function(_dereq_,module,exports){
  59151. /* global THREE */
  59152. var debug = _dereq_('./debug');
  59153. var extend = _dereq_('object-assign');
  59154. var warn = debug('utils:coordinates:warn');
  59155. // Order of coordinates parsed by coordinates.parse.
  59156. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  59157. // Coordinate string regex. Handles negative, positive, and decimals.
  59158. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  59159. module.exports.regex = regex;
  59160. var OBJECT = 'object';
  59161. var whitespaceRegex = /\s+/g;
  59162. /**
  59163. * Parses coordinates from an "x y z" string.
  59164. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  59165. *
  59166. * @param {string} val - An "x y z" string.
  59167. * @param {string} defaults - fallback value.
  59168. * @returns {object} An object with keys [x, y, z].
  59169. */
  59170. function parse (value, defaultVec) {
  59171. var coordinate;
  59172. var defaultVal;
  59173. var key;
  59174. var i;
  59175. var vec;
  59176. var x;
  59177. var y;
  59178. var z;
  59179. var w;
  59180. if (value && value instanceof Object) {
  59181. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  59182. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  59183. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  59184. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  59185. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  59186. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  59187. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  59188. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  59189. return value;
  59190. }
  59191. if (value === null || value === undefined) {
  59192. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  59193. }
  59194. coordinate = value.trim().split(whitespaceRegex);
  59195. vec = {};
  59196. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  59197. key = COORDINATE_KEYS[i];
  59198. if (coordinate[i]) {
  59199. vec[key] = parseFloat(coordinate[i], 10);
  59200. } else {
  59201. defaultVal = defaultVec && defaultVec[key];
  59202. if (defaultVal === undefined) { continue; }
  59203. vec[key] = parseIfString(defaultVal);
  59204. }
  59205. }
  59206. return vec;
  59207. }
  59208. module.exports.parse = parse;
  59209. /**
  59210. * Stringify coordinates from an object with keys [x y z].
  59211. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  59212. *
  59213. * @param {object|string} data - An object with keys [x y z].
  59214. * @returns {string} An "x y z" string.
  59215. */
  59216. function stringify (data) {
  59217. var str;
  59218. if (typeof data !== OBJECT) { return data; }
  59219. str = data.x + ' ' + data.y;
  59220. if (data.z != null) { str += ' ' + data.z; }
  59221. if (data.w != null) { str += ' ' + data.w; }
  59222. return str;
  59223. }
  59224. module.exports.stringify = stringify;
  59225. /**
  59226. * @returns {bool}
  59227. */
  59228. function isCoordinates (value) {
  59229. return regex.test(value);
  59230. }
  59231. module.exports.isCoordinates = isCoordinates;
  59232. module.exports.isCoordinate = function (value) {
  59233. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  59234. return isCoordinates(value);
  59235. };
  59236. function parseIfString (val) {
  59237. if (val !== null && val !== undefined && val.constructor === String) {
  59238. return parseFloat(val, 10);
  59239. }
  59240. return val;
  59241. }
  59242. /**
  59243. * Convert {x, y, z} object to three.js Vector3.
  59244. */
  59245. module.exports.toVector3 = function (vec3) {
  59246. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  59247. };
  59248. },{"./debug":199,"object-assign":39}],199:[function(_dereq_,module,exports){
  59249. (function (process){
  59250. var debugLib = _dereq_('debug');
  59251. var extend = _dereq_('object-assign');
  59252. var settings = {
  59253. colors: {
  59254. debug: 'gray',
  59255. error: 'red',
  59256. info: 'gray',
  59257. warn: 'orange'
  59258. }
  59259. };
  59260. /**
  59261. * Monkeypatches `debug` so we can colorize error/warning messages.
  59262. *
  59263. * (See issue: https://github.com/visionmedia/debug/issues/137)
  59264. */
  59265. var debug = function (namespace) {
  59266. var d = debugLib(namespace);
  59267. d.color = getDebugNamespaceColor(namespace);
  59268. return d;
  59269. };
  59270. extend(debug, debugLib);
  59271. /**
  59272. * Returns the type of the namespace (e.g., `error`, `warn`).
  59273. *
  59274. * @param {String} namespace
  59275. * The debug logger's namespace (e.g., `components:geometry:warn`).
  59276. * @returns {String} The type of the namespace (e.g., `warn`).
  59277. * @api private
  59278. */
  59279. function getDebugNamespaceType (namespace) {
  59280. var chunks = namespace.split(':');
  59281. return chunks[chunks.length - 1]; // Return the last one
  59282. }
  59283. /**
  59284. * Returns the color of the namespace (e.g., `orange`).
  59285. *
  59286. * @param {String} namespace
  59287. * The debug logger's namespace (e.g., `components:geometry:warn`).
  59288. * @returns {String} The color of the namespace (e.g., `orange`).
  59289. * @api private
  59290. */
  59291. function getDebugNamespaceColor (namespace) {
  59292. var type = getDebugNamespaceType(namespace);
  59293. var color = settings.colors && settings.colors[type];
  59294. return color || null;
  59295. }
  59296. /**
  59297. * Returns `localStorage` if possible.
  59298. *
  59299. * This is necessary because Safari throws when a user disables
  59300. * cookies or `localStorage` and you attempt to access it.
  59301. *
  59302. * @returns {localStorage}
  59303. * @api private
  59304. */
  59305. function storage () {
  59306. try {
  59307. return window.localStorage;
  59308. } catch (e) {
  59309. }
  59310. }
  59311. /**
  59312. * To enable console logging, type this in the Console of your Dev Tools:
  59313. *
  59314. * localStorage.logs = 1
  59315. *
  59316. * To disable console logging:
  59317. *
  59318. * localStorage.logs = 0
  59319. *
  59320. */
  59321. var ls = storage();
  59322. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  59323. debug.enable('*');
  59324. } else {
  59325. debug.enable('*:error,*:info,*:warn');
  59326. }
  59327. if (process.browser) { window.logs = debug; }
  59328. module.exports = debug;
  59329. }).call(this,_dereq_('_process'))
  59330. },{"_process":49,"debug":8,"object-assign":39}],200:[function(_dereq_,module,exports){
  59331. (function (process){
  59332. var error = _dereq_('debug')('device:error');
  59333. var vrDisplay;
  59334. var supportsVRSession = false;
  59335. var supportsARSession = false;
  59336. /**
  59337. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  59338. * We fallback to WebVR API and will hotfix when implementation is complete.
  59339. */
  59340. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  59341. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  59342. window.addEventListener('vrdisplayactivate', function (evt) {
  59343. var canvasEl;
  59344. // WebXR takes priority if available.
  59345. if (isWebXRAvailable) { return; }
  59346. canvasEl = document.createElement('canvas');
  59347. vrDisplay = evt.display;
  59348. // We need to make sure the canvas has a WebGL context associated with it.
  59349. // Otherwise, the requestPresent could be denied.
  59350. canvasEl.getContext('webgl', {});
  59351. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  59352. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  59353. });
  59354. // Support both WebVR and WebXR APIs.
  59355. if (isWebXRAvailable) {
  59356. var updateEnterInterfaces = function () {
  59357. var sceneEl = document.querySelector('a-scene');
  59358. if (!sceneEl) {
  59359. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  59360. return;
  59361. }
  59362. if (sceneEl.hasLoaded) {
  59363. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  59364. } else {
  59365. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  59366. }
  59367. };
  59368. var errorHandler = function (err) {
  59369. error('WebXR session support error: ' + err.message);
  59370. };
  59371. if (navigator.xr.isSessionSupported) {
  59372. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  59373. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  59374. supportsVRSession = supported;
  59375. updateEnterInterfaces();
  59376. }).catch(errorHandler);
  59377. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  59378. supportsARSession = supported;
  59379. updateEnterInterfaces();
  59380. }).catch(function () {});
  59381. } else if (navigator.xr.supportsSession) {
  59382. // Fallback for implementations that haven't updated to the new spec yet,
  59383. // the old version used supportsSession which is rejected for missing
  59384. // support.
  59385. navigator.xr.supportsSession('immersive-vr').then(function () {
  59386. supportsVRSession = true;
  59387. updateEnterInterfaces();
  59388. }).catch(errorHandler);
  59389. navigator.xr.supportsSession('immersive-ar').then(function () {
  59390. supportsARSession = true;
  59391. updateEnterInterfaces();
  59392. }).catch(function () {});
  59393. } else {
  59394. error('WebXR has neither isSessionSupported or supportsSession?!');
  59395. }
  59396. } else {
  59397. if (navigator.getVRDisplays) {
  59398. navigator.getVRDisplays().then(function (displays) {
  59399. var sceneEl = document.querySelector('a-scene');
  59400. vrDisplay = displays.length && displays[0];
  59401. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  59402. });
  59403. }
  59404. }
  59405. function getVRDisplay () { return vrDisplay; }
  59406. module.exports.getVRDisplay = getVRDisplay;
  59407. /**
  59408. * Determine if a headset is connected by checking if a vrDisplay is available.
  59409. */
  59410. function checkHeadsetConnected () {
  59411. return supportsVRSession || supportsARSession || !!getVRDisplay();
  59412. }
  59413. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  59414. function checkARSupport () { return supportsARSession; }
  59415. module.exports.checkARSupport = checkARSupport;
  59416. /**
  59417. * Checks if browser is mobile and not stand-alone dedicated vr device.
  59418. * @return {Boolean} True if mobile browser detected.
  59419. */
  59420. var isMobile = (function () {
  59421. var _isMobile = false;
  59422. (function (a) {
  59423. // eslint-disable-next-line no-useless-escape
  59424. 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))) {
  59425. _isMobile = true;
  59426. }
  59427. if (isIOS() || isTablet() || isR7()) {
  59428. _isMobile = true;
  59429. }
  59430. if (isMobileVR()) {
  59431. _isMobile = false;
  59432. }
  59433. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  59434. return function () { return _isMobile; };
  59435. })();
  59436. module.exports.isMobile = isMobile;
  59437. /**
  59438. * Detect tablet devices.
  59439. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  59440. */
  59441. function isTablet (mockUserAgent) {
  59442. var userAgent = mockUserAgent || window.navigator.userAgent;
  59443. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  59444. }
  59445. module.exports.isTablet = isTablet;
  59446. function isIOS () {
  59447. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  59448. }
  59449. module.exports.isIOS = isIOS;
  59450. function isMobileDeviceRequestingDesktopSite () {
  59451. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  59452. }
  59453. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  59454. /**
  59455. * Detect Oculus Browser (standalone headset)
  59456. */
  59457. function isOculusBrowser () {
  59458. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  59459. }
  59460. module.exports.isOculusBrowser = isOculusBrowser;
  59461. /**
  59462. * Detect Firefox Reality (standalone headset)
  59463. */
  59464. function isFirefoxReality () {
  59465. return /(Mobile VR)/i.test(window.navigator.userAgent);
  59466. }
  59467. module.exports.isFirefoxReality = isFirefoxReality;
  59468. /**
  59469. * Detect browsers in Stand-Alone headsets
  59470. */
  59471. function isMobileVR () {
  59472. return isOculusBrowser() || isFirefoxReality();
  59473. }
  59474. module.exports.isMobileVR = isMobileVR;
  59475. function isR7 () {
  59476. return /R7 Build/.test(window.navigator.userAgent);
  59477. }
  59478. module.exports.isR7 = isR7;
  59479. /**
  59480. * Checks mobile device orientation.
  59481. * @return {Boolean} True if landscape orientation.
  59482. */
  59483. module.exports.isLandscape = function () {
  59484. var orientation = window.orientation;
  59485. if (isR7()) { orientation += 90; }
  59486. return orientation === 90 || orientation === -90;
  59487. };
  59488. /**
  59489. * Check if running in a browser or spoofed browser (bundler).
  59490. * We need to check a node api that isn't mocked on either side.
  59491. * `require` and `module.exports` are mocked in browser by bundlers.
  59492. * `window` is mocked in node.
  59493. * `process` is also mocked by browserify, but has custom properties.
  59494. */
  59495. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  59496. /**
  59497. * Check if running in node on the server.
  59498. */
  59499. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  59500. }).call(this,_dereq_('_process'))
  59501. },{"_process":49,"debug":8}],201:[function(_dereq_,module,exports){
  59502. /**
  59503. * Split a delimited component property string (e.g., `material.color`) to an object
  59504. * containing `component` name and `property` name. If there is no delimiter, just return the
  59505. * string back.
  59506. *
  59507. * Cache arrays from splitting strings via delimiter to save on memory.
  59508. *
  59509. * @param {string} str - e.g., `material.opacity`.
  59510. * @param {string} delimiter - e.g., `.`.
  59511. * @returns {array} e.g., `['material', 'opacity']`.
  59512. */
  59513. var propertyPathCache = {};
  59514. function getComponentPropertyPath (str, delimiter) {
  59515. delimiter = delimiter || '.';
  59516. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  59517. if (str.indexOf(delimiter) !== -1) {
  59518. propertyPathCache[delimiter][str] = str.split(delimiter);
  59519. } else {
  59520. propertyPathCache[delimiter][str] = str;
  59521. }
  59522. return propertyPathCache[delimiter][str];
  59523. }
  59524. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  59525. module.exports.propertyPathCache = propertyPathCache;
  59526. /**
  59527. * Get component property using encoded component name + component property name with a
  59528. * delimiter.
  59529. */
  59530. module.exports.getComponentProperty = function (el, name, delimiter) {
  59531. var splitName;
  59532. delimiter = delimiter || '.';
  59533. if (name.indexOf(delimiter) !== -1) {
  59534. splitName = getComponentPropertyPath(name, delimiter);
  59535. if (splitName.constructor === String) {
  59536. return el.getAttribute(splitName);
  59537. }
  59538. return el.getAttribute(splitName[0])[splitName[1]];
  59539. }
  59540. return el.getAttribute(name);
  59541. };
  59542. /**
  59543. * Set component property using encoded component name + component property name with a
  59544. * delimiter.
  59545. */
  59546. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  59547. var splitName;
  59548. delimiter = delimiter || '.';
  59549. if (name.indexOf(delimiter) !== -1) {
  59550. splitName = getComponentPropertyPath(name, delimiter);
  59551. if (splitName.constructor === String) {
  59552. el.setAttribute(splitName, value);
  59553. } else {
  59554. el.setAttribute(splitName[0], splitName[1], value);
  59555. }
  59556. return;
  59557. }
  59558. el.setAttribute(name, value);
  59559. };
  59560. },{}],202:[function(_dereq_,module,exports){
  59561. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  59562. var width = canvasEl.style.width;
  59563. var height = canvasEl.style.height;
  59564. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  59565. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  59566. // By changing the size 1 pixel and restoring the previous value
  59567. // we trigger a size recalculation cycle.
  59568. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  59569. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  59570. setTimeout(function () {
  59571. canvasEl.style.width = width;
  59572. canvasEl.style.height = height;
  59573. }, 200);
  59574. };
  59575. },{}],203:[function(_dereq_,module,exports){
  59576. /* global location */
  59577. /* Centralized place to reference utilities since utils is exposed to the user. */
  59578. var debug = _dereq_('./debug');
  59579. var deepAssign = _dereq_('deep-assign');
  59580. var device = _dereq_('./device');
  59581. var objectAssign = _dereq_('object-assign');
  59582. var objectPool = _dereq_('./object-pool');
  59583. var warn = debug('utils:warn');
  59584. module.exports.bind = _dereq_('./bind');
  59585. module.exports.coordinates = _dereq_('./coordinates');
  59586. module.exports.debug = debug;
  59587. module.exports.device = device;
  59588. module.exports.entity = _dereq_('./entity');
  59589. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  59590. module.exports.isIE11 = _dereq_('./is-ie11');
  59591. module.exports.material = _dereq_('./material');
  59592. module.exports.objectPool = objectPool;
  59593. module.exports.split = _dereq_('./split').split;
  59594. module.exports.styleParser = _dereq_('./styleParser');
  59595. module.exports.trackedControls = _dereq_('./tracked-controls');
  59596. module.exports.checkHeadsetConnected = function () {
  59597. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  59598. return device.checkHeadsetConnected(arguments);
  59599. };
  59600. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  59601. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  59602. };
  59603. module.exports.isIOS = function () {
  59604. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  59605. return device.isIOS(arguments);
  59606. };
  59607. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  59608. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  59609. };
  59610. module.exports.isMobile = function () {
  59611. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  59612. return device.isMobile(arguments);
  59613. };
  59614. /**
  59615. * Returns throttle function that gets called at most once every interval.
  59616. *
  59617. * @param {function} functionToThrottle
  59618. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  59619. * @param {object} optionalContext - If given, bind function to throttle to this context.
  59620. * @returns {function} Throttled function.
  59621. */
  59622. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  59623. var lastTime;
  59624. if (optionalContext) {
  59625. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  59626. }
  59627. return function () {
  59628. var time = Date.now();
  59629. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  59630. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  59631. lastTime = time;
  59632. functionToThrottle.apply(null, arguments);
  59633. }
  59634. };
  59635. };
  59636. /**
  59637. * Returns throttle function that gets called at most once every interval.
  59638. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  59639. *
  59640. * @param {function} functionToThrottle
  59641. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  59642. * @param {object} optionalContext - If given, bind function to throttle to this context.
  59643. * @returns {function} Throttled function.
  59644. */
  59645. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  59646. var lastTime;
  59647. if (optionalContext) {
  59648. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  59649. }
  59650. return function (time, delta) {
  59651. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  59652. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  59653. lastTime = time;
  59654. functionToThrottle(time, sinceLastTime);
  59655. }
  59656. };
  59657. };
  59658. /**
  59659. * Returns debounce function that gets called only once after a set of repeated calls.
  59660. *
  59661. * @param {function} functionToDebounce
  59662. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  59663. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  59664. * @returns {function} Debounced function.
  59665. */
  59666. module.exports.debounce = function (func, wait, immediate) {
  59667. var timeout;
  59668. return function () {
  59669. var context = this;
  59670. var args = arguments;
  59671. var later = function () {
  59672. timeout = null;
  59673. if (!immediate) func.apply(context, args);
  59674. };
  59675. var callNow = immediate && !timeout;
  59676. clearTimeout(timeout);
  59677. timeout = setTimeout(later, wait);
  59678. if (callNow) func.apply(context, args);
  59679. };
  59680. };
  59681. /**
  59682. * Mix the properties of source object(s) into a destination object.
  59683. *
  59684. * @param {object} dest - The object to which properties will be copied.
  59685. * @param {...object} source - The object(s) from which properties will be copied.
  59686. */
  59687. module.exports.extend = objectAssign;
  59688. module.exports.extendDeep = deepAssign;
  59689. module.exports.clone = function (obj) {
  59690. return JSON.parse(JSON.stringify(obj));
  59691. };
  59692. /**
  59693. * Checks if two values are equal.
  59694. * Includes objects and arrays and nested objects and arrays.
  59695. * Try to keep this function performant as it will be called often to see if a component
  59696. * should be updated.
  59697. *
  59698. * @param {object} a - First object.
  59699. * @param {object} b - Second object.
  59700. * @returns {boolean} Whether two objects are deeply equal.
  59701. */
  59702. var deepEqual = (function () {
  59703. var arrayPool = objectPool.createPool(function () { return []; });
  59704. return function (a, b) {
  59705. var key;
  59706. var keysA;
  59707. var keysB;
  59708. var i;
  59709. var valA;
  59710. var valB;
  59711. // If not objects or arrays, compare as values.
  59712. if (a === undefined || b === undefined || a === null || b === null ||
  59713. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  59714. (a.constructor === Array && b.constructor === Array))) {
  59715. return a === b;
  59716. }
  59717. // Different number of keys, not equal.
  59718. keysA = arrayPool.use();
  59719. keysB = arrayPool.use();
  59720. keysA.length = 0;
  59721. keysB.length = 0;
  59722. for (key in a) { keysA.push(key); }
  59723. for (key in b) { keysB.push(key); }
  59724. if (keysA.length !== keysB.length) {
  59725. arrayPool.recycle(keysA);
  59726. arrayPool.recycle(keysB);
  59727. return false;
  59728. }
  59729. // Return `false` at the first sign of inequality.
  59730. for (i = 0; i < keysA.length; ++i) {
  59731. valA = a[keysA[i]];
  59732. valB = b[keysA[i]];
  59733. // Check nested array and object.
  59734. if ((typeof valA === 'object' || typeof valB === 'object') ||
  59735. (Array.isArray(valA) && Array.isArray(valB))) {
  59736. if (valA === valB) { continue; }
  59737. if (!deepEqual(valA, valB)) {
  59738. arrayPool.recycle(keysA);
  59739. arrayPool.recycle(keysB);
  59740. return false;
  59741. }
  59742. } else if (valA !== valB) {
  59743. arrayPool.recycle(keysA);
  59744. arrayPool.recycle(keysB);
  59745. return false;
  59746. }
  59747. }
  59748. arrayPool.recycle(keysA);
  59749. arrayPool.recycle(keysB);
  59750. return true;
  59751. };
  59752. })();
  59753. module.exports.deepEqual = deepEqual;
  59754. /**
  59755. * Computes the difference between two objects.
  59756. *
  59757. * @param {object} a - First object to compare (e.g., oldData).
  59758. * @param {object} b - Second object to compare (e.g., newData).
  59759. * @returns {object}
  59760. * Difference object where set of keys note which values were not equal, and values are
  59761. * `b`'s values.
  59762. */
  59763. module.exports.diff = (function () {
  59764. var keys = [];
  59765. return function (a, b, targetObject) {
  59766. var aVal;
  59767. var bVal;
  59768. var bKey;
  59769. var diff;
  59770. var key;
  59771. var i;
  59772. var isComparingObjects;
  59773. diff = targetObject || {};
  59774. // Collect A keys.
  59775. keys.length = 0;
  59776. for (key in a) { keys.push(key); }
  59777. if (!b) { return diff; }
  59778. // Collect B keys.
  59779. for (bKey in b) {
  59780. if (keys.indexOf(bKey) === -1) {
  59781. keys.push(bKey);
  59782. }
  59783. }
  59784. for (i = 0; i < keys.length; i++) {
  59785. key = keys[i];
  59786. aVal = a[key];
  59787. bVal = b[key];
  59788. isComparingObjects = aVal && bVal &&
  59789. aVal.constructor === Object && bVal.constructor === Object;
  59790. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  59791. (!isComparingObjects && aVal !== bVal)) {
  59792. diff[key] = bVal;
  59793. }
  59794. }
  59795. return diff;
  59796. };
  59797. })();
  59798. /**
  59799. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  59800. * @param {Event} event Event object.
  59801. * @returns {Boolean} Whether the key event should be captured.
  59802. */
  59803. module.exports.shouldCaptureKeyEvent = function (event) {
  59804. if (event.metaKey) { return false; }
  59805. return document.activeElement === document.body;
  59806. };
  59807. /**
  59808. * Splits a string into an array based on a delimiter.
  59809. *
  59810. * @param {string=} [str=''] Source string
  59811. * @param {string=} [delimiter=' '] Delimiter to use
  59812. * @returns {array} Array of delimited strings
  59813. */
  59814. module.exports.splitString = function (str, delimiter) {
  59815. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  59816. // First collapse the whitespace (or whatever the delimiter is).
  59817. var regex = new RegExp(delimiter, 'g');
  59818. str = (str || '').replace(regex, delimiter);
  59819. // Then split.
  59820. return str.split(delimiter);
  59821. };
  59822. /**
  59823. * Extracts data from the element given an object that contains expected keys.
  59824. *
  59825. * @param {Element} Source element.
  59826. * @param {Object} [defaults={}] Object of default key-value pairs.
  59827. * @returns {Object}
  59828. */
  59829. module.exports.getElData = function (el, defaults) {
  59830. defaults = defaults || {};
  59831. var data = {};
  59832. Object.keys(defaults).forEach(copyAttribute);
  59833. function copyAttribute (key) {
  59834. if (el.hasAttribute(key)) {
  59835. data[key] = el.getAttribute(key);
  59836. }
  59837. }
  59838. return data;
  59839. };
  59840. /**
  59841. * Retrieves querystring value.
  59842. * @param {String} name Name of querystring key.
  59843. * @return {String} Value
  59844. */
  59845. module.exports.getUrlParameter = function (name) {
  59846. // eslint-disable-next-line no-useless-escape
  59847. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  59848. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  59849. var results = regex.exec(location.search);
  59850. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  59851. };
  59852. /**
  59853. * Detects whether context is within iframe.
  59854. */
  59855. module.exports.isIframed = function () {
  59856. return window.top !== window.self;
  59857. };
  59858. /**
  59859. * Finds all elements under the element that have the isScene
  59860. * property set to true
  59861. */
  59862. module.exports.findAllScenes = function (el) {
  59863. var matchingElements = [];
  59864. var allElements = el.getElementsByTagName('*');
  59865. for (var i = 0, n = allElements.length; i < n; i++) {
  59866. if (allElements[i].isScene) {
  59867. // Element exists with isScene set.
  59868. matchingElements.push(allElements[i]);
  59869. }
  59870. }
  59871. return matchingElements;
  59872. };
  59873. // Must be at bottom to avoid circular dependency.
  59874. module.exports.srcLoader = _dereq_('./src-loader');
  59875. },{"./bind":197,"./coordinates":198,"./debug":199,"./device":200,"./entity":201,"./forceCanvasResizeSafariMobile":202,"./is-ie11":204,"./material":206,"./object-pool":207,"./split":208,"./src-loader":209,"./styleParser":210,"./tracked-controls":211,"deep-assign":10,"object-assign":39}],204:[function(_dereq_,module,exports){
  59876. // https://stackoverflow.com/a/17907562
  59877. function getInternetExplorerVersion () {
  59878. var version = -1;
  59879. var userAgent = navigator.userAgent;
  59880. var re;
  59881. if (navigator.appName === 'Microsoft Internet Explorer') {
  59882. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  59883. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  59884. } else if (navigator.appName === 'Netscape') {
  59885. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  59886. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  59887. }
  59888. return version;
  59889. }
  59890. module.exports = getInternetExplorerVersion() === 11;
  59891. },{}],205:[function(_dereq_,module,exports){
  59892. /**
  59893. * Check if device is iOS and older than version 10.
  59894. */
  59895. module.exports = function isIOSOlderThan10 (userAgent) {
  59896. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  59897. };
  59898. },{}],206:[function(_dereq_,module,exports){
  59899. var THREE = _dereq_('../lib/three');
  59900. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  59901. var COLOR_MAPS = new Set([
  59902. 'emissiveMap',
  59903. 'envMap',
  59904. 'map',
  59905. 'specularMap'
  59906. ]);
  59907. /**
  59908. * Update `material` texture property (usually but not always `map`)
  59909. * from `data` property (usually but not always `src`)
  59910. *
  59911. * @param {object} shader - A-Frame shader instance.
  59912. * @param {object} data
  59913. */
  59914. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  59915. var el = shader.el;
  59916. var material = shader.material;
  59917. var rendererSystem = el.sceneEl.systems.renderer;
  59918. var src = data[dataName];
  59919. // Because a single material / shader may have multiple textures,
  59920. // we need to remember the source value for this data property
  59921. // to avoid redundant operations which can be expensive otherwise
  59922. // (e.g. video texture loads).
  59923. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  59924. if (!src) {
  59925. // Forget the prior material src.
  59926. delete shader.materialSrcs[materialName];
  59927. // Remove the texture.
  59928. setMap(null);
  59929. return;
  59930. }
  59931. // Don't process if material src hasn't changed.
  59932. if (src === shader.materialSrcs[materialName]) { return; }
  59933. // Remember the new src for this texture (there may be multiple).
  59934. shader.materialSrcs[materialName] = src;
  59935. // If the new material src is already a texture, just use it.
  59936. if (src instanceof THREE.Texture) { setMap(src); } else {
  59937. // Load texture for the new material src.
  59938. // (And check if we should still use it once available in callback.)
  59939. el.sceneEl.systems.material.loadTexture(src,
  59940. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  59941. checkSetMap);
  59942. }
  59943. function checkSetMap (texture) {
  59944. // If the source has been changed, don't use loaded texture.
  59945. if (shader.materialSrcs[materialName] !== src) { return; }
  59946. setMap(texture);
  59947. }
  59948. function setMap (texture) {
  59949. material[materialName] = texture;
  59950. if (texture && COLOR_MAPS.has(materialName)) {
  59951. rendererSystem.applyColorCorrection(texture);
  59952. }
  59953. material.needsUpdate = true;
  59954. handleTextureEvents(el, texture);
  59955. }
  59956. };
  59957. /**
  59958. * Update `material.map` given `data.src`. For standard and flat shaders.
  59959. *
  59960. * @param {object} shader - A-Frame shader instance.
  59961. * @param {object} data
  59962. */
  59963. module.exports.updateMap = function (shader, data) {
  59964. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  59965. };
  59966. /**
  59967. * Updates the material's maps which give the illusion of extra geometry.
  59968. *
  59969. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  59970. * @param {object} shader - A-Frame shader instance
  59971. * @param {object} data
  59972. */
  59973. module.exports.updateDistortionMap = function (longType, shader, data) {
  59974. var shortType = longType;
  59975. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  59976. var el = shader.el;
  59977. var material = shader.material;
  59978. var rendererSystem = el.sceneEl.systems.renderer;
  59979. var src = data[longType + 'Map'];
  59980. var info = {};
  59981. info.src = src;
  59982. // Pass through the repeat and offset to be handled by the material loader.
  59983. info.offset = data[longType + 'TextureOffset'];
  59984. info.repeat = data[longType + 'TextureRepeat'];
  59985. info.wrap = data[longType + 'TextureWrap'];
  59986. if (src) {
  59987. if (src === shader[longType + 'TextureSrc']) { return; }
  59988. // Texture added or changed.
  59989. shader[longType + 'TextureSrc'] = src;
  59990. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  59991. return;
  59992. }
  59993. // Texture removed.
  59994. if (!material.map) { return; }
  59995. setMap(null);
  59996. function setMap (texture) {
  59997. var slot = shortType + 'Map';
  59998. material[slot] = texture;
  59999. if (texture && COLOR_MAPS.has(slot)) {
  60000. rendererSystem.applyColorCorrection(texture);
  60001. }
  60002. material.needsUpdate = true;
  60003. handleTextureEvents(el, texture);
  60004. }
  60005. };
  60006. /**
  60007. * Emit event on entities on texture-related events.
  60008. *
  60009. * @param {Element} el - Entity.
  60010. * @param {object} texture - three.js Texture.
  60011. */
  60012. function handleTextureEvents (el, texture) {
  60013. if (!texture) { return; }
  60014. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  60015. // Video events.
  60016. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  60017. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  60018. // Check to see if we need to use iOS 10 HLS shader.
  60019. // Only override the shader if it is stock shader that we know doesn't correct.
  60020. if (!el.components || !el.components.material) { return; }
  60021. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  60022. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  60023. el.setAttribute('material', 'shader', 'ios10hls');
  60024. }
  60025. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  60026. });
  60027. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  60028. // Works for non-looping videos only.
  60029. el.emit('materialvideoended', {src: texture.image, texture: texture});
  60030. });
  60031. }
  60032. module.exports.handleTextureEvents = handleTextureEvents;
  60033. /**
  60034. * Given video element src and type, guess whether stream is HLS.
  60035. *
  60036. * @param {string} src - src from video element (generally URL to content).
  60037. * @param {string} type - type from video element (generally MIME type if present).
  60038. */
  60039. module.exports.isHLS = function (src, type) {
  60040. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  60041. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  60042. return false;
  60043. };
  60044. },{"../lib/three":177}],207:[function(_dereq_,module,exports){
  60045. /*
  60046. Adapted deePool by Kyle Simpson.
  60047. MIT License: http://getify.mit-license.org
  60048. */
  60049. var EMPTY_SLOT = Object.freeze(Object.create(null));
  60050. // Default object factory.
  60051. function defaultObjectFactory () { return {}; }
  60052. /**
  60053. * Create a new pool.
  60054. */
  60055. module.exports.createPool = function createPool (objectFactory) {
  60056. var objPool = [];
  60057. var nextFreeSlot = null; // Pool location to look for a free object to use.
  60058. objectFactory = objectFactory || defaultObjectFactory;
  60059. function use () {
  60060. var objToUse;
  60061. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  60062. grow(objPool.length || 5);
  60063. }
  60064. objToUse = objPool[nextFreeSlot];
  60065. objPool[nextFreeSlot++] = EMPTY_SLOT;
  60066. clearObject(objToUse);
  60067. return objToUse;
  60068. }
  60069. function recycle (obj) {
  60070. if (!(obj instanceof Object)) { return; }
  60071. if (nextFreeSlot === null || nextFreeSlot === -1) {
  60072. objPool[objPool.length] = obj;
  60073. return;
  60074. }
  60075. objPool[--nextFreeSlot] = obj;
  60076. }
  60077. function grow (count) {
  60078. var currentLength;
  60079. var i;
  60080. count = count === undefined ? objPool.length : count;
  60081. if (count > 0 && nextFreeSlot == null) {
  60082. nextFreeSlot = 0;
  60083. }
  60084. if (count > 0) {
  60085. currentLength = objPool.length;
  60086. objPool.length += Number(count);
  60087. for (i = currentLength; i < objPool.length; i++) {
  60088. // Add new obj to pool.
  60089. objPool[i] = objectFactory();
  60090. }
  60091. }
  60092. return objPool.length;
  60093. }
  60094. function size () {
  60095. return objPool.length;
  60096. }
  60097. return {
  60098. grow: grow,
  60099. pool: objPool,
  60100. recycle: recycle,
  60101. size: size,
  60102. use: use
  60103. };
  60104. };
  60105. function clearObject (obj) {
  60106. var key;
  60107. if (!obj || obj.constructor !== Object) { return; }
  60108. for (key in obj) { obj[key] = undefined; }
  60109. }
  60110. module.exports.clearObject = clearObject;
  60111. function removeUnusedKeys (obj, schema) {
  60112. var key;
  60113. if (!obj || obj.constructor !== Object) { return; }
  60114. for (key in obj) {
  60115. if (!(key in schema)) {
  60116. delete obj[key];
  60117. }
  60118. }
  60119. }
  60120. module.exports.removeUnusedKeys = removeUnusedKeys;
  60121. },{}],208:[function(_dereq_,module,exports){
  60122. /**
  60123. * String split with cached result.
  60124. */
  60125. module.exports.split = (function () {
  60126. var splitCache = {};
  60127. return function (str, delimiter) {
  60128. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  60129. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  60130. splitCache[delimiter][str] = str.split(delimiter);
  60131. return splitCache[delimiter][str];
  60132. };
  60133. })();
  60134. },{}],209:[function(_dereq_,module,exports){
  60135. /* global Image, XMLHttpRequest */
  60136. var debug = _dereq_('./debug');
  60137. var warn = debug('utils:src-loader:warn');
  60138. /**
  60139. * Validate a texture, either as a selector or as a URL.
  60140. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  60141. * callback.
  60142. *
  60143. * `src` will be passed into the callback
  60144. *
  60145. * @params {string|Element} src - URL or media element.
  60146. * @params {function} isImageCb - callback if texture is an image.
  60147. * @params {function} isVideoCb - callback if texture is a video.
  60148. */
  60149. function validateSrc (src, isImageCb, isVideoCb) {
  60150. checkIsImage(src, function isAnImageUrl (isImage) {
  60151. if (isImage) {
  60152. isImageCb(src);
  60153. return;
  60154. }
  60155. isVideoCb(src);
  60156. });
  60157. }
  60158. /**
  60159. * Validates six images as a cubemap, either as selector or comma-separated
  60160. * URLs.
  60161. *
  60162. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  60163. must be wrapped by `url()`.
  60164. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  60165. must be wrapped by `url()`.
  60166. */
  60167. function validateCubemapSrc (src, cb) {
  60168. var aCubemap;
  60169. var cubemapSrcRegex = '';
  60170. var i;
  60171. var urls;
  60172. var validatedUrls = [];
  60173. for (i = 0; i < 5; i++) {
  60174. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  60175. }
  60176. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  60177. urls = src.match(new RegExp(cubemapSrcRegex));
  60178. // `src` is a comma-separated list of URLs.
  60179. // In this case, re-use validateSrc for each side of the cube.
  60180. function isImageCb (url) {
  60181. validatedUrls.push(url);
  60182. if (validatedUrls.length === 6) {
  60183. cb(validatedUrls);
  60184. }
  60185. }
  60186. if (urls) {
  60187. for (i = 1; i < 7; i++) {
  60188. validateSrc(parseUrl(urls[i]), isImageCb);
  60189. }
  60190. return;
  60191. }
  60192. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  60193. aCubemap = validateAndGetQuerySelector(src);
  60194. if (!aCubemap) { return; }
  60195. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  60196. return cb(aCubemap.srcs);
  60197. }
  60198. // Else if aCubeMap is not a <a-cubemap>.
  60199. warn('Selector "%s" does not point to <a-cubemap>', src);
  60200. }
  60201. /**
  60202. * Parses src from `url(src)`.
  60203. * @param {string} src - String to parse.
  60204. * @return {string} The parsed src, if parseable.
  60205. */
  60206. function parseUrl (src) {
  60207. var parsedSrc = src.match(/\url\((.+)\)/);
  60208. if (!parsedSrc) { return; }
  60209. return parsedSrc[1];
  60210. }
  60211. /**
  60212. * Call back whether `src` is an image.
  60213. *
  60214. * @param {string|Element} src - URL or element that will be tested.
  60215. * @param {function} onResult - Callback with whether `src` is an image.
  60216. */
  60217. function checkIsImage (src, onResult) {
  60218. var request;
  60219. if (src.tagName) {
  60220. onResult(src.tagName === 'IMG');
  60221. return;
  60222. }
  60223. request = new XMLHttpRequest();
  60224. // Try to send HEAD request to check if image first.
  60225. request.open('HEAD', src);
  60226. request.addEventListener('load', function (event) {
  60227. var contentType;
  60228. if (request.status >= 200 && request.status < 300) {
  60229. contentType = request.getResponseHeader('Content-Type');
  60230. if (contentType == null) {
  60231. checkIsImageFallback(src, onResult);
  60232. } else {
  60233. if (contentType.startsWith('image')) {
  60234. onResult(true);
  60235. } else {
  60236. onResult(false);
  60237. }
  60238. }
  60239. } else {
  60240. checkIsImageFallback(src, onResult);
  60241. }
  60242. request.abort();
  60243. });
  60244. request.send();
  60245. }
  60246. function checkIsImageFallback (src, onResult) {
  60247. var tester = new Image();
  60248. tester.addEventListener('load', onLoad);
  60249. function onLoad () { onResult(true); }
  60250. tester.addEventListener('error', onError);
  60251. function onError () { onResult(false); }
  60252. tester.src = src;
  60253. }
  60254. /**
  60255. * Query and validate a query selector,
  60256. *
  60257. * @param {string} selector - DOM selector.
  60258. * @return {object|null|undefined} Selected DOM element if exists.
  60259. null if query yields no results.
  60260. undefined if `selector` is not a valid selector.
  60261. */
  60262. function validateAndGetQuerySelector (selector) {
  60263. try {
  60264. var el = document.querySelector(selector);
  60265. if (!el) {
  60266. warn('No element was found matching the selector: "%s"', selector);
  60267. }
  60268. return el;
  60269. } catch (e) { // Capture exception if it's not a valid selector.
  60270. warn('"%s" is not a valid selector', selector);
  60271. return undefined;
  60272. }
  60273. }
  60274. module.exports = {
  60275. parseUrl: parseUrl,
  60276. validateSrc: validateSrc,
  60277. validateCubemapSrc: validateCubemapSrc
  60278. };
  60279. },{"./debug":199}],210:[function(_dereq_,module,exports){
  60280. /**
  60281. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  60282. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  60283. * by Josh Johnston (MIT License).
  60284. */
  60285. var DASH_REGEX = /-([a-z])/g;
  60286. /**
  60287. * Deserialize style-like string into an object of properties.
  60288. *
  60289. * @param {string} value - HTML attribute value.
  60290. * @param {object} obj - Reused object for object pooling.
  60291. * @returns {object} Property data.
  60292. */
  60293. module.exports.parse = function (value, obj) {
  60294. var parsedData;
  60295. if (typeof value !== 'string') { return value; }
  60296. parsedData = styleParse(value, obj);
  60297. // The style parser returns an object { "" : "test"} when fed a string
  60298. if (parsedData['']) { return value; }
  60299. return transformKeysToCamelCase(parsedData);
  60300. };
  60301. /**
  60302. * Serialize an object of properties into a style-like string.
  60303. *
  60304. * @param {object} data - Property data.
  60305. * @returns {string}
  60306. */
  60307. module.exports.stringify = function (data) {
  60308. if (typeof data === 'string') { return data; }
  60309. return styleStringify(data);
  60310. };
  60311. /**
  60312. * Converts string from hyphen to camelCase.
  60313. *
  60314. * @param {string} str - String to camelCase.
  60315. * @return {string} CamelCased string.
  60316. */
  60317. function toCamelCase (str) {
  60318. return str.replace(DASH_REGEX, upperCase);
  60319. }
  60320. module.exports.toCamelCase = toCamelCase;
  60321. /**
  60322. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  60323. * `maxValue`).
  60324. *
  60325. * @param {object} obj - The object to camelCase keys.
  60326. * @return {object} The object with keys camelCased.
  60327. */
  60328. function transformKeysToCamelCase (obj) {
  60329. var camelKey;
  60330. var key;
  60331. for (key in obj) {
  60332. camelKey = toCamelCase(key);
  60333. if (key === camelKey) { continue; }
  60334. obj[camelKey] = obj[key];
  60335. delete obj[key];
  60336. }
  60337. return obj;
  60338. }
  60339. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  60340. /**
  60341. * Split a string into chunks matching `<key>: <value>`
  60342. */
  60343. var getKeyValueChunks = (function () {
  60344. var chunks = [];
  60345. var hasUnclosedUrl = /url\([^)]+$/;
  60346. return function getKeyValueChunks (raw) {
  60347. var chunk = '';
  60348. var nextSplit;
  60349. var offset = 0;
  60350. var sep = ';';
  60351. chunks.length = 0;
  60352. while (offset < raw.length) {
  60353. nextSplit = raw.indexOf(sep, offset);
  60354. if (nextSplit === -1) { nextSplit = raw.length; }
  60355. chunk += raw.substring(offset, nextSplit);
  60356. // data URIs can contain semicolons, so make sure we get the whole thing
  60357. if (hasUnclosedUrl.test(chunk)) {
  60358. chunk += ';';
  60359. offset = nextSplit + 1;
  60360. continue;
  60361. }
  60362. chunks.push(chunk.trim());
  60363. chunk = '';
  60364. offset = nextSplit + 1;
  60365. }
  60366. return chunks;
  60367. };
  60368. })();
  60369. /**
  60370. * Convert a style attribute string to an object.
  60371. *
  60372. * @param {object} str - Attribute string.
  60373. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  60374. */
  60375. function styleParse (str, obj) {
  60376. var chunks;
  60377. var i;
  60378. var item;
  60379. var pos;
  60380. var key;
  60381. var val;
  60382. obj = obj || {};
  60383. chunks = getKeyValueChunks(str);
  60384. for (i = 0; i < chunks.length; i++) {
  60385. item = chunks[i];
  60386. if (!item) { continue; }
  60387. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  60388. pos = item.indexOf(':');
  60389. key = item.substr(0, pos).trim();
  60390. val = item.substr(pos + 1).trim();
  60391. obj[key] = val;
  60392. }
  60393. return obj;
  60394. }
  60395. /**
  60396. * Convert an object into an attribute string
  60397. **/
  60398. function styleStringify (obj) {
  60399. var key;
  60400. var keyCount = 0;
  60401. var i = 0;
  60402. var str = '';
  60403. for (key in obj) { keyCount++; }
  60404. for (key in obj) {
  60405. str += (key + ': ' + obj[key]);
  60406. if (i < keyCount - 1) { str += '; '; }
  60407. i++;
  60408. }
  60409. return str;
  60410. }
  60411. function upperCase (str) { return str[1].toUpperCase(); }
  60412. },{}],211:[function(_dereq_,module,exports){
  60413. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  60414. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  60415. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  60416. /**
  60417. * Called on controller component `.play` handlers.
  60418. * Check if controller matches parameters and inject tracked-controls component.
  60419. * Handle event listeners.
  60420. * Generate controllerconnected or controllerdisconnected events.
  60421. *
  60422. * @param {object} component - Tracked controls component.
  60423. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  60424. * @param {object} queryObject - Map of values to match.
  60425. */
  60426. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  60427. var el = component.el;
  60428. var controller;
  60429. var hasWebXR = el.sceneEl.hasWebXR;
  60430. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  60431. var isPresent;
  60432. controller = isControllerPresent(component, idPrefix, queryObject);
  60433. isPresent = !!controller;
  60434. // If component was previously paused and now playing, re-add event listeners.
  60435. // Handle the event listeners here since this helper method is control of calling
  60436. // `.addEventListeners` and `.removeEventListeners`.
  60437. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  60438. component.addEventListeners();
  60439. }
  60440. // Nothing changed, no need to do anything.
  60441. if (isPresent === component.controllerPresent) { return isPresent; }
  60442. component.controllerPresent = isPresent;
  60443. // Update controller presence.
  60444. if (isPresent) {
  60445. component.addEventListeners();
  60446. component.injectTrackedControls();
  60447. el.emit('controllerconnected', {name: component.name, component: component});
  60448. } else {
  60449. component.removeEventListeners();
  60450. el.emit('controllerdisconnected', {name: component.name, component: component});
  60451. }
  60452. };
  60453. /**
  60454. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  60455. *
  60456. * @param {object} component - Tracked controls component.
  60457. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  60458. * @param {object} queryObject - Map of values to match.
  60459. */
  60460. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  60461. var gamepads;
  60462. var sceneEl = component.el.sceneEl;
  60463. var trackedControlsSystem;
  60464. var filterControllerIndex = queryObject.index || 0;
  60465. if (!idPrefix) { return false; }
  60466. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  60467. if (!trackedControlsSystem) { return false; }
  60468. gamepads = trackedControlsSystem.controllers;
  60469. if (!gamepads.length) { return false; }
  60470. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  60471. filterControllerIndex);
  60472. }
  60473. /**
  60474. *
  60475. * @param {object} component - Tracked controls component.
  60476. */
  60477. function isControllerPresentWebXR (component, id, queryObject) {
  60478. var controllers;
  60479. var sceneEl = component.el.sceneEl;
  60480. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  60481. if (!trackedControlsSystem) { return false; }
  60482. controllers = trackedControlsSystem.controllers;
  60483. if (!controllers || !controllers.length) { return false; }
  60484. return findMatchingControllerWebXR(
  60485. controllers, id,
  60486. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles, queryObject.handTracking);
  60487. }
  60488. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  60489. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  60490. /**
  60491. * Walk through the given controllers to find any where the device ID equals
  60492. * filterIdExact, or startsWith filterIdPrefix.
  60493. * A controller where this considered true is considered a 'match'.
  60494. *
  60495. * For each matching controller:
  60496. * If filterHand is set, and the controller:
  60497. * is handed, we further verify that controller.hand equals filterHand.
  60498. * is unhanded (controller.hand is ''), we skip until we have found a
  60499. * number of matching controllers that equals filterControllerIndex
  60500. * If filterHand is not set, we skip until we have found the nth matching
  60501. * controller, where n equals filterControllerIndex
  60502. *
  60503. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  60504. * one or both of: [filterHand, filterControllerIndex]
  60505. *
  60506. * @param {object} controllers - Array of gamepads to search
  60507. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  60508. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  60509. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  60510. * @param {object} filterControllerIndex - Find the nth matching controller,
  60511. * where n equals filterControllerIndex. defaults to 0.
  60512. */
  60513. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  60514. filterControllerIndex) {
  60515. var controller;
  60516. var i;
  60517. var matchingControllerOccurence = 0;
  60518. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  60519. for (i = 0; i < controllers.length; i++) {
  60520. controller = controllers[i];
  60521. // Determine if the controller ID matches our criteria.
  60522. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  60523. continue;
  60524. }
  60525. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  60526. // If the hand filter and controller handedness are defined we compare them.
  60527. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  60528. // If we have detected an unhanded controller and the component was asking
  60529. // for a particular hand, we need to treat the controllers in the array as
  60530. // pairs of controllers. This effectively means that we need to skip
  60531. // NUM_HANDS matches for each controller number, instead of 1.
  60532. if (filterHand && !controller.hand) {
  60533. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  60534. } else {
  60535. return controller;
  60536. }
  60537. // We are looking for the nth occurence of a matching controller
  60538. // (n equals targetControllerMatch).
  60539. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  60540. ++matchingControllerOccurence;
  60541. }
  60542. return undefined;
  60543. }
  60544. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles, handTracking) {
  60545. var i;
  60546. var j;
  60547. var controller;
  60548. var controllerMatch = false;
  60549. var controllerHasHandedness;
  60550. var profiles;
  60551. for (i = 0; i < controllers.length; i++) {
  60552. controller = controllers[i];
  60553. profiles = controller.profiles;
  60554. if (handTracking) {
  60555. controllerMatch = controller.hand;
  60556. } else {
  60557. if (iterateProfiles) {
  60558. for (j = 0; j < profiles.length; j++) {
  60559. controllerMatch = profiles[j].startsWith(idPrefix);
  60560. if (controllerMatch) { break; }
  60561. }
  60562. } else {
  60563. controllerMatch = profiles.length > 0 && profiles[0].startsWith(idPrefix);
  60564. }
  60565. }
  60566. if (!controllerMatch) { continue; }
  60567. // Vive controllers are assigned handedness at runtime and it might not be always available.
  60568. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  60569. if (controllerHasHandedness) {
  60570. if (controller.handedness === handedness) { return controllers[i]; }
  60571. } else { // Fallback to index if controller has no handedness.
  60572. if ((i === index)) { return controllers[i]; }
  60573. }
  60574. }
  60575. return undefined;
  60576. }
  60577. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  60578. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  60579. /**
  60580. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  60581. *
  60582. * @param {object} component - Controller component in use.
  60583. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  60584. * @param {object} evt - Event to process.
  60585. */
  60586. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  60587. var axes;
  60588. var buttonType;
  60589. var changed;
  60590. var detail;
  60591. var j;
  60592. for (buttonType in axesMapping) {
  60593. axes = axesMapping[buttonType];
  60594. changed = false;
  60595. for (j = 0; j < axes.length; j++) {
  60596. if (evt.detail.changed[axes[j]]) { changed = true; }
  60597. }
  60598. if (!changed) { continue; }
  60599. // Axis has changed. Emit the specific moved event with axis values in detail.
  60600. detail = {};
  60601. for (j = 0; j < axes.length; j++) {
  60602. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  60603. }
  60604. component.el.emit(buttonType + 'moved', detail);
  60605. }
  60606. };
  60607. /**
  60608. * Handle a button event and reemits the events.
  60609. *
  60610. * @param {string} id - id of the button.
  60611. * @param {string} evtName - name of the reemitted event
  60612. * @param {object} component - reference to the component
  60613. * @param {string} hand - handedness of the controller: left or right.
  60614. */
  60615. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  60616. var mapping = hand ? component.mapping[hand] : component.mapping;
  60617. var buttonName = mapping.buttons[id];
  60618. component.el.emit(buttonName + evtName);
  60619. if (component.updateModel) {
  60620. component.updateModel(buttonName, evtName);
  60621. }
  60622. };
  60623. },{"../constants":121}],212:[function(_dereq_,module,exports){
  60624. /**
  60625. * @author richt / http://richt.me
  60626. * @author WestLangley / http://github.com/WestLangley
  60627. *
  60628. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  60629. */
  60630. THREE.DeviceOrientationControls = function ( object ) {
  60631. var scope = this;
  60632. this.object = object;
  60633. this.object.rotation.reorder( 'YXZ' );
  60634. this.enabled = true;
  60635. this.deviceOrientation = {};
  60636. this.screenOrientation = 0;
  60637. this.alphaOffset = 0; // radians
  60638. var onDeviceOrientationChangeEvent = function ( event ) {
  60639. scope.deviceOrientation = event;
  60640. };
  60641. var onScreenOrientationChangeEvent = function () {
  60642. scope.screenOrientation = window.orientation || 0;
  60643. };
  60644. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  60645. var setObjectQuaternion = function () {
  60646. var zee = new THREE.Vector3( 0, 0, 1 );
  60647. var euler = new THREE.Euler();
  60648. var q0 = new THREE.Quaternion();
  60649. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  60650. return function ( quaternion, alpha, beta, gamma, orient ) {
  60651. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  60652. quaternion.setFromEuler( euler ); // orient the device
  60653. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  60654. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  60655. };
  60656. }();
  60657. this.connect = function () {
  60658. onScreenOrientationChangeEvent();
  60659. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  60660. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  60661. scope.enabled = true;
  60662. };
  60663. this.disconnect = function () {
  60664. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  60665. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  60666. scope.enabled = false;
  60667. };
  60668. this.update = function () {
  60669. if ( scope.enabled === false ) return;
  60670. var device = scope.deviceOrientation;
  60671. if ( device ) {
  60672. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  60673. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  60674. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  60675. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  60676. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  60677. }
  60678. };
  60679. this.dispose = function () {
  60680. scope.disconnect();
  60681. };
  60682. this.connect();
  60683. };
  60684. },{}],213:[function(_dereq_,module,exports){
  60685. window.glStats = function () {
  60686. var _rS = null;
  60687. var _totalDrawArraysCalls = 0,
  60688. _totalDrawElementsCalls = 0,
  60689. _totalUseProgramCalls = 0,
  60690. _totalFaces = 0,
  60691. _totalVertices = 0,
  60692. _totalPoints = 0,
  60693. _totalBindTexures = 0;
  60694. function _h ( f, c ) {
  60695. return function () {
  60696. c.apply( this, arguments );
  60697. f.apply( this, arguments );
  60698. };
  60699. }
  60700. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  60701. _totalDrawArraysCalls++;
  60702. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  60703. else _totalVertices += arguments[ 2 ];
  60704. } );
  60705. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  60706. _totalDrawElementsCalls++;
  60707. _totalFaces += arguments[ 1 ] / 3;
  60708. _totalVertices += arguments[ 1 ];
  60709. } );
  60710. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  60711. _totalUseProgramCalls++;
  60712. } );
  60713. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  60714. _totalBindTexures++;
  60715. } );
  60716. var _values = {
  60717. allcalls: {
  60718. over: 3000,
  60719. caption: 'Calls (hook)'
  60720. },
  60721. drawelements: {
  60722. caption: 'drawElements (hook)'
  60723. },
  60724. drawarrays: {
  60725. caption: 'drawArrays (hook)'
  60726. }
  60727. };
  60728. var _groups = [ {
  60729. caption: 'WebGL',
  60730. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  60731. } ];
  60732. var _fractions = [ {
  60733. base: 'allcalls',
  60734. steps: [ 'drawelements', 'drawarrays' ]
  60735. } ];
  60736. function _update () {
  60737. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  60738. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  60739. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  60740. _rS( 'bindTexture' ).set( _totalBindTexures );
  60741. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  60742. _rS( 'glfaces' ).set( _totalFaces );
  60743. _rS( 'glvertices' ).set( _totalVertices );
  60744. _rS( 'glpoints' ).set( _totalPoints );
  60745. }
  60746. function _start () {
  60747. _totalDrawArraysCalls = 0;
  60748. _totalDrawElementsCalls = 0;
  60749. _totalUseProgramCalls = 0;
  60750. _totalFaces = 0;
  60751. _totalVertices = 0;
  60752. _totalPoints = 0;
  60753. _totalBindTexures = 0;
  60754. }
  60755. function _end () {}
  60756. function _attach ( r ) {
  60757. _rS = r;
  60758. }
  60759. return {
  60760. update: _update,
  60761. start: _start,
  60762. end: _end,
  60763. attach: _attach,
  60764. values: _values,
  60765. groups: _groups,
  60766. fractions: _fractions
  60767. };
  60768. };
  60769. window.threeStats = function ( renderer ) {
  60770. var _rS = null;
  60771. var _values = {
  60772. 'renderer.info.memory.geometries': {
  60773. caption: 'Geometries'
  60774. },
  60775. 'renderer.info.memory.textures': {
  60776. caption: 'Textures'
  60777. },
  60778. 'renderer.info.programs': {
  60779. caption: 'Programs'
  60780. },
  60781. 'renderer.info.render.calls': {
  60782. caption: 'Calls'
  60783. },
  60784. 'renderer.info.render.triangles': {
  60785. caption: 'Triangles',
  60786. over: 1000
  60787. },
  60788. 'renderer.info.render.points': {
  60789. caption: 'Points'
  60790. }
  60791. };
  60792. var _groups = [ {
  60793. caption: 'Three.js - Memory',
  60794. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  60795. }, {
  60796. caption: 'Three.js - Render',
  60797. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  60798. } ];
  60799. var _fractions = [];
  60800. function _update () {
  60801. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  60802. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  60803. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  60804. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  60805. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  60806. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  60807. }
  60808. function _start () {}
  60809. function _end () {}
  60810. function _attach ( r ) {
  60811. _rS = r;
  60812. }
  60813. return {
  60814. update: _update,
  60815. start: _start,
  60816. end: _end,
  60817. attach: _attach,
  60818. values: _values,
  60819. groups: _groups,
  60820. fractions: _fractions
  60821. };
  60822. };
  60823. /*
  60824. * From https://github.com/paulirish/memory-stats.js
  60825. */
  60826. window.BrowserStats = function () {
  60827. var _rS = null;
  60828. var _usedJSHeapSize = 0,
  60829. _totalJSHeapSize = 0;
  60830. if ( window.performance && !performance.memory ) {
  60831. performance.memory = {
  60832. usedJSHeapSize: 0,
  60833. totalJSHeapSize: 0
  60834. };
  60835. }
  60836. if ( performance.memory.totalJSHeapSize === 0 ) {
  60837. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  60838. }
  60839. var _values = {
  60840. memory: {
  60841. caption: 'Used Memory',
  60842. average: true,
  60843. avgMs: 1000,
  60844. over: 22
  60845. },
  60846. total: {
  60847. caption: 'Total Memory'
  60848. }
  60849. };
  60850. var _groups = [ {
  60851. caption: 'Browser',
  60852. values: [ 'memory', 'total' ]
  60853. } ];
  60854. var _fractions = [ {
  60855. base: 'total',
  60856. steps: [ 'memory' ]
  60857. } ];
  60858. var log1024 = Math.log( 1024 );
  60859. function _size ( v ) {
  60860. var precision = 100; //Math.pow(10, 2);
  60861. var i = Math.floor( Math.log( v ) / log1024 );
  60862. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  60863. }
  60864. function _update () {
  60865. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  60866. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  60867. _rS( 'memory' ).set( _usedJSHeapSize );
  60868. _rS( 'total' ).set( _totalJSHeapSize );
  60869. }
  60870. function _start () {
  60871. _usedJSHeapSize = 0;
  60872. }
  60873. function _end () {}
  60874. function _attach ( r ) {
  60875. _rS = r;
  60876. }
  60877. return {
  60878. update: _update,
  60879. start: _start,
  60880. end: _end,
  60881. attach: _attach,
  60882. values: _values,
  60883. groups: _groups,
  60884. fractions: _fractions
  60885. };
  60886. };
  60887. if (typeof module === 'object') {
  60888. module.exports = {
  60889. glStats: window.glStats,
  60890. threeStats: window.threeStats,
  60891. BrowserStats: window.BrowserStats
  60892. };
  60893. }
  60894. },{}],214:[function(_dereq_,module,exports){
  60895. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  60896. 'use strict';
  60897. ( function () {
  60898. if ( 'performance' in window == false ) {
  60899. window.performance = {};
  60900. }
  60901. var performance = window.performance;
  60902. if ( 'now' in performance == false ) {
  60903. var nowOffset = Date.now();
  60904. if ( performance.timing && performance.timing.navigationStart ) {
  60905. nowOffset = performance.timing.navigationStart;
  60906. }
  60907. performance.now = function now () {
  60908. return Date.now() - nowOffset;
  60909. };
  60910. }
  60911. if( !performance.mark ) {
  60912. performance.mark = function(){}
  60913. }
  60914. if( !performance.measure ) {
  60915. performance.measure = function(){}
  60916. }
  60917. } )();
  60918. window.rStats = function rStats ( settings ) {
  60919. function iterateKeys ( array, callback ) {
  60920. var keys = Object.keys( array );
  60921. for ( var j = 0, l = keys.length; j < l; j++ ) {
  60922. callback( keys[ j ] );
  60923. }
  60924. }
  60925. function importCSS ( url ) {
  60926. var element = document.createElement( 'link' );
  60927. element.href = url;
  60928. element.rel = 'stylesheet';
  60929. element.type = 'text/css';
  60930. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  60931. }
  60932. var _settings = settings || {};
  60933. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  60934. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  60935. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  60936. var _css = _settings.css || [ _cssFont, _cssRStats ];
  60937. _css.forEach(function (uri) {
  60938. importCSS( uri );
  60939. });
  60940. if ( !_settings.values ) _settings.values = {};
  60941. var _base, _div, _elHeight = 10, _elWidth = 200;
  60942. var _perfCounters = {};
  60943. function Graph ( _dom, _id, _defArg ) {
  60944. var _def = _defArg || {};
  60945. var _canvas = document.createElement( 'canvas' ),
  60946. _ctx = _canvas.getContext( '2d' ),
  60947. _max = 0,
  60948. _current = 0;
  60949. var c = _def.color ? _def.color : '#666666';
  60950. var _dotCanvas = document.createElement( 'canvas' ),
  60951. _dotCtx = _dotCanvas.getContext( '2d' );
  60952. _dotCanvas.width = 1;
  60953. _dotCanvas.height = 2 * _elHeight;
  60954. _dotCtx.fillStyle = '#444444';
  60955. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  60956. _dotCtx.fillStyle = c;
  60957. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  60958. _dotCtx.fillStyle = '#ffffff';
  60959. _dotCtx.globalAlpha = 0.5;
  60960. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  60961. _dotCtx.globalAlpha = 1;
  60962. var _alarmCanvas = document.createElement( 'canvas' ),
  60963. _alarmCtx = _alarmCanvas.getContext( '2d' );
  60964. _alarmCanvas.width = 1;
  60965. _alarmCanvas.height = 2 * _elHeight;
  60966. _alarmCtx.fillStyle = '#444444';
  60967. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  60968. _alarmCtx.fillStyle = '#b70000';
  60969. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  60970. _alarmCtx.globalAlpha = 0.5;
  60971. _alarmCtx.fillStyle = '#ffffff';
  60972. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  60973. _alarmCtx.globalAlpha = 1;
  60974. function _init () {
  60975. _canvas.width = _elWidth;
  60976. _canvas.height = _elHeight;
  60977. _canvas.style.width = _canvas.width + 'px';
  60978. _canvas.style.height = _canvas.height + 'px';
  60979. _canvas.className = 'rs-canvas';
  60980. _dom.appendChild( _canvas );
  60981. _ctx.fillStyle = '#444444';
  60982. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  60983. }
  60984. function _draw ( v, alarm ) {
  60985. _current += ( v - _current ) * 0.1;
  60986. _max *= 0.99;
  60987. if ( _current > _max ) _max = _current;
  60988. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  60989. if ( alarm ) {
  60990. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  60991. } else {
  60992. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  60993. }
  60994. }
  60995. _init();
  60996. return {
  60997. draw: _draw
  60998. };
  60999. }
  61000. function StackGraph ( _dom, _num ) {
  61001. var _canvas = document.createElement( 'canvas' ),
  61002. _ctx = _canvas.getContext( '2d' );
  61003. function _init () {
  61004. _canvas.width = _elWidth;
  61005. _canvas.height = _elHeight * _num;
  61006. _canvas.style.width = _canvas.width + 'px';
  61007. _canvas.style.height = _canvas.height + 'px';
  61008. _canvas.className = 'rs-canvas';
  61009. _dom.appendChild( _canvas );
  61010. _ctx.fillStyle = '#444444';
  61011. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  61012. }
  61013. function _draw ( v ) {
  61014. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  61015. var th = 0;
  61016. iterateKeys( v, function ( j ) {
  61017. var h = v[ j ] * _canvas.height;
  61018. _ctx.fillStyle = _colours[ j ];
  61019. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  61020. th += h;
  61021. } );
  61022. }
  61023. _init();
  61024. return {
  61025. draw: _draw
  61026. };
  61027. }
  61028. function PerfCounter ( id, group ) {
  61029. var _id = id,
  61030. _time,
  61031. _value = 0,
  61032. _total = 0,
  61033. _averageValue = 0,
  61034. _accumValue = 0,
  61035. _accumStart = performance.now(),
  61036. _accumSamples = 0,
  61037. _dom = document.createElement( 'div' ),
  61038. _spanId = document.createElement( 'span' ),
  61039. _spanValue = document.createElement( 'div' ),
  61040. _spanValueText = document.createTextNode( '' ),
  61041. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  61042. _graph = new Graph( _dom, _id, _def ),
  61043. _started = false;
  61044. _spanId.className = 'rs-counter-id';
  61045. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  61046. _spanValue.className = 'rs-counter-value';
  61047. _spanValue.appendChild( _spanValueText );
  61048. _dom.appendChild( _spanId );
  61049. _dom.appendChild( _spanValue );
  61050. if ( group ) group.div.appendChild( _dom );
  61051. else _div.appendChild( _dom );
  61052. _time = performance.now();
  61053. function _average ( v ) {
  61054. if ( _def && _def.average ) {
  61055. _accumValue += v;
  61056. _accumSamples++;
  61057. var t = performance.now();
  61058. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  61059. _averageValue = _accumValue / _accumSamples;
  61060. _accumValue = 0;
  61061. _accumStart = t;
  61062. _accumSamples = 0;
  61063. }
  61064. }
  61065. }
  61066. function _start () {
  61067. _time = performance.now();
  61068. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  61069. _started = true;
  61070. }
  61071. function _end () {
  61072. _value = performance.now() - _time;
  61073. if( _settings.userTimingAPI ) {
  61074. performance.mark( _id + '-end' );
  61075. if( _started ) {
  61076. performance.measure( _id, _id + '-start', _id + '-end' );
  61077. }
  61078. }
  61079. _average( _value );
  61080. }
  61081. function _tick () {
  61082. _end();
  61083. _start();
  61084. }
  61085. function _draw () {
  61086. var v = ( _def && _def.average ) ? _averageValue : _value;
  61087. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  61088. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  61089. _graph.draw( _value, a );
  61090. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  61091. }
  61092. function _frame () {
  61093. var t = performance.now();
  61094. var e = t - _time;
  61095. _total++;
  61096. if ( e > 1000 ) {
  61097. if ( _def && _def.interpolate === false ) {
  61098. _value = _total;
  61099. } else {
  61100. _value = _total * 1000 / e;
  61101. }
  61102. _total = 0;
  61103. _time = t;
  61104. _average( _value );
  61105. }
  61106. }
  61107. function _set ( v ) {
  61108. _value = v;
  61109. _average( _value );
  61110. }
  61111. return {
  61112. set: _set,
  61113. start: _start,
  61114. tick: _tick,
  61115. end: _end,
  61116. frame: _frame,
  61117. value: function () {
  61118. return _value;
  61119. },
  61120. draw: _draw
  61121. };
  61122. }
  61123. function sample () {
  61124. var _value = 0;
  61125. function _set ( v ) {
  61126. _value = v;
  61127. }
  61128. return {
  61129. set: _set,
  61130. value: function () {
  61131. return _value;
  61132. }
  61133. };
  61134. }
  61135. function _perf ( idArg ) {
  61136. var id = idArg.toLowerCase();
  61137. if ( id === undefined ) id = 'default';
  61138. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  61139. var group = null;
  61140. if ( _settings && _settings.groups ) {
  61141. iterateKeys( _settings.groups, function ( j ) {
  61142. var g = _settings.groups[ parseInt( j, 10 ) ];
  61143. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  61144. group = g;
  61145. }
  61146. } );
  61147. }
  61148. var p = new PerfCounter( id, group );
  61149. _perfCounters[ id ] = p;
  61150. return p;
  61151. }
  61152. function _init () {
  61153. if ( _settings.plugins ) {
  61154. if ( !_settings.values ) _settings.values = {};
  61155. if ( !_settings.groups ) _settings.groups = [];
  61156. if ( !_settings.fractions ) _settings.fractions = [];
  61157. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  61158. _settings.plugins[ j ].attach( _perf );
  61159. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  61160. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  61161. } );
  61162. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  61163. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  61164. }
  61165. } else {
  61166. _settings.plugins = {};
  61167. }
  61168. _base = document.createElement( 'div' );
  61169. _base.className = 'rs-base';
  61170. _div = document.createElement( 'div' );
  61171. _div.className = 'rs-container';
  61172. _div.style.height = 'auto';
  61173. _base.appendChild( _div );
  61174. document.body.appendChild( _base );
  61175. if ( !_settings ) return;
  61176. if ( _settings.groups ) {
  61177. iterateKeys( _settings.groups, function ( j ) {
  61178. var g = _settings.groups[ parseInt( j, 10 ) ];
  61179. var div = document.createElement( 'div' );
  61180. div.className = 'rs-group';
  61181. g.div = div;
  61182. var h1 = document.createElement( 'h1' );
  61183. h1.textContent = g.caption;
  61184. h1.addEventListener( 'click', function ( e ) {
  61185. this.classList.toggle( 'hidden' );
  61186. e.preventDefault();
  61187. }.bind( div ) );
  61188. _div.appendChild( h1 );
  61189. _div.appendChild( div );
  61190. } );
  61191. }
  61192. if ( _settings.fractions ) {
  61193. iterateKeys( _settings.fractions, function ( j ) {
  61194. var f = _settings.fractions[ parseInt( j, 10 ) ];
  61195. var div = document.createElement( 'div' );
  61196. div.className = 'rs-fraction';
  61197. var legend = document.createElement( 'div' );
  61198. legend.className = 'rs-legend';
  61199. var h = 0;
  61200. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  61201. var p = document.createElement( 'p' );
  61202. p.textContent = _settings.fractions[ j ].steps[ k ];
  61203. p.style.color = _colours[ h ];
  61204. legend.appendChild( p );
  61205. h++;
  61206. } );
  61207. div.appendChild( legend );
  61208. div.style.height = h * _elHeight + 'px';
  61209. f.div = div;
  61210. var graph = new StackGraph( div, h );
  61211. f.graph = graph;
  61212. _div.appendChild( div );
  61213. } );
  61214. }
  61215. }
  61216. function _update () {
  61217. iterateKeys( _settings.plugins, function ( j ) {
  61218. _settings.plugins[ j ].update();
  61219. } );
  61220. iterateKeys( _perfCounters, function ( j ) {
  61221. _perfCounters[ j ].draw();
  61222. } );
  61223. if ( _settings && _settings.fractions ) {
  61224. iterateKeys( _settings.fractions, function ( j ) {
  61225. var f = _settings.fractions[ parseInt( j, 10 ) ];
  61226. var v = [];
  61227. var base = _perfCounters[ f.base.toLowerCase() ];
  61228. if ( base ) {
  61229. base = base.value();
  61230. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  61231. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  61232. var val = _perfCounters[ s ];
  61233. if ( val ) {
  61234. v.push( val.value() / base );
  61235. }
  61236. } );
  61237. }
  61238. f.graph.draw( v );
  61239. } );
  61240. }
  61241. /*if( _height != _div.clientHeight ) {
  61242. _height = _div.clientHeight;
  61243. _base.style.height = _height + 2 * _elHeight + 'px';
  61244. console.log( _base.clientHeight );
  61245. }*/
  61246. }
  61247. _init();
  61248. return function ( id ) {
  61249. if ( id ) return _perf( id );
  61250. return {
  61251. element: _base,
  61252. update: _update
  61253. };
  61254. };
  61255. }
  61256. if (typeof module === 'object') {
  61257. module.exports = window.rStats;
  61258. }
  61259. },{}],215:[function(_dereq_,module,exports){
  61260. // https://stackoverflow.com/a/36213464
  61261. if (!String.prototype.startsWith) {
  61262. String.prototype.startsWith = function(searchString, position){
  61263. position = position || 0;
  61264. return this.substr(position, searchString.length) === searchString;
  61265. };
  61266. }
  61267. },{}],216:[function(_dereq_,module,exports){
  61268. /*
  61269. * Copyright 2015 Google Inc. All Rights Reserved.
  61270. * Licensed under the Apache License, Version 2.0 (the "License");
  61271. * you may not use this file except in compliance with the License.
  61272. * You may obtain a copy of the License at
  61273. *
  61274. * http://www.apache.org/licenses/LICENSE-2.0
  61275. *
  61276. * Unless required by applicable law or agreed to in writing, software
  61277. * distributed under the License is distributed on an "AS IS" BASIS,
  61278. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  61279. * See the License for the specific language governing permissions and
  61280. * limitations under the License.
  61281. */
  61282. var Util = {};
  61283. Util.base64 = function(mimeType, base64) {
  61284. return 'data:' + mimeType + ';base64,' + base64;
  61285. };
  61286. Util.isMobile = function() {
  61287. var check = false;
  61288. (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);
  61289. return check;
  61290. };
  61291. Util.isIOS = function() {
  61292. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  61293. };
  61294. Util.isIFrame = function() {
  61295. try {
  61296. return window.self !== window.top;
  61297. } catch (e) {
  61298. return true;
  61299. }
  61300. };
  61301. Util.appendQueryParameter = function(url, key, value) {
  61302. // Determine delimiter based on if the URL already GET parameters in it.
  61303. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  61304. url += delimiter + key + '=' + value;
  61305. return url;
  61306. };
  61307. // From http://goo.gl/4WX3tg
  61308. Util.getQueryParameter = function(name) {
  61309. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  61310. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  61311. results = regex.exec(location.search);
  61312. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  61313. };
  61314. Util.isLandscapeMode = function() {
  61315. return (window.orientation == 90 || window.orientation == -90);
  61316. };
  61317. module.exports = Util;
  61318. },{}],217:[function(_dereq_,module,exports){
  61319. /*
  61320. * Copyright 2015 Google Inc. All Rights Reserved.
  61321. * Licensed under the Apache License, Version 2.0 (the "License");
  61322. * you may not use this file except in compliance with the License.
  61323. * You may obtain a copy of the License at
  61324. *
  61325. * http://www.apache.org/licenses/LICENSE-2.0
  61326. *
  61327. * Unless required by applicable law or agreed to in writing, software
  61328. * distributed under the License is distributed on an "AS IS" BASIS,
  61329. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  61330. * See the License for the specific language governing permissions and
  61331. * limitations under the License.
  61332. */
  61333. var Util = _dereq_('./util.js');
  61334. /**
  61335. * Android and iOS compatible wakelock implementation.
  61336. *
  61337. * Refactored thanks to dkovalev@.
  61338. */
  61339. function AndroidWakeLock() {
  61340. var video = document.createElement('video');
  61341. video.addEventListener('ended', function() {
  61342. video.play();
  61343. });
  61344. this.request = function() {
  61345. if (video.paused) {
  61346. // Base64 version of videos_src/no-sleep-60s.webm.
  61347. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  61348. video.play();
  61349. }
  61350. };
  61351. this.release = function() {
  61352. video.pause();
  61353. video.src = '';
  61354. };
  61355. }
  61356. function iOSWakeLock() {
  61357. var timer = null;
  61358. this.request = function() {
  61359. if (!timer) {
  61360. timer = setInterval(function() {
  61361. window.location.href = '/';
  61362. setTimeout(window.stop, 0);
  61363. }, 15000);
  61364. }
  61365. }
  61366. this.release = function() {
  61367. if (timer) {
  61368. clearInterval(timer);
  61369. timer = null;
  61370. }
  61371. }
  61372. }
  61373. function getWakeLock() {
  61374. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  61375. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  61376. return iOSWakeLock;
  61377. } else {
  61378. return AndroidWakeLock;
  61379. }
  61380. }
  61381. module.exports = getWakeLock();
  61382. },{"./util.js":216}]},{},[175])(175)
  61383. });
  61384. //# sourceMappingURL=aframe-master.js.map