aframe-master.js 2.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450
  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 = '109dev';
  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 FrontFaceDirectionCW = 0;
  5647. var FrontFaceDirectionCCW = 1;
  5648. var BasicShadowMap = 0;
  5649. var PCFShadowMap = 1;
  5650. var PCFSoftShadowMap = 2;
  5651. var VSMShadowMap = 3;
  5652. var FrontSide = 0;
  5653. var BackSide = 1;
  5654. var DoubleSide = 2;
  5655. var FlatShading = 1;
  5656. var SmoothShading = 2;
  5657. var NoColors = 0;
  5658. var FaceColors = 1;
  5659. var VertexColors = 2;
  5660. var NoBlending = 0;
  5661. var NormalBlending = 1;
  5662. var AdditiveBlending = 2;
  5663. var SubtractiveBlending = 3;
  5664. var MultiplyBlending = 4;
  5665. var CustomBlending = 5;
  5666. var AddEquation = 100;
  5667. var SubtractEquation = 101;
  5668. var ReverseSubtractEquation = 102;
  5669. var MinEquation = 103;
  5670. var MaxEquation = 104;
  5671. var ZeroFactor = 200;
  5672. var OneFactor = 201;
  5673. var SrcColorFactor = 202;
  5674. var OneMinusSrcColorFactor = 203;
  5675. var SrcAlphaFactor = 204;
  5676. var OneMinusSrcAlphaFactor = 205;
  5677. var DstAlphaFactor = 206;
  5678. var OneMinusDstAlphaFactor = 207;
  5679. var DstColorFactor = 208;
  5680. var OneMinusDstColorFactor = 209;
  5681. var SrcAlphaSaturateFactor = 210;
  5682. var NeverDepth = 0;
  5683. var AlwaysDepth = 1;
  5684. var LessDepth = 2;
  5685. var LessEqualDepth = 3;
  5686. var EqualDepth = 4;
  5687. var GreaterEqualDepth = 5;
  5688. var GreaterDepth = 6;
  5689. var NotEqualDepth = 7;
  5690. var MultiplyOperation = 0;
  5691. var MixOperation = 1;
  5692. var AddOperation = 2;
  5693. var NoToneMapping = 0;
  5694. var LinearToneMapping = 1;
  5695. var ReinhardToneMapping = 2;
  5696. var Uncharted2ToneMapping = 3;
  5697. var CineonToneMapping = 4;
  5698. var ACESFilmicToneMapping = 5;
  5699. var UVMapping = 300;
  5700. var CubeReflectionMapping = 301;
  5701. var CubeRefractionMapping = 302;
  5702. var EquirectangularReflectionMapping = 303;
  5703. var EquirectangularRefractionMapping = 304;
  5704. var SphericalReflectionMapping = 305;
  5705. var CubeUVReflectionMapping = 306;
  5706. var CubeUVRefractionMapping = 307;
  5707. var RepeatWrapping = 1000;
  5708. var ClampToEdgeWrapping = 1001;
  5709. var MirroredRepeatWrapping = 1002;
  5710. var NearestFilter = 1003;
  5711. var NearestMipmapNearestFilter = 1004;
  5712. var NearestMipMapNearestFilter = 1004;
  5713. var NearestMipmapLinearFilter = 1005;
  5714. var NearestMipMapLinearFilter = 1005;
  5715. var LinearFilter = 1006;
  5716. var LinearMipmapNearestFilter = 1007;
  5717. var LinearMipMapNearestFilter = 1007;
  5718. var LinearMipmapLinearFilter = 1008;
  5719. var LinearMipMapLinearFilter = 1008;
  5720. var UnsignedByteType = 1009;
  5721. var ByteType = 1010;
  5722. var ShortType = 1011;
  5723. var UnsignedShortType = 1012;
  5724. var IntType = 1013;
  5725. var UnsignedIntType = 1014;
  5726. var FloatType = 1015;
  5727. var HalfFloatType = 1016;
  5728. var UnsignedShort4444Type = 1017;
  5729. var UnsignedShort5551Type = 1018;
  5730. var UnsignedShort565Type = 1019;
  5731. var UnsignedInt248Type = 1020;
  5732. var AlphaFormat = 1021;
  5733. var RGBFormat = 1022;
  5734. var RGBAFormat = 1023;
  5735. var LuminanceFormat = 1024;
  5736. var LuminanceAlphaFormat = 1025;
  5737. var RGBEFormat = RGBAFormat;
  5738. var DepthFormat = 1026;
  5739. var DepthStencilFormat = 1027;
  5740. var RedFormat = 1028;
  5741. var RGB_S3TC_DXT1_Format = 33776;
  5742. var RGBA_S3TC_DXT1_Format = 33777;
  5743. var RGBA_S3TC_DXT3_Format = 33778;
  5744. var RGBA_S3TC_DXT5_Format = 33779;
  5745. var RGB_PVRTC_4BPPV1_Format = 35840;
  5746. var RGB_PVRTC_2BPPV1_Format = 35841;
  5747. var RGBA_PVRTC_4BPPV1_Format = 35842;
  5748. var RGBA_PVRTC_2BPPV1_Format = 35843;
  5749. var RGB_ETC1_Format = 36196;
  5750. var RGBA_ASTC_4x4_Format = 37808;
  5751. var RGBA_ASTC_5x4_Format = 37809;
  5752. var RGBA_ASTC_5x5_Format = 37810;
  5753. var RGBA_ASTC_6x5_Format = 37811;
  5754. var RGBA_ASTC_6x6_Format = 37812;
  5755. var RGBA_ASTC_8x5_Format = 37813;
  5756. var RGBA_ASTC_8x6_Format = 37814;
  5757. var RGBA_ASTC_8x8_Format = 37815;
  5758. var RGBA_ASTC_10x5_Format = 37816;
  5759. var RGBA_ASTC_10x6_Format = 37817;
  5760. var RGBA_ASTC_10x8_Format = 37818;
  5761. var RGBA_ASTC_10x10_Format = 37819;
  5762. var RGBA_ASTC_12x10_Format = 37820;
  5763. var RGBA_ASTC_12x12_Format = 37821;
  5764. var LoopOnce = 2200;
  5765. var LoopRepeat = 2201;
  5766. var LoopPingPong = 2202;
  5767. var InterpolateDiscrete = 2300;
  5768. var InterpolateLinear = 2301;
  5769. var InterpolateSmooth = 2302;
  5770. var ZeroCurvatureEnding = 2400;
  5771. var ZeroSlopeEnding = 2401;
  5772. var WrapAroundEnding = 2402;
  5773. var TrianglesDrawMode = 0;
  5774. var TriangleStripDrawMode = 1;
  5775. var TriangleFanDrawMode = 2;
  5776. var LinearEncoding = 3000;
  5777. var sRGBEncoding = 3001;
  5778. var GammaEncoding = 3007;
  5779. var RGBEEncoding = 3002;
  5780. var LogLuvEncoding = 3003;
  5781. var RGBM7Encoding = 3004;
  5782. var RGBM16Encoding = 3005;
  5783. var RGBDEncoding = 3006;
  5784. var BasicDepthPacking = 3200;
  5785. var RGBADepthPacking = 3201;
  5786. var TangentSpaceNormalMap = 0;
  5787. var ObjectSpaceNormalMap = 1;
  5788. var ZeroStencilOp = 0;
  5789. var KeepStencilOp = 7680;
  5790. var ReplaceStencilOp = 7681;
  5791. var IncrementStencilOp = 7682;
  5792. var DecrementStencilOp = 7683;
  5793. var IncrementWrapStencilOp = 34055;
  5794. var DecrementWrapStencilOp = 34056;
  5795. var InvertStencilOp = 5386;
  5796. var NeverStencilFunc = 512;
  5797. var LessStencilFunc = 513;
  5798. var EqualStencilFunc = 514;
  5799. var LessEqualStencilFunc = 515;
  5800. var GreaterStencilFunc = 516;
  5801. var NotEqualStencilFunc = 517;
  5802. var GreaterEqualStencilFunc = 518;
  5803. var AlwaysStencilFunc = 519;
  5804. /**
  5805. * https://github.com/mrdoob/eventdispatcher.js/
  5806. */
  5807. function EventDispatcher() {}
  5808. Object.assign( EventDispatcher.prototype, {
  5809. addEventListener: function ( type, listener ) {
  5810. if ( this._listeners === undefined ) { this._listeners = {}; }
  5811. var listeners = this._listeners;
  5812. if ( listeners[ type ] === undefined ) {
  5813. listeners[ type ] = [];
  5814. }
  5815. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  5816. listeners[ type ].push( listener );
  5817. }
  5818. },
  5819. hasEventListener: function ( type, listener ) {
  5820. if ( this._listeners === undefined ) { return false; }
  5821. var listeners = this._listeners;
  5822. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  5823. },
  5824. removeEventListener: function ( type, listener ) {
  5825. if ( this._listeners === undefined ) { return; }
  5826. var listeners = this._listeners;
  5827. var listenerArray = listeners[ type ];
  5828. if ( listenerArray !== undefined ) {
  5829. var index = listenerArray.indexOf( listener );
  5830. if ( index !== - 1 ) {
  5831. listenerArray.splice( index, 1 );
  5832. }
  5833. }
  5834. },
  5835. dispatchEvent: function ( event ) {
  5836. if ( this._listeners === undefined ) { return; }
  5837. var listeners = this._listeners;
  5838. var listenerArray = listeners[ event.type ];
  5839. if ( listenerArray !== undefined ) {
  5840. event.target = this;
  5841. var array = listenerArray.slice( 0 );
  5842. for ( var i = 0, l = array.length; i < l; i ++ ) {
  5843. array[ i ].call( this, event );
  5844. }
  5845. }
  5846. }
  5847. } );
  5848. /**
  5849. * @author alteredq / http://alteredqualia.com/
  5850. * @author mrdoob / http://mrdoob.com/
  5851. */
  5852. var _lut = [];
  5853. for ( var i = 0; i < 256; i ++ ) {
  5854. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  5855. }
  5856. var _Math = {
  5857. DEG2RAD: Math.PI / 180,
  5858. RAD2DEG: 180 / Math.PI,
  5859. generateUUID: function () {
  5860. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  5861. var d0 = Math.random() * 0xffffffff | 0;
  5862. var d1 = Math.random() * 0xffffffff | 0;
  5863. var d2 = Math.random() * 0xffffffff | 0;
  5864. var d3 = Math.random() * 0xffffffff | 0;
  5865. var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  5866. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  5867. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  5868. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  5869. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  5870. return uuid.toUpperCase();
  5871. },
  5872. clamp: function ( value, min, max ) {
  5873. return Math.max( min, Math.min( max, value ) );
  5874. },
  5875. // compute euclidian modulo of m % n
  5876. // https://en.wikipedia.org/wiki/Modulo_operation
  5877. euclideanModulo: function ( n, m ) {
  5878. return ( ( n % m ) + m ) % m;
  5879. },
  5880. // Linear mapping from range <a1, a2> to range <b1, b2>
  5881. mapLinear: function ( x, a1, a2, b1, b2 ) {
  5882. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  5883. },
  5884. // https://en.wikipedia.org/wiki/Linear_interpolation
  5885. lerp: function ( x, y, t ) {
  5886. return ( 1 - t ) * x + t * y;
  5887. },
  5888. // http://en.wikipedia.org/wiki/Smoothstep
  5889. smoothstep: function ( x, min, max ) {
  5890. if ( x <= min ) { return 0; }
  5891. if ( x >= max ) { return 1; }
  5892. x = ( x - min ) / ( max - min );
  5893. return x * x * ( 3 - 2 * x );
  5894. },
  5895. smootherstep: function ( x, min, max ) {
  5896. if ( x <= min ) { return 0; }
  5897. if ( x >= max ) { return 1; }
  5898. x = ( x - min ) / ( max - min );
  5899. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  5900. },
  5901. // Random integer from <low, high> interval
  5902. randInt: function ( low, high ) {
  5903. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  5904. },
  5905. // Random float from <low, high> interval
  5906. randFloat: function ( low, high ) {
  5907. return low + Math.random() * ( high - low );
  5908. },
  5909. // Random float from <-range/2, range/2> interval
  5910. randFloatSpread: function ( range ) {
  5911. return range * ( 0.5 - Math.random() );
  5912. },
  5913. degToRad: function ( degrees ) {
  5914. return degrees * _Math.DEG2RAD;
  5915. },
  5916. radToDeg: function ( radians ) {
  5917. return radians * _Math.RAD2DEG;
  5918. },
  5919. isPowerOfTwo: function ( value ) {
  5920. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  5921. },
  5922. ceilPowerOfTwo: function ( value ) {
  5923. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  5924. },
  5925. floorPowerOfTwo: function ( value ) {
  5926. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  5927. }
  5928. };
  5929. /**
  5930. * @author mrdoob / http://mrdoob.com/
  5931. * @author philogb / http://blog.thejit.org/
  5932. * @author egraether / http://egraether.com/
  5933. * @author zz85 / http://www.lab4games.net/zz85/blog
  5934. */
  5935. function Vector2( x, y ) {
  5936. this.x = x || 0;
  5937. this.y = y || 0;
  5938. }
  5939. Object.defineProperties( Vector2.prototype, {
  5940. "width": {
  5941. get: function () {
  5942. return this.x;
  5943. },
  5944. set: function ( value ) {
  5945. this.x = value;
  5946. }
  5947. },
  5948. "height": {
  5949. get: function () {
  5950. return this.y;
  5951. },
  5952. set: function ( value ) {
  5953. this.y = value;
  5954. }
  5955. }
  5956. } );
  5957. Object.assign( Vector2.prototype, {
  5958. isVector2: true,
  5959. set: function ( x, y ) {
  5960. this.x = x;
  5961. this.y = y;
  5962. return this;
  5963. },
  5964. setScalar: function ( scalar ) {
  5965. this.x = scalar;
  5966. this.y = scalar;
  5967. return this;
  5968. },
  5969. setX: function ( x ) {
  5970. this.x = x;
  5971. return this;
  5972. },
  5973. setY: function ( y ) {
  5974. this.y = y;
  5975. return this;
  5976. },
  5977. setComponent: function ( index, value ) {
  5978. switch ( index ) {
  5979. case 0: this.x = value; break;
  5980. case 1: this.y = value; break;
  5981. default: throw new Error( 'index is out of range: ' + index );
  5982. }
  5983. return this;
  5984. },
  5985. getComponent: function ( index ) {
  5986. switch ( index ) {
  5987. case 0: return this.x;
  5988. case 1: return this.y;
  5989. default: throw new Error( 'index is out of range: ' + index );
  5990. }
  5991. },
  5992. clone: function () {
  5993. return new this.constructor( this.x, this.y );
  5994. },
  5995. copy: function ( v ) {
  5996. this.x = v.x;
  5997. this.y = v.y;
  5998. return this;
  5999. },
  6000. add: function ( v, w ) {
  6001. if ( w !== undefined ) {
  6002. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6003. return this.addVectors( v, w );
  6004. }
  6005. this.x += v.x;
  6006. this.y += v.y;
  6007. return this;
  6008. },
  6009. addScalar: function ( s ) {
  6010. this.x += s;
  6011. this.y += s;
  6012. return this;
  6013. },
  6014. addVectors: function ( a, b ) {
  6015. this.x = a.x + b.x;
  6016. this.y = a.y + b.y;
  6017. return this;
  6018. },
  6019. addScaledVector: function ( v, s ) {
  6020. this.x += v.x * s;
  6021. this.y += v.y * s;
  6022. return this;
  6023. },
  6024. sub: function ( v, w ) {
  6025. if ( w !== undefined ) {
  6026. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6027. return this.subVectors( v, w );
  6028. }
  6029. this.x -= v.x;
  6030. this.y -= v.y;
  6031. return this;
  6032. },
  6033. subScalar: function ( s ) {
  6034. this.x -= s;
  6035. this.y -= s;
  6036. return this;
  6037. },
  6038. subVectors: function ( a, b ) {
  6039. this.x = a.x - b.x;
  6040. this.y = a.y - b.y;
  6041. return this;
  6042. },
  6043. multiply: function ( v ) {
  6044. this.x *= v.x;
  6045. this.y *= v.y;
  6046. return this;
  6047. },
  6048. multiplyScalar: function ( scalar ) {
  6049. this.x *= scalar;
  6050. this.y *= scalar;
  6051. return this;
  6052. },
  6053. divide: function ( v ) {
  6054. this.x /= v.x;
  6055. this.y /= v.y;
  6056. return this;
  6057. },
  6058. divideScalar: function ( scalar ) {
  6059. return this.multiplyScalar( 1 / scalar );
  6060. },
  6061. applyMatrix3: function ( m ) {
  6062. var x = this.x, y = this.y;
  6063. var e = m.elements;
  6064. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  6065. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  6066. return this;
  6067. },
  6068. min: function ( v ) {
  6069. this.x = Math.min( this.x, v.x );
  6070. this.y = Math.min( this.y, v.y );
  6071. return this;
  6072. },
  6073. max: function ( v ) {
  6074. this.x = Math.max( this.x, v.x );
  6075. this.y = Math.max( this.y, v.y );
  6076. return this;
  6077. },
  6078. clamp: function ( min, max ) {
  6079. // assumes min < max, componentwise
  6080. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6081. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6082. return this;
  6083. },
  6084. clampScalar: function ( minVal, maxVal ) {
  6085. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6086. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6087. return this;
  6088. },
  6089. clampLength: function ( min, max ) {
  6090. var length = this.length();
  6091. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6092. },
  6093. floor: function () {
  6094. this.x = Math.floor( this.x );
  6095. this.y = Math.floor( this.y );
  6096. return this;
  6097. },
  6098. ceil: function () {
  6099. this.x = Math.ceil( this.x );
  6100. this.y = Math.ceil( this.y );
  6101. return this;
  6102. },
  6103. round: function () {
  6104. this.x = Math.round( this.x );
  6105. this.y = Math.round( this.y );
  6106. return this;
  6107. },
  6108. roundToZero: function () {
  6109. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6110. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6111. return this;
  6112. },
  6113. negate: function () {
  6114. this.x = - this.x;
  6115. this.y = - this.y;
  6116. return this;
  6117. },
  6118. dot: function ( v ) {
  6119. return this.x * v.x + this.y * v.y;
  6120. },
  6121. cross: function ( v ) {
  6122. return this.x * v.y - this.y * v.x;
  6123. },
  6124. lengthSq: function () {
  6125. return this.x * this.x + this.y * this.y;
  6126. },
  6127. length: function () {
  6128. return Math.sqrt( this.x * this.x + this.y * this.y );
  6129. },
  6130. manhattanLength: function () {
  6131. return Math.abs( this.x ) + Math.abs( this.y );
  6132. },
  6133. normalize: function () {
  6134. return this.divideScalar( this.length() || 1 );
  6135. },
  6136. angle: function () {
  6137. // computes the angle in radians with respect to the positive x-axis
  6138. var angle = Math.atan2( this.y, this.x );
  6139. if ( angle < 0 ) { angle += 2 * Math.PI; }
  6140. return angle;
  6141. },
  6142. distanceTo: function ( v ) {
  6143. return Math.sqrt( this.distanceToSquared( v ) );
  6144. },
  6145. distanceToSquared: function ( v ) {
  6146. var dx = this.x - v.x, dy = this.y - v.y;
  6147. return dx * dx + dy * dy;
  6148. },
  6149. manhattanDistanceTo: function ( v ) {
  6150. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  6151. },
  6152. setLength: function ( length ) {
  6153. return this.normalize().multiplyScalar( length );
  6154. },
  6155. lerp: function ( v, alpha ) {
  6156. this.x += ( v.x - this.x ) * alpha;
  6157. this.y += ( v.y - this.y ) * alpha;
  6158. return this;
  6159. },
  6160. lerpVectors: function ( v1, v2, alpha ) {
  6161. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6162. },
  6163. equals: function ( v ) {
  6164. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  6165. },
  6166. fromArray: function ( array, offset ) {
  6167. if ( offset === undefined ) { offset = 0; }
  6168. this.x = array[ offset ];
  6169. this.y = array[ offset + 1 ];
  6170. return this;
  6171. },
  6172. toArray: function ( array, offset ) {
  6173. if ( array === undefined ) { array = []; }
  6174. if ( offset === undefined ) { offset = 0; }
  6175. array[ offset ] = this.x;
  6176. array[ offset + 1 ] = this.y;
  6177. return array;
  6178. },
  6179. fromBufferAttribute: function ( attribute, index, offset ) {
  6180. if ( offset !== undefined ) {
  6181. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  6182. }
  6183. this.x = attribute.getX( index );
  6184. this.y = attribute.getY( index );
  6185. return this;
  6186. },
  6187. rotateAround: function ( center, angle ) {
  6188. var c = Math.cos( angle ), s = Math.sin( angle );
  6189. var x = this.x - center.x;
  6190. var y = this.y - center.y;
  6191. this.x = x * c - y * s + center.x;
  6192. this.y = x * s + y * c + center.y;
  6193. return this;
  6194. }
  6195. } );
  6196. /**
  6197. * @author mikael emtinger / http://gomo.se/
  6198. * @author alteredq / http://alteredqualia.com/
  6199. * @author WestLangley / http://github.com/WestLangley
  6200. * @author bhouston / http://clara.io
  6201. */
  6202. function Quaternion( x, y, z, w ) {
  6203. this._x = x || 0;
  6204. this._y = y || 0;
  6205. this._z = z || 0;
  6206. this._w = ( w !== undefined ) ? w : 1;
  6207. }
  6208. Object.assign( Quaternion, {
  6209. slerp: function ( qa, qb, qm, t ) {
  6210. return qm.copy( qa ).slerp( qb, t );
  6211. },
  6212. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  6213. // fuzz-free, array-based Quaternion SLERP operation
  6214. var x0 = src0[ srcOffset0 + 0 ],
  6215. y0 = src0[ srcOffset0 + 1 ],
  6216. z0 = src0[ srcOffset0 + 2 ],
  6217. w0 = src0[ srcOffset0 + 3 ],
  6218. x1 = src1[ srcOffset1 + 0 ],
  6219. y1 = src1[ srcOffset1 + 1 ],
  6220. z1 = src1[ srcOffset1 + 2 ],
  6221. w1 = src1[ srcOffset1 + 3 ];
  6222. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  6223. var s = 1 - t,
  6224. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  6225. dir = ( cos >= 0 ? 1 : - 1 ),
  6226. sqrSin = 1 - cos * cos;
  6227. // Skip the Slerp for tiny steps to avoid numeric problems:
  6228. if ( sqrSin > Number.EPSILON ) {
  6229. var sin = Math.sqrt( sqrSin ),
  6230. len = Math.atan2( sin, cos * dir );
  6231. s = Math.sin( s * len ) / sin;
  6232. t = Math.sin( t * len ) / sin;
  6233. }
  6234. var tDir = t * dir;
  6235. x0 = x0 * s + x1 * tDir;
  6236. y0 = y0 * s + y1 * tDir;
  6237. z0 = z0 * s + z1 * tDir;
  6238. w0 = w0 * s + w1 * tDir;
  6239. // Normalize in case we just did a lerp:
  6240. if ( s === 1 - t ) {
  6241. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  6242. x0 *= f;
  6243. y0 *= f;
  6244. z0 *= f;
  6245. w0 *= f;
  6246. }
  6247. }
  6248. dst[ dstOffset ] = x0;
  6249. dst[ dstOffset + 1 ] = y0;
  6250. dst[ dstOffset + 2 ] = z0;
  6251. dst[ dstOffset + 3 ] = w0;
  6252. }
  6253. } );
  6254. Object.defineProperties( Quaternion.prototype, {
  6255. x: {
  6256. get: function () {
  6257. return this._x;
  6258. },
  6259. set: function ( value ) {
  6260. this._x = value;
  6261. this._onChangeCallback();
  6262. }
  6263. },
  6264. y: {
  6265. get: function () {
  6266. return this._y;
  6267. },
  6268. set: function ( value ) {
  6269. this._y = value;
  6270. this._onChangeCallback();
  6271. }
  6272. },
  6273. z: {
  6274. get: function () {
  6275. return this._z;
  6276. },
  6277. set: function ( value ) {
  6278. this._z = value;
  6279. this._onChangeCallback();
  6280. }
  6281. },
  6282. w: {
  6283. get: function () {
  6284. return this._w;
  6285. },
  6286. set: function ( value ) {
  6287. this._w = value;
  6288. this._onChangeCallback();
  6289. }
  6290. }
  6291. } );
  6292. Object.assign( Quaternion.prototype, {
  6293. isQuaternion: true,
  6294. set: function ( x, y, z, w ) {
  6295. this._x = x;
  6296. this._y = y;
  6297. this._z = z;
  6298. this._w = w;
  6299. this._onChangeCallback();
  6300. return this;
  6301. },
  6302. clone: function () {
  6303. return new this.constructor( this._x, this._y, this._z, this._w );
  6304. },
  6305. copy: function ( quaternion ) {
  6306. this._x = quaternion.x;
  6307. this._y = quaternion.y;
  6308. this._z = quaternion.z;
  6309. this._w = quaternion.w;
  6310. this._onChangeCallback();
  6311. return this;
  6312. },
  6313. setFromEuler: function ( euler, update ) {
  6314. if ( ! ( euler && euler.isEuler ) ) {
  6315. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6316. }
  6317. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  6318. // http://www.mathworks.com/matlabcentral/fileexchange/
  6319. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  6320. // content/SpinCalc.m
  6321. var cos = Math.cos;
  6322. var sin = Math.sin;
  6323. var c1 = cos( x / 2 );
  6324. var c2 = cos( y / 2 );
  6325. var c3 = cos( z / 2 );
  6326. var s1 = sin( x / 2 );
  6327. var s2 = sin( y / 2 );
  6328. var s3 = sin( z / 2 );
  6329. if ( order === 'XYZ' ) {
  6330. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6331. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6332. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6333. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6334. } else if ( order === 'YXZ' ) {
  6335. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6336. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6338. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6339. } else if ( order === 'ZXY' ) {
  6340. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6341. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6344. } else if ( order === 'ZYX' ) {
  6345. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6346. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6349. } else if ( order === 'YZX' ) {
  6350. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6351. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6352. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6353. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6354. } else if ( order === 'XZY' ) {
  6355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6356. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6357. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6359. }
  6360. if ( update !== false ) { this._onChangeCallback(); }
  6361. return this;
  6362. },
  6363. setFromAxisAngle: function ( axis, angle ) {
  6364. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  6365. // assumes axis is normalized
  6366. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  6367. this._x = axis.x * s;
  6368. this._y = axis.y * s;
  6369. this._z = axis.z * s;
  6370. this._w = Math.cos( halfAngle );
  6371. this._onChangeCallback();
  6372. return this;
  6373. },
  6374. setFromRotationMatrix: function ( m ) {
  6375. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  6376. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6377. var te = m.elements,
  6378. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6379. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6380. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  6381. trace = m11 + m22 + m33,
  6382. s;
  6383. if ( trace > 0 ) {
  6384. s = 0.5 / Math.sqrt( trace + 1.0 );
  6385. this._w = 0.25 / s;
  6386. this._x = ( m32 - m23 ) * s;
  6387. this._y = ( m13 - m31 ) * s;
  6388. this._z = ( m21 - m12 ) * s;
  6389. } else if ( m11 > m22 && m11 > m33 ) {
  6390. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  6391. this._w = ( m32 - m23 ) / s;
  6392. this._x = 0.25 * s;
  6393. this._y = ( m12 + m21 ) / s;
  6394. this._z = ( m13 + m31 ) / s;
  6395. } else if ( m22 > m33 ) {
  6396. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  6397. this._w = ( m13 - m31 ) / s;
  6398. this._x = ( m12 + m21 ) / s;
  6399. this._y = 0.25 * s;
  6400. this._z = ( m23 + m32 ) / s;
  6401. } else {
  6402. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  6403. this._w = ( m21 - m12 ) / s;
  6404. this._x = ( m13 + m31 ) / s;
  6405. this._y = ( m23 + m32 ) / s;
  6406. this._z = 0.25 * s;
  6407. }
  6408. this._onChangeCallback();
  6409. return this;
  6410. },
  6411. setFromUnitVectors: function ( vFrom, vTo ) {
  6412. // assumes direction vectors vFrom and vTo are normalized
  6413. var EPS = 0.000001;
  6414. var r = vFrom.dot( vTo ) + 1;
  6415. if ( r < EPS ) {
  6416. r = 0;
  6417. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  6418. this._x = - vFrom.y;
  6419. this._y = vFrom.x;
  6420. this._z = 0;
  6421. this._w = r;
  6422. } else {
  6423. this._x = 0;
  6424. this._y = - vFrom.z;
  6425. this._z = vFrom.y;
  6426. this._w = r;
  6427. }
  6428. } else {
  6429. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  6430. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  6431. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  6432. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  6433. this._w = r;
  6434. }
  6435. return this.normalize();
  6436. },
  6437. angleTo: function ( q ) {
  6438. return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) );
  6439. },
  6440. rotateTowards: function ( q, step ) {
  6441. var angle = this.angleTo( q );
  6442. if ( angle === 0 ) { return this; }
  6443. var t = Math.min( 1, step / angle );
  6444. this.slerp( q, t );
  6445. return this;
  6446. },
  6447. inverse: function () {
  6448. // quaternion is assumed to have unit length
  6449. return this.conjugate();
  6450. },
  6451. conjugate: function () {
  6452. this._x *= - 1;
  6453. this._y *= - 1;
  6454. this._z *= - 1;
  6455. this._onChangeCallback();
  6456. return this;
  6457. },
  6458. dot: function ( v ) {
  6459. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  6460. },
  6461. lengthSq: function () {
  6462. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  6463. },
  6464. length: function () {
  6465. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  6466. },
  6467. normalize: function () {
  6468. var l = this.length();
  6469. if ( l === 0 ) {
  6470. this._x = 0;
  6471. this._y = 0;
  6472. this._z = 0;
  6473. this._w = 1;
  6474. } else {
  6475. l = 1 / l;
  6476. this._x = this._x * l;
  6477. this._y = this._y * l;
  6478. this._z = this._z * l;
  6479. this._w = this._w * l;
  6480. }
  6481. this._onChangeCallback();
  6482. return this;
  6483. },
  6484. multiply: function ( q, p ) {
  6485. if ( p !== undefined ) {
  6486. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  6487. return this.multiplyQuaternions( q, p );
  6488. }
  6489. return this.multiplyQuaternions( this, q );
  6490. },
  6491. premultiply: function ( q ) {
  6492. return this.multiplyQuaternions( q, this );
  6493. },
  6494. multiplyQuaternions: function ( a, b ) {
  6495. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6496. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6497. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6498. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6499. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6500. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6501. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6502. this._onChangeCallback();
  6503. return this;
  6504. },
  6505. slerp: function ( qb, t ) {
  6506. if ( t === 0 ) { return this; }
  6507. if ( t === 1 ) { return this.copy( qb ); }
  6508. var x = this._x, y = this._y, z = this._z, w = this._w;
  6509. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6510. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6511. if ( cosHalfTheta < 0 ) {
  6512. this._w = - qb._w;
  6513. this._x = - qb._x;
  6514. this._y = - qb._y;
  6515. this._z = - qb._z;
  6516. cosHalfTheta = - cosHalfTheta;
  6517. } else {
  6518. this.copy( qb );
  6519. }
  6520. if ( cosHalfTheta >= 1.0 ) {
  6521. this._w = w;
  6522. this._x = x;
  6523. this._y = y;
  6524. this._z = z;
  6525. return this;
  6526. }
  6527. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6528. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6529. var s = 1 - t;
  6530. this._w = s * w + t * this._w;
  6531. this._x = s * x + t * this._x;
  6532. this._y = s * y + t * this._y;
  6533. this._z = s * z + t * this._z;
  6534. this.normalize();
  6535. this._onChangeCallback();
  6536. return this;
  6537. }
  6538. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6539. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6540. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6541. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6542. this._w = ( w * ratioA + this._w * ratioB );
  6543. this._x = ( x * ratioA + this._x * ratioB );
  6544. this._y = ( y * ratioA + this._y * ratioB );
  6545. this._z = ( z * ratioA + this._z * ratioB );
  6546. this._onChangeCallback();
  6547. return this;
  6548. },
  6549. equals: function ( quaternion ) {
  6550. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6551. },
  6552. fromArray: function ( array, offset ) {
  6553. if ( offset === undefined ) { offset = 0; }
  6554. this._x = array[ offset ];
  6555. this._y = array[ offset + 1 ];
  6556. this._z = array[ offset + 2 ];
  6557. this._w = array[ offset + 3 ];
  6558. this._onChangeCallback();
  6559. return this;
  6560. },
  6561. toArray: function ( array, offset ) {
  6562. if ( array === undefined ) { array = []; }
  6563. if ( offset === undefined ) { offset = 0; }
  6564. array[ offset ] = this._x;
  6565. array[ offset + 1 ] = this._y;
  6566. array[ offset + 2 ] = this._z;
  6567. array[ offset + 3 ] = this._w;
  6568. return array;
  6569. },
  6570. _onChange: function ( callback ) {
  6571. this._onChangeCallback = callback;
  6572. return this;
  6573. },
  6574. _onChangeCallback: function () {}
  6575. } );
  6576. /**
  6577. * @author mrdoob / http://mrdoob.com/
  6578. * @author kile / http://kile.stravaganza.org/
  6579. * @author philogb / http://blog.thejit.org/
  6580. * @author mikael emtinger / http://gomo.se/
  6581. * @author egraether / http://egraether.com/
  6582. * @author WestLangley / http://github.com/WestLangley
  6583. */
  6584. var _vector = new Vector3();
  6585. var _quaternion = new Quaternion();
  6586. function Vector3( x, y, z ) {
  6587. this.x = x || 0;
  6588. this.y = y || 0;
  6589. this.z = z || 0;
  6590. }
  6591. Object.assign( Vector3.prototype, {
  6592. isVector3: true,
  6593. set: function ( x, y, z ) {
  6594. this.x = x;
  6595. this.y = y;
  6596. this.z = z;
  6597. return this;
  6598. },
  6599. setScalar: function ( scalar ) {
  6600. this.x = scalar;
  6601. this.y = scalar;
  6602. this.z = scalar;
  6603. return this;
  6604. },
  6605. setX: function ( x ) {
  6606. this.x = x;
  6607. return this;
  6608. },
  6609. setY: function ( y ) {
  6610. this.y = y;
  6611. return this;
  6612. },
  6613. setZ: function ( z ) {
  6614. this.z = z;
  6615. return this;
  6616. },
  6617. setComponent: function ( index, value ) {
  6618. switch ( index ) {
  6619. case 0: this.x = value; break;
  6620. case 1: this.y = value; break;
  6621. case 2: this.z = value; break;
  6622. default: throw new Error( 'index is out of range: ' + index );
  6623. }
  6624. return this;
  6625. },
  6626. getComponent: function ( index ) {
  6627. switch ( index ) {
  6628. case 0: return this.x;
  6629. case 1: return this.y;
  6630. case 2: return this.z;
  6631. default: throw new Error( 'index is out of range: ' + index );
  6632. }
  6633. },
  6634. clone: function () {
  6635. return new this.constructor( this.x, this.y, this.z );
  6636. },
  6637. copy: function ( v ) {
  6638. this.x = v.x;
  6639. this.y = v.y;
  6640. this.z = v.z;
  6641. return this;
  6642. },
  6643. add: function ( v, w ) {
  6644. if ( w !== undefined ) {
  6645. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6646. return this.addVectors( v, w );
  6647. }
  6648. this.x += v.x;
  6649. this.y += v.y;
  6650. this.z += v.z;
  6651. return this;
  6652. },
  6653. addScalar: function ( s ) {
  6654. this.x += s;
  6655. this.y += s;
  6656. this.z += s;
  6657. return this;
  6658. },
  6659. addVectors: function ( a, b ) {
  6660. this.x = a.x + b.x;
  6661. this.y = a.y + b.y;
  6662. this.z = a.z + b.z;
  6663. return this;
  6664. },
  6665. addScaledVector: function ( v, s ) {
  6666. this.x += v.x * s;
  6667. this.y += v.y * s;
  6668. this.z += v.z * s;
  6669. return this;
  6670. },
  6671. sub: function ( v, w ) {
  6672. if ( w !== undefined ) {
  6673. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6674. return this.subVectors( v, w );
  6675. }
  6676. this.x -= v.x;
  6677. this.y -= v.y;
  6678. this.z -= v.z;
  6679. return this;
  6680. },
  6681. subScalar: function ( s ) {
  6682. this.x -= s;
  6683. this.y -= s;
  6684. this.z -= s;
  6685. return this;
  6686. },
  6687. subVectors: function ( a, b ) {
  6688. this.x = a.x - b.x;
  6689. this.y = a.y - b.y;
  6690. this.z = a.z - b.z;
  6691. return this;
  6692. },
  6693. multiply: function ( v, w ) {
  6694. if ( w !== undefined ) {
  6695. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6696. return this.multiplyVectors( v, w );
  6697. }
  6698. this.x *= v.x;
  6699. this.y *= v.y;
  6700. this.z *= v.z;
  6701. return this;
  6702. },
  6703. multiplyScalar: function ( scalar ) {
  6704. this.x *= scalar;
  6705. this.y *= scalar;
  6706. this.z *= scalar;
  6707. return this;
  6708. },
  6709. multiplyVectors: function ( a, b ) {
  6710. this.x = a.x * b.x;
  6711. this.y = a.y * b.y;
  6712. this.z = a.z * b.z;
  6713. return this;
  6714. },
  6715. applyEuler: function ( euler ) {
  6716. if ( ! ( euler && euler.isEuler ) ) {
  6717. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6718. }
  6719. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  6720. },
  6721. applyAxisAngle: function ( axis, angle ) {
  6722. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  6723. },
  6724. applyMatrix3: function ( m ) {
  6725. var x = this.x, y = this.y, z = this.z;
  6726. var e = m.elements;
  6727. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6728. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6729. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6730. return this;
  6731. },
  6732. applyMatrix4: function ( m ) {
  6733. var x = this.x, y = this.y, z = this.z;
  6734. var e = m.elements;
  6735. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6736. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6737. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6738. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6739. return this;
  6740. },
  6741. applyQuaternion: function ( q ) {
  6742. var x = this.x, y = this.y, z = this.z;
  6743. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6744. // calculate quat * vector
  6745. var ix = qw * x + qy * z - qz * y;
  6746. var iy = qw * y + qz * x - qx * z;
  6747. var iz = qw * z + qx * y - qy * x;
  6748. var iw = - qx * x - qy * y - qz * z;
  6749. // calculate result * inverse quat
  6750. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6751. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6752. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6753. return this;
  6754. },
  6755. project: function ( camera ) {
  6756. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6757. },
  6758. unproject: function ( camera ) {
  6759. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  6760. },
  6761. transformDirection: function ( m ) {
  6762. // input: THREE.Matrix4 affine matrix
  6763. // vector interpreted as a direction
  6764. var x = this.x, y = this.y, z = this.z;
  6765. var e = m.elements;
  6766. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6767. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6768. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6769. return this.normalize();
  6770. },
  6771. divide: function ( v ) {
  6772. this.x /= v.x;
  6773. this.y /= v.y;
  6774. this.z /= v.z;
  6775. return this;
  6776. },
  6777. divideScalar: function ( scalar ) {
  6778. return this.multiplyScalar( 1 / scalar );
  6779. },
  6780. min: function ( v ) {
  6781. this.x = Math.min( this.x, v.x );
  6782. this.y = Math.min( this.y, v.y );
  6783. this.z = Math.min( this.z, v.z );
  6784. return this;
  6785. },
  6786. max: function ( v ) {
  6787. this.x = Math.max( this.x, v.x );
  6788. this.y = Math.max( this.y, v.y );
  6789. this.z = Math.max( this.z, v.z );
  6790. return this;
  6791. },
  6792. clamp: function ( min, max ) {
  6793. // assumes min < max, componentwise
  6794. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6795. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6796. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6797. return this;
  6798. },
  6799. clampScalar: function ( minVal, maxVal ) {
  6800. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6801. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6802. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  6803. return this;
  6804. },
  6805. clampLength: function ( min, max ) {
  6806. var length = this.length();
  6807. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6808. },
  6809. floor: function () {
  6810. this.x = Math.floor( this.x );
  6811. this.y = Math.floor( this.y );
  6812. this.z = Math.floor( this.z );
  6813. return this;
  6814. },
  6815. ceil: function () {
  6816. this.x = Math.ceil( this.x );
  6817. this.y = Math.ceil( this.y );
  6818. this.z = Math.ceil( this.z );
  6819. return this;
  6820. },
  6821. round: function () {
  6822. this.x = Math.round( this.x );
  6823. this.y = Math.round( this.y );
  6824. this.z = Math.round( this.z );
  6825. return this;
  6826. },
  6827. roundToZero: function () {
  6828. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6829. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6830. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6831. return this;
  6832. },
  6833. negate: function () {
  6834. this.x = - this.x;
  6835. this.y = - this.y;
  6836. this.z = - this.z;
  6837. return this;
  6838. },
  6839. dot: function ( v ) {
  6840. return this.x * v.x + this.y * v.y + this.z * v.z;
  6841. },
  6842. // TODO lengthSquared?
  6843. lengthSq: function () {
  6844. return this.x * this.x + this.y * this.y + this.z * this.z;
  6845. },
  6846. length: function () {
  6847. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6848. },
  6849. manhattanLength: function () {
  6850. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6851. },
  6852. normalize: function () {
  6853. return this.divideScalar( this.length() || 1 );
  6854. },
  6855. setLength: function ( length ) {
  6856. return this.normalize().multiplyScalar( length );
  6857. },
  6858. lerp: function ( v, alpha ) {
  6859. this.x += ( v.x - this.x ) * alpha;
  6860. this.y += ( v.y - this.y ) * alpha;
  6861. this.z += ( v.z - this.z ) * alpha;
  6862. return this;
  6863. },
  6864. lerpVectors: function ( v1, v2, alpha ) {
  6865. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6866. },
  6867. cross: function ( v, w ) {
  6868. if ( w !== undefined ) {
  6869. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6870. return this.crossVectors( v, w );
  6871. }
  6872. return this.crossVectors( this, v );
  6873. },
  6874. crossVectors: function ( a, b ) {
  6875. var ax = a.x, ay = a.y, az = a.z;
  6876. var bx = b.x, by = b.y, bz = b.z;
  6877. this.x = ay * bz - az * by;
  6878. this.y = az * bx - ax * bz;
  6879. this.z = ax * by - ay * bx;
  6880. return this;
  6881. },
  6882. projectOnVector: function ( vector ) {
  6883. var scalar = vector.dot( this ) / vector.lengthSq();
  6884. return this.copy( vector ).multiplyScalar( scalar );
  6885. },
  6886. projectOnPlane: function ( planeNormal ) {
  6887. _vector.copy( this ).projectOnVector( planeNormal );
  6888. return this.sub( _vector );
  6889. },
  6890. reflect: function ( normal ) {
  6891. // reflect incident vector off plane orthogonal to normal
  6892. // normal is assumed to have unit length
  6893. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6894. },
  6895. angleTo: function ( v ) {
  6896. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6897. // clamp, to handle numerical problems
  6898. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6899. },
  6900. distanceTo: function ( v ) {
  6901. return Math.sqrt( this.distanceToSquared( v ) );
  6902. },
  6903. distanceToSquared: function ( v ) {
  6904. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6905. return dx * dx + dy * dy + dz * dz;
  6906. },
  6907. manhattanDistanceTo: function ( v ) {
  6908. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6909. },
  6910. setFromSpherical: function ( s ) {
  6911. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6912. },
  6913. setFromSphericalCoords: function ( radius, phi, theta ) {
  6914. var sinPhiRadius = Math.sin( phi ) * radius;
  6915. this.x = sinPhiRadius * Math.sin( theta );
  6916. this.y = Math.cos( phi ) * radius;
  6917. this.z = sinPhiRadius * Math.cos( theta );
  6918. return this;
  6919. },
  6920. setFromCylindrical: function ( c ) {
  6921. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  6922. },
  6923. setFromCylindricalCoords: function ( radius, theta, y ) {
  6924. this.x = radius * Math.sin( theta );
  6925. this.y = y;
  6926. this.z = radius * Math.cos( theta );
  6927. return this;
  6928. },
  6929. setFromMatrixPosition: function ( m ) {
  6930. var e = m.elements;
  6931. this.x = e[ 12 ];
  6932. this.y = e[ 13 ];
  6933. this.z = e[ 14 ];
  6934. return this;
  6935. },
  6936. setFromMatrixScale: function ( m ) {
  6937. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6938. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6939. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6940. this.x = sx;
  6941. this.y = sy;
  6942. this.z = sz;
  6943. return this;
  6944. },
  6945. setFromMatrixColumn: function ( m, index ) {
  6946. return this.fromArray( m.elements, index * 4 );
  6947. },
  6948. equals: function ( v ) {
  6949. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6950. },
  6951. fromArray: function ( array, offset ) {
  6952. if ( offset === undefined ) { offset = 0; }
  6953. this.x = array[ offset ];
  6954. this.y = array[ offset + 1 ];
  6955. this.z = array[ offset + 2 ];
  6956. return this;
  6957. },
  6958. toArray: function ( array, offset ) {
  6959. if ( array === undefined ) { array = []; }
  6960. if ( offset === undefined ) { offset = 0; }
  6961. array[ offset ] = this.x;
  6962. array[ offset + 1 ] = this.y;
  6963. array[ offset + 2 ] = this.z;
  6964. return array;
  6965. },
  6966. fromBufferAttribute: function ( attribute, index, offset ) {
  6967. if ( offset !== undefined ) {
  6968. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6969. }
  6970. this.x = attribute.getX( index );
  6971. this.y = attribute.getY( index );
  6972. this.z = attribute.getZ( index );
  6973. return this;
  6974. }
  6975. } );
  6976. /**
  6977. * @author alteredq / http://alteredqualia.com/
  6978. * @author WestLangley / http://github.com/WestLangley
  6979. * @author bhouston / http://clara.io
  6980. * @author tschw
  6981. */
  6982. var _vector$1 = new Vector3();
  6983. function Matrix3() {
  6984. this.elements = [
  6985. 1, 0, 0,
  6986. 0, 1, 0,
  6987. 0, 0, 1
  6988. ];
  6989. if ( arguments.length > 0 ) {
  6990. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6991. }
  6992. }
  6993. Object.assign( Matrix3.prototype, {
  6994. isMatrix3: true,
  6995. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6996. var te = this.elements;
  6997. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6998. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6999. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  7000. return this;
  7001. },
  7002. identity: function () {
  7003. this.set(
  7004. 1, 0, 0,
  7005. 0, 1, 0,
  7006. 0, 0, 1
  7007. );
  7008. return this;
  7009. },
  7010. clone: function () {
  7011. return new this.constructor().fromArray( this.elements );
  7012. },
  7013. copy: function ( m ) {
  7014. var te = this.elements;
  7015. var me = m.elements;
  7016. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  7017. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  7018. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  7019. return this;
  7020. },
  7021. setFromMatrix4: function ( m ) {
  7022. var me = m.elements;
  7023. this.set(
  7024. me[ 0 ], me[ 4 ], me[ 8 ],
  7025. me[ 1 ], me[ 5 ], me[ 9 ],
  7026. me[ 2 ], me[ 6 ], me[ 10 ]
  7027. );
  7028. return this;
  7029. },
  7030. applyToBufferAttribute: function ( attribute ) {
  7031. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  7032. _vector$1.x = attribute.getX( i );
  7033. _vector$1.y = attribute.getY( i );
  7034. _vector$1.z = attribute.getZ( i );
  7035. _vector$1.applyMatrix3( this );
  7036. attribute.setXYZ( i, _vector$1.x, _vector$1.y, _vector$1.z );
  7037. }
  7038. return attribute;
  7039. },
  7040. multiply: function ( m ) {
  7041. return this.multiplyMatrices( this, m );
  7042. },
  7043. premultiply: function ( m ) {
  7044. return this.multiplyMatrices( m, this );
  7045. },
  7046. multiplyMatrices: function ( a, b ) {
  7047. var ae = a.elements;
  7048. var be = b.elements;
  7049. var te = this.elements;
  7050. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  7051. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  7052. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  7053. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  7054. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  7055. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  7056. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  7057. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  7058. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  7059. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  7060. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  7061. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  7062. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  7063. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  7064. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  7065. return this;
  7066. },
  7067. multiplyScalar: function ( s ) {
  7068. var te = this.elements;
  7069. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  7070. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  7071. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  7072. return this;
  7073. },
  7074. determinant: function () {
  7075. var te = this.elements;
  7076. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  7077. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  7078. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  7079. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  7080. },
  7081. getInverse: function ( matrix, throwOnDegenerate ) {
  7082. if ( matrix && matrix.isMatrix4 ) {
  7083. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  7084. }
  7085. var me = matrix.elements,
  7086. te = this.elements,
  7087. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  7088. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  7089. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  7090. t11 = n33 * n22 - n32 * n23,
  7091. t12 = n32 * n13 - n33 * n12,
  7092. t13 = n23 * n12 - n22 * n13,
  7093. det = n11 * t11 + n21 * t12 + n31 * t13;
  7094. if ( det === 0 ) {
  7095. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  7096. if ( throwOnDegenerate === true ) {
  7097. throw new Error( msg );
  7098. } else {
  7099. console.warn( msg );
  7100. }
  7101. return this.identity();
  7102. }
  7103. var detInv = 1 / det;
  7104. te[ 0 ] = t11 * detInv;
  7105. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  7106. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  7107. te[ 3 ] = t12 * detInv;
  7108. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  7109. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  7110. te[ 6 ] = t13 * detInv;
  7111. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  7112. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  7113. return this;
  7114. },
  7115. transpose: function () {
  7116. var tmp, m = this.elements;
  7117. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  7118. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  7119. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  7120. return this;
  7121. },
  7122. getNormalMatrix: function ( matrix4 ) {
  7123. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  7124. },
  7125. transposeIntoArray: function ( r ) {
  7126. var m = this.elements;
  7127. r[ 0 ] = m[ 0 ];
  7128. r[ 1 ] = m[ 3 ];
  7129. r[ 2 ] = m[ 6 ];
  7130. r[ 3 ] = m[ 1 ];
  7131. r[ 4 ] = m[ 4 ];
  7132. r[ 5 ] = m[ 7 ];
  7133. r[ 6 ] = m[ 2 ];
  7134. r[ 7 ] = m[ 5 ];
  7135. r[ 8 ] = m[ 8 ];
  7136. return this;
  7137. },
  7138. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  7139. var c = Math.cos( rotation );
  7140. var s = Math.sin( rotation );
  7141. this.set(
  7142. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  7143. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  7144. 0, 0, 1
  7145. );
  7146. },
  7147. scale: function ( sx, sy ) {
  7148. var te = this.elements;
  7149. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  7150. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  7151. return this;
  7152. },
  7153. rotate: function ( theta ) {
  7154. var c = Math.cos( theta );
  7155. var s = Math.sin( theta );
  7156. var te = this.elements;
  7157. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  7158. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  7159. te[ 0 ] = c * a11 + s * a21;
  7160. te[ 3 ] = c * a12 + s * a22;
  7161. te[ 6 ] = c * a13 + s * a23;
  7162. te[ 1 ] = - s * a11 + c * a21;
  7163. te[ 4 ] = - s * a12 + c * a22;
  7164. te[ 7 ] = - s * a13 + c * a23;
  7165. return this;
  7166. },
  7167. translate: function ( tx, ty ) {
  7168. var te = this.elements;
  7169. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  7170. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  7171. return this;
  7172. },
  7173. equals: function ( matrix ) {
  7174. var te = this.elements;
  7175. var me = matrix.elements;
  7176. for ( var i = 0; i < 9; i ++ ) {
  7177. if ( te[ i ] !== me[ i ] ) { return false; }
  7178. }
  7179. return true;
  7180. },
  7181. fromArray: function ( array, offset ) {
  7182. if ( offset === undefined ) { offset = 0; }
  7183. for ( var i = 0; i < 9; i ++ ) {
  7184. this.elements[ i ] = array[ i + offset ];
  7185. }
  7186. return this;
  7187. },
  7188. toArray: function ( array, offset ) {
  7189. if ( array === undefined ) { array = []; }
  7190. if ( offset === undefined ) { offset = 0; }
  7191. var te = this.elements;
  7192. array[ offset ] = te[ 0 ];
  7193. array[ offset + 1 ] = te[ 1 ];
  7194. array[ offset + 2 ] = te[ 2 ];
  7195. array[ offset + 3 ] = te[ 3 ];
  7196. array[ offset + 4 ] = te[ 4 ];
  7197. array[ offset + 5 ] = te[ 5 ];
  7198. array[ offset + 6 ] = te[ 6 ];
  7199. array[ offset + 7 ] = te[ 7 ];
  7200. array[ offset + 8 ] = te[ 8 ];
  7201. return array;
  7202. }
  7203. } );
  7204. /**
  7205. * @author mrdoob / http://mrdoob.com/
  7206. * @author alteredq / http://alteredqualia.com/
  7207. * @author szimek / https://github.com/szimek/
  7208. */
  7209. var _canvas;
  7210. var ImageUtils = {
  7211. getDataURL: function ( image ) {
  7212. var canvas;
  7213. if ( typeof HTMLCanvasElement == 'undefined' ) {
  7214. return image.src;
  7215. } else if ( image instanceof HTMLCanvasElement ) {
  7216. canvas = image;
  7217. } else {
  7218. if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); }
  7219. _canvas.width = image.width;
  7220. _canvas.height = image.height;
  7221. var context = _canvas.getContext( '2d' );
  7222. if ( image instanceof ImageData ) {
  7223. context.putImageData( image, 0, 0 );
  7224. } else {
  7225. context.drawImage( image, 0, 0, image.width, image.height );
  7226. }
  7227. canvas = _canvas;
  7228. }
  7229. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  7230. return canvas.toDataURL( 'image/jpeg', 0.6 );
  7231. } else {
  7232. return canvas.toDataURL( 'image/png' );
  7233. }
  7234. }
  7235. };
  7236. /**
  7237. * @author mrdoob / http://mrdoob.com/
  7238. * @author alteredq / http://alteredqualia.com/
  7239. * @author szimek / https://github.com/szimek/
  7240. */
  7241. var textureId = 0;
  7242. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7243. Object.defineProperty( this, 'id', { value: textureId ++ } );
  7244. this.uuid = _Math.generateUUID();
  7245. this.name = '';
  7246. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  7247. this.mipmaps = [];
  7248. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  7249. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  7250. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  7251. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  7252. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  7253. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7254. this.format = format !== undefined ? format : RGBAFormat;
  7255. this.type = type !== undefined ? type : UnsignedByteType;
  7256. this.offset = new Vector2( 0, 0 );
  7257. this.repeat = new Vector2( 1, 1 );
  7258. this.center = new Vector2( 0, 0 );
  7259. this.rotation = 0;
  7260. this.matrixAutoUpdate = true;
  7261. this.matrix = new Matrix3();
  7262. this.generateMipmaps = true;
  7263. this.premultiplyAlpha = false;
  7264. this.flipY = true;
  7265. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7266. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  7267. //
  7268. // Also changing the encoding after already used by a Material will not automatically make the Material
  7269. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  7270. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  7271. this.version = 0;
  7272. this.onUpdate = null;
  7273. }
  7274. Texture.DEFAULT_IMAGE = undefined;
  7275. Texture.DEFAULT_MAPPING = UVMapping;
  7276. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7277. constructor: Texture,
  7278. isTexture: true,
  7279. updateMatrix: function () {
  7280. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  7281. },
  7282. clone: function () {
  7283. return new this.constructor().copy( this );
  7284. },
  7285. copy: function ( source ) {
  7286. this.name = source.name;
  7287. this.image = source.image;
  7288. this.mipmaps = source.mipmaps.slice( 0 );
  7289. this.mapping = source.mapping;
  7290. this.wrapS = source.wrapS;
  7291. this.wrapT = source.wrapT;
  7292. this.magFilter = source.magFilter;
  7293. this.minFilter = source.minFilter;
  7294. this.anisotropy = source.anisotropy;
  7295. this.format = source.format;
  7296. this.type = source.type;
  7297. this.offset.copy( source.offset );
  7298. this.repeat.copy( source.repeat );
  7299. this.center.copy( source.center );
  7300. this.rotation = source.rotation;
  7301. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7302. this.matrix.copy( source.matrix );
  7303. this.generateMipmaps = source.generateMipmaps;
  7304. this.premultiplyAlpha = source.premultiplyAlpha;
  7305. this.flipY = source.flipY;
  7306. this.unpackAlignment = source.unpackAlignment;
  7307. this.encoding = source.encoding;
  7308. return this;
  7309. },
  7310. toJSON: function ( meta ) {
  7311. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  7312. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  7313. return meta.textures[ this.uuid ];
  7314. }
  7315. var output = {
  7316. metadata: {
  7317. version: 4.5,
  7318. type: 'Texture',
  7319. generator: 'Texture.toJSON'
  7320. },
  7321. uuid: this.uuid,
  7322. name: this.name,
  7323. mapping: this.mapping,
  7324. repeat: [ this.repeat.x, this.repeat.y ],
  7325. offset: [ this.offset.x, this.offset.y ],
  7326. center: [ this.center.x, this.center.y ],
  7327. rotation: this.rotation,
  7328. wrap: [ this.wrapS, this.wrapT ],
  7329. format: this.format,
  7330. type: this.type,
  7331. encoding: this.encoding,
  7332. minFilter: this.minFilter,
  7333. magFilter: this.magFilter,
  7334. anisotropy: this.anisotropy,
  7335. flipY: this.flipY,
  7336. premultiplyAlpha: this.premultiplyAlpha,
  7337. unpackAlignment: this.unpackAlignment
  7338. };
  7339. if ( this.image !== undefined ) {
  7340. // TODO: Move to THREE.Image
  7341. var image = this.image;
  7342. if ( image.uuid === undefined ) {
  7343. image.uuid = _Math.generateUUID(); // UGH
  7344. }
  7345. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  7346. var url;
  7347. if ( Array.isArray( image ) ) {
  7348. // process array of images e.g. CubeTexture
  7349. url = [];
  7350. for ( var i = 0, l = image.length; i < l; i ++ ) {
  7351. url.push( ImageUtils.getDataURL( image[ i ] ) );
  7352. }
  7353. } else {
  7354. // process single image
  7355. url = ImageUtils.getDataURL( image );
  7356. }
  7357. meta.images[ image.uuid ] = {
  7358. uuid: image.uuid,
  7359. url: url
  7360. };
  7361. }
  7362. output.image = image.uuid;
  7363. }
  7364. if ( ! isRootObject ) {
  7365. meta.textures[ this.uuid ] = output;
  7366. }
  7367. return output;
  7368. },
  7369. dispose: function () {
  7370. this.dispatchEvent( { type: 'dispose' } );
  7371. },
  7372. transformUv: function ( uv ) {
  7373. if ( this.mapping !== UVMapping ) { return uv; }
  7374. uv.applyMatrix3( this.matrix );
  7375. if ( uv.x < 0 || uv.x > 1 ) {
  7376. switch ( this.wrapS ) {
  7377. case RepeatWrapping:
  7378. uv.x = uv.x - Math.floor( uv.x );
  7379. break;
  7380. case ClampToEdgeWrapping:
  7381. uv.x = uv.x < 0 ? 0 : 1;
  7382. break;
  7383. case MirroredRepeatWrapping:
  7384. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  7385. uv.x = Math.ceil( uv.x ) - uv.x;
  7386. } else {
  7387. uv.x = uv.x - Math.floor( uv.x );
  7388. }
  7389. break;
  7390. }
  7391. }
  7392. if ( uv.y < 0 || uv.y > 1 ) {
  7393. switch ( this.wrapT ) {
  7394. case RepeatWrapping:
  7395. uv.y = uv.y - Math.floor( uv.y );
  7396. break;
  7397. case ClampToEdgeWrapping:
  7398. uv.y = uv.y < 0 ? 0 : 1;
  7399. break;
  7400. case MirroredRepeatWrapping:
  7401. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  7402. uv.y = Math.ceil( uv.y ) - uv.y;
  7403. } else {
  7404. uv.y = uv.y - Math.floor( uv.y );
  7405. }
  7406. break;
  7407. }
  7408. }
  7409. if ( this.flipY ) {
  7410. uv.y = 1 - uv.y;
  7411. }
  7412. return uv;
  7413. }
  7414. } );
  7415. Object.defineProperty( Texture.prototype, "needsUpdate", {
  7416. set: function ( value ) {
  7417. if ( value === true ) { this.version ++; }
  7418. }
  7419. } );
  7420. /**
  7421. * @author supereggbert / http://www.paulbrunt.co.uk/
  7422. * @author philogb / http://blog.thejit.org/
  7423. * @author mikael emtinger / http://gomo.se/
  7424. * @author egraether / http://egraether.com/
  7425. * @author WestLangley / http://github.com/WestLangley
  7426. */
  7427. function Vector4( x, y, z, w ) {
  7428. this.x = x || 0;
  7429. this.y = y || 0;
  7430. this.z = z || 0;
  7431. this.w = ( w !== undefined ) ? w : 1;
  7432. }
  7433. Object.defineProperties( Vector4.prototype, {
  7434. "width": {
  7435. get: function () {
  7436. return this.z;
  7437. },
  7438. set: function ( value ) {
  7439. this.z = value;
  7440. }
  7441. },
  7442. "height": {
  7443. get: function () {
  7444. return this.w;
  7445. },
  7446. set: function ( value ) {
  7447. this.w = value;
  7448. }
  7449. }
  7450. } );
  7451. Object.assign( Vector4.prototype, {
  7452. isVector4: true,
  7453. set: function ( x, y, z, w ) {
  7454. this.x = x;
  7455. this.y = y;
  7456. this.z = z;
  7457. this.w = w;
  7458. return this;
  7459. },
  7460. setScalar: function ( scalar ) {
  7461. this.x = scalar;
  7462. this.y = scalar;
  7463. this.z = scalar;
  7464. this.w = scalar;
  7465. return this;
  7466. },
  7467. setX: function ( x ) {
  7468. this.x = x;
  7469. return this;
  7470. },
  7471. setY: function ( y ) {
  7472. this.y = y;
  7473. return this;
  7474. },
  7475. setZ: function ( z ) {
  7476. this.z = z;
  7477. return this;
  7478. },
  7479. setW: function ( w ) {
  7480. this.w = w;
  7481. return this;
  7482. },
  7483. setComponent: function ( index, value ) {
  7484. switch ( index ) {
  7485. case 0: this.x = value; break;
  7486. case 1: this.y = value; break;
  7487. case 2: this.z = value; break;
  7488. case 3: this.w = value; break;
  7489. default: throw new Error( 'index is out of range: ' + index );
  7490. }
  7491. return this;
  7492. },
  7493. getComponent: function ( index ) {
  7494. switch ( index ) {
  7495. case 0: return this.x;
  7496. case 1: return this.y;
  7497. case 2: return this.z;
  7498. case 3: return this.w;
  7499. default: throw new Error( 'index is out of range: ' + index );
  7500. }
  7501. },
  7502. clone: function () {
  7503. return new this.constructor( this.x, this.y, this.z, this.w );
  7504. },
  7505. copy: function ( v ) {
  7506. this.x = v.x;
  7507. this.y = v.y;
  7508. this.z = v.z;
  7509. this.w = ( v.w !== undefined ) ? v.w : 1;
  7510. return this;
  7511. },
  7512. add: function ( v, w ) {
  7513. if ( w !== undefined ) {
  7514. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  7515. return this.addVectors( v, w );
  7516. }
  7517. this.x += v.x;
  7518. this.y += v.y;
  7519. this.z += v.z;
  7520. this.w += v.w;
  7521. return this;
  7522. },
  7523. addScalar: function ( s ) {
  7524. this.x += s;
  7525. this.y += s;
  7526. this.z += s;
  7527. this.w += s;
  7528. return this;
  7529. },
  7530. addVectors: function ( a, b ) {
  7531. this.x = a.x + b.x;
  7532. this.y = a.y + b.y;
  7533. this.z = a.z + b.z;
  7534. this.w = a.w + b.w;
  7535. return this;
  7536. },
  7537. addScaledVector: function ( v, s ) {
  7538. this.x += v.x * s;
  7539. this.y += v.y * s;
  7540. this.z += v.z * s;
  7541. this.w += v.w * s;
  7542. return this;
  7543. },
  7544. sub: function ( v, w ) {
  7545. if ( w !== undefined ) {
  7546. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  7547. return this.subVectors( v, w );
  7548. }
  7549. this.x -= v.x;
  7550. this.y -= v.y;
  7551. this.z -= v.z;
  7552. this.w -= v.w;
  7553. return this;
  7554. },
  7555. subScalar: function ( s ) {
  7556. this.x -= s;
  7557. this.y -= s;
  7558. this.z -= s;
  7559. this.w -= s;
  7560. return this;
  7561. },
  7562. subVectors: function ( a, b ) {
  7563. this.x = a.x - b.x;
  7564. this.y = a.y - b.y;
  7565. this.z = a.z - b.z;
  7566. this.w = a.w - b.w;
  7567. return this;
  7568. },
  7569. multiplyScalar: function ( scalar ) {
  7570. this.x *= scalar;
  7571. this.y *= scalar;
  7572. this.z *= scalar;
  7573. this.w *= scalar;
  7574. return this;
  7575. },
  7576. applyMatrix4: function ( m ) {
  7577. var x = this.x, y = this.y, z = this.z, w = this.w;
  7578. var e = m.elements;
  7579. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  7580. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  7581. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  7582. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  7583. return this;
  7584. },
  7585. divideScalar: function ( scalar ) {
  7586. return this.multiplyScalar( 1 / scalar );
  7587. },
  7588. setAxisAngleFromQuaternion: function ( q ) {
  7589. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7590. // q is assumed to be normalized
  7591. this.w = 2 * Math.acos( q.w );
  7592. var s = Math.sqrt( 1 - q.w * q.w );
  7593. if ( s < 0.0001 ) {
  7594. this.x = 1;
  7595. this.y = 0;
  7596. this.z = 0;
  7597. } else {
  7598. this.x = q.x / s;
  7599. this.y = q.y / s;
  7600. this.z = q.z / s;
  7601. }
  7602. return this;
  7603. },
  7604. setAxisAngleFromRotationMatrix: function ( m ) {
  7605. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7606. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7607. var angle, x, y, z, // variables for result
  7608. epsilon = 0.01, // margin to allow for rounding errors
  7609. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  7610. te = m.elements,
  7611. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7612. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7613. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7614. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  7615. ( Math.abs( m13 - m31 ) < epsilon ) &&
  7616. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  7617. // singularity found
  7618. // first check for identity matrix which must have +1 for all terms
  7619. // in leading diagonal and zero in other terms
  7620. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  7621. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  7622. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  7623. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  7624. // this singularity is identity matrix so angle = 0
  7625. this.set( 1, 0, 0, 0 );
  7626. return this; // zero angle, arbitrary axis
  7627. }
  7628. // otherwise this singularity is angle = 180
  7629. angle = Math.PI;
  7630. var xx = ( m11 + 1 ) / 2;
  7631. var yy = ( m22 + 1 ) / 2;
  7632. var zz = ( m33 + 1 ) / 2;
  7633. var xy = ( m12 + m21 ) / 4;
  7634. var xz = ( m13 + m31 ) / 4;
  7635. var yz = ( m23 + m32 ) / 4;
  7636. if ( ( xx > yy ) && ( xx > zz ) ) {
  7637. // m11 is the largest diagonal term
  7638. if ( xx < epsilon ) {
  7639. x = 0;
  7640. y = 0.707106781;
  7641. z = 0.707106781;
  7642. } else {
  7643. x = Math.sqrt( xx );
  7644. y = xy / x;
  7645. z = xz / x;
  7646. }
  7647. } else if ( yy > zz ) {
  7648. // m22 is the largest diagonal term
  7649. if ( yy < epsilon ) {
  7650. x = 0.707106781;
  7651. y = 0;
  7652. z = 0.707106781;
  7653. } else {
  7654. y = Math.sqrt( yy );
  7655. x = xy / y;
  7656. z = yz / y;
  7657. }
  7658. } else {
  7659. // m33 is the largest diagonal term so base result on this
  7660. if ( zz < epsilon ) {
  7661. x = 0.707106781;
  7662. y = 0.707106781;
  7663. z = 0;
  7664. } else {
  7665. z = Math.sqrt( zz );
  7666. x = xz / z;
  7667. y = yz / z;
  7668. }
  7669. }
  7670. this.set( x, y, z, angle );
  7671. return this; // return 180 deg rotation
  7672. }
  7673. // as we have reached here there are no singularities so we can handle normally
  7674. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  7675. ( m13 - m31 ) * ( m13 - m31 ) +
  7676. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  7677. if ( Math.abs( s ) < 0.001 ) { s = 1; }
  7678. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7679. // caught by singularity test above, but I've left it in just in case
  7680. this.x = ( m32 - m23 ) / s;
  7681. this.y = ( m13 - m31 ) / s;
  7682. this.z = ( m21 - m12 ) / s;
  7683. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  7684. return this;
  7685. },
  7686. min: function ( v ) {
  7687. this.x = Math.min( this.x, v.x );
  7688. this.y = Math.min( this.y, v.y );
  7689. this.z = Math.min( this.z, v.z );
  7690. this.w = Math.min( this.w, v.w );
  7691. return this;
  7692. },
  7693. max: function ( v ) {
  7694. this.x = Math.max( this.x, v.x );
  7695. this.y = Math.max( this.y, v.y );
  7696. this.z = Math.max( this.z, v.z );
  7697. this.w = Math.max( this.w, v.w );
  7698. return this;
  7699. },
  7700. clamp: function ( min, max ) {
  7701. // assumes min < max, componentwise
  7702. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7703. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7704. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7705. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  7706. return this;
  7707. },
  7708. clampScalar: function ( minVal, maxVal ) {
  7709. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  7710. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  7711. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  7712. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  7713. return this;
  7714. },
  7715. clampLength: function ( min, max ) {
  7716. var length = this.length();
  7717. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7718. },
  7719. floor: function () {
  7720. this.x = Math.floor( this.x );
  7721. this.y = Math.floor( this.y );
  7722. this.z = Math.floor( this.z );
  7723. this.w = Math.floor( this.w );
  7724. return this;
  7725. },
  7726. ceil: function () {
  7727. this.x = Math.ceil( this.x );
  7728. this.y = Math.ceil( this.y );
  7729. this.z = Math.ceil( this.z );
  7730. this.w = Math.ceil( this.w );
  7731. return this;
  7732. },
  7733. round: function () {
  7734. this.x = Math.round( this.x );
  7735. this.y = Math.round( this.y );
  7736. this.z = Math.round( this.z );
  7737. this.w = Math.round( this.w );
  7738. return this;
  7739. },
  7740. roundToZero: function () {
  7741. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7742. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7743. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7744. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7745. return this;
  7746. },
  7747. negate: function () {
  7748. this.x = - this.x;
  7749. this.y = - this.y;
  7750. this.z = - this.z;
  7751. this.w = - this.w;
  7752. return this;
  7753. },
  7754. dot: function ( v ) {
  7755. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7756. },
  7757. lengthSq: function () {
  7758. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7759. },
  7760. length: function () {
  7761. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7762. },
  7763. manhattanLength: function () {
  7764. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7765. },
  7766. normalize: function () {
  7767. return this.divideScalar( this.length() || 1 );
  7768. },
  7769. setLength: function ( length ) {
  7770. return this.normalize().multiplyScalar( length );
  7771. },
  7772. lerp: function ( v, alpha ) {
  7773. this.x += ( v.x - this.x ) * alpha;
  7774. this.y += ( v.y - this.y ) * alpha;
  7775. this.z += ( v.z - this.z ) * alpha;
  7776. this.w += ( v.w - this.w ) * alpha;
  7777. return this;
  7778. },
  7779. lerpVectors: function ( v1, v2, alpha ) {
  7780. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7781. },
  7782. equals: function ( v ) {
  7783. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7784. },
  7785. fromArray: function ( array, offset ) {
  7786. if ( offset === undefined ) { offset = 0; }
  7787. this.x = array[ offset ];
  7788. this.y = array[ offset + 1 ];
  7789. this.z = array[ offset + 2 ];
  7790. this.w = array[ offset + 3 ];
  7791. return this;
  7792. },
  7793. toArray: function ( array, offset ) {
  7794. if ( array === undefined ) { array = []; }
  7795. if ( offset === undefined ) { offset = 0; }
  7796. array[ offset ] = this.x;
  7797. array[ offset + 1 ] = this.y;
  7798. array[ offset + 2 ] = this.z;
  7799. array[ offset + 3 ] = this.w;
  7800. return array;
  7801. },
  7802. fromBufferAttribute: function ( attribute, index, offset ) {
  7803. if ( offset !== undefined ) {
  7804. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7805. }
  7806. this.x = attribute.getX( index );
  7807. this.y = attribute.getY( index );
  7808. this.z = attribute.getZ( index );
  7809. this.w = attribute.getW( index );
  7810. return this;
  7811. }
  7812. } );
  7813. /**
  7814. * @author szimek / https://github.com/szimek/
  7815. * @author alteredq / http://alteredqualia.com/
  7816. * @author Marius Kintel / https://github.com/kintel
  7817. */
  7818. /*
  7819. In options, we can specify:
  7820. * Texture parameters for an auto-generated target texture
  7821. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7822. */
  7823. function WebGLRenderTarget( width, height, options ) {
  7824. this.width = width;
  7825. this.height = height;
  7826. this.scissor = new Vector4( 0, 0, width, height );
  7827. this.scissorTest = false;
  7828. this.viewport = new Vector4( 0, 0, width, height );
  7829. options = options || {};
  7830. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7831. this.texture.image = {};
  7832. this.texture.image.width = width;
  7833. this.texture.image.height = height;
  7834. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7835. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7836. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7837. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7838. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7839. }
  7840. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7841. constructor: WebGLRenderTarget,
  7842. isWebGLRenderTarget: true,
  7843. setSize: function ( width, height ) {
  7844. if ( this.width !== width || this.height !== height ) {
  7845. this.width = width;
  7846. this.height = height;
  7847. this.texture.image.width = width;
  7848. this.texture.image.height = height;
  7849. this.dispose();
  7850. }
  7851. this.viewport.set( 0, 0, width, height );
  7852. this.scissor.set( 0, 0, width, height );
  7853. },
  7854. clone: function () {
  7855. return new this.constructor().copy( this );
  7856. },
  7857. copy: function ( source ) {
  7858. this.width = source.width;
  7859. this.height = source.height;
  7860. this.viewport.copy( source.viewport );
  7861. this.texture = source.texture.clone();
  7862. this.depthBuffer = source.depthBuffer;
  7863. this.stencilBuffer = source.stencilBuffer;
  7864. this.depthTexture = source.depthTexture;
  7865. return this;
  7866. },
  7867. dispose: function () {
  7868. this.dispatchEvent( { type: 'dispose' } );
  7869. }
  7870. } );
  7871. /**
  7872. * @author Mugen87 / https://github.com/Mugen87
  7873. * @author Matt DesLauriers / @mattdesl
  7874. */
  7875. function WebGLMultisampleRenderTarget( width, height, options ) {
  7876. WebGLRenderTarget.call( this, width, height, options );
  7877. this.samples = 4;
  7878. }
  7879. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  7880. constructor: WebGLMultisampleRenderTarget,
  7881. isWebGLMultisampleRenderTarget: true,
  7882. copy: function ( source ) {
  7883. WebGLRenderTarget.prototype.copy.call( this, source );
  7884. this.samples = source.samples;
  7885. return this;
  7886. }
  7887. } );
  7888. var _v1 = new Vector3();
  7889. var _m1 = new Matrix4();
  7890. var _zero = new Vector3( 0, 0, 0 );
  7891. var _one = new Vector3( 1, 1, 1 );
  7892. var _x = new Vector3();
  7893. var _y = new Vector3();
  7894. var _z = new Vector3();
  7895. /**
  7896. * @author mrdoob / http://mrdoob.com/
  7897. * @author supereggbert / http://www.paulbrunt.co.uk/
  7898. * @author philogb / http://blog.thejit.org/
  7899. * @author jordi_ros / http://plattsoft.com
  7900. * @author D1plo1d / http://github.com/D1plo1d
  7901. * @author alteredq / http://alteredqualia.com/
  7902. * @author mikael emtinger / http://gomo.se/
  7903. * @author timknip / http://www.floorplanner.com/
  7904. * @author bhouston / http://clara.io
  7905. * @author WestLangley / http://github.com/WestLangley
  7906. */
  7907. function Matrix4() {
  7908. this.elements = [
  7909. 1, 0, 0, 0,
  7910. 0, 1, 0, 0,
  7911. 0, 0, 1, 0,
  7912. 0, 0, 0, 1
  7913. ];
  7914. if ( arguments.length > 0 ) {
  7915. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  7916. }
  7917. }
  7918. Object.assign( Matrix4.prototype, {
  7919. isMatrix4: true,
  7920. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7921. var te = this.elements;
  7922. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7923. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7924. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7925. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7926. return this;
  7927. },
  7928. identity: function () {
  7929. this.set(
  7930. 1, 0, 0, 0,
  7931. 0, 1, 0, 0,
  7932. 0, 0, 1, 0,
  7933. 0, 0, 0, 1
  7934. );
  7935. return this;
  7936. },
  7937. clone: function () {
  7938. return new Matrix4().fromArray( this.elements );
  7939. },
  7940. copy: function ( m ) {
  7941. var te = this.elements;
  7942. var me = m.elements;
  7943. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7944. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7945. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7946. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7947. return this;
  7948. },
  7949. copyPosition: function ( m ) {
  7950. var te = this.elements, me = m.elements;
  7951. te[ 12 ] = me[ 12 ];
  7952. te[ 13 ] = me[ 13 ];
  7953. te[ 14 ] = me[ 14 ];
  7954. return this;
  7955. },
  7956. extractBasis: function ( xAxis, yAxis, zAxis ) {
  7957. xAxis.setFromMatrixColumn( this, 0 );
  7958. yAxis.setFromMatrixColumn( this, 1 );
  7959. zAxis.setFromMatrixColumn( this, 2 );
  7960. return this;
  7961. },
  7962. makeBasis: function ( xAxis, yAxis, zAxis ) {
  7963. this.set(
  7964. xAxis.x, yAxis.x, zAxis.x, 0,
  7965. xAxis.y, yAxis.y, zAxis.y, 0,
  7966. xAxis.z, yAxis.z, zAxis.z, 0,
  7967. 0, 0, 0, 1
  7968. );
  7969. return this;
  7970. },
  7971. extractRotation: function ( m ) {
  7972. // this method does not support reflection matrices
  7973. var te = this.elements;
  7974. var me = m.elements;
  7975. var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
  7976. var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
  7977. var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();
  7978. te[ 0 ] = me[ 0 ] * scaleX;
  7979. te[ 1 ] = me[ 1 ] * scaleX;
  7980. te[ 2 ] = me[ 2 ] * scaleX;
  7981. te[ 3 ] = 0;
  7982. te[ 4 ] = me[ 4 ] * scaleY;
  7983. te[ 5 ] = me[ 5 ] * scaleY;
  7984. te[ 6 ] = me[ 6 ] * scaleY;
  7985. te[ 7 ] = 0;
  7986. te[ 8 ] = me[ 8 ] * scaleZ;
  7987. te[ 9 ] = me[ 9 ] * scaleZ;
  7988. te[ 10 ] = me[ 10 ] * scaleZ;
  7989. te[ 11 ] = 0;
  7990. te[ 12 ] = 0;
  7991. te[ 13 ] = 0;
  7992. te[ 14 ] = 0;
  7993. te[ 15 ] = 1;
  7994. return this;
  7995. },
  7996. makeRotationFromEuler: function ( euler ) {
  7997. if ( ! ( euler && euler.isEuler ) ) {
  7998. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  7999. }
  8000. var te = this.elements;
  8001. var x = euler.x, y = euler.y, z = euler.z;
  8002. var a = Math.cos( x ), b = Math.sin( x );
  8003. var c = Math.cos( y ), d = Math.sin( y );
  8004. var e = Math.cos( z ), f = Math.sin( z );
  8005. if ( euler.order === 'XYZ' ) {
  8006. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  8007. te[ 0 ] = c * e;
  8008. te[ 4 ] = - c * f;
  8009. te[ 8 ] = d;
  8010. te[ 1 ] = af + be * d;
  8011. te[ 5 ] = ae - bf * d;
  8012. te[ 9 ] = - b * c;
  8013. te[ 2 ] = bf - ae * d;
  8014. te[ 6 ] = be + af * d;
  8015. te[ 10 ] = a * c;
  8016. } else if ( euler.order === 'YXZ' ) {
  8017. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  8018. te[ 0 ] = ce + df * b;
  8019. te[ 4 ] = de * b - cf;
  8020. te[ 8 ] = a * d;
  8021. te[ 1 ] = a * f;
  8022. te[ 5 ] = a * e;
  8023. te[ 9 ] = - b;
  8024. te[ 2 ] = cf * b - de;
  8025. te[ 6 ] = df + ce * b;
  8026. te[ 10 ] = a * c;
  8027. } else if ( euler.order === 'ZXY' ) {
  8028. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  8029. te[ 0 ] = ce - df * b;
  8030. te[ 4 ] = - a * f;
  8031. te[ 8 ] = de + cf * b;
  8032. te[ 1 ] = cf + de * b;
  8033. te[ 5 ] = a * e;
  8034. te[ 9 ] = df - ce * b;
  8035. te[ 2 ] = - a * d;
  8036. te[ 6 ] = b;
  8037. te[ 10 ] = a * c;
  8038. } else if ( euler.order === 'ZYX' ) {
  8039. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  8040. te[ 0 ] = c * e;
  8041. te[ 4 ] = be * d - af;
  8042. te[ 8 ] = ae * d + bf;
  8043. te[ 1 ] = c * f;
  8044. te[ 5 ] = bf * d + ae;
  8045. te[ 9 ] = af * d - be;
  8046. te[ 2 ] = - d;
  8047. te[ 6 ] = b * c;
  8048. te[ 10 ] = a * c;
  8049. } else if ( euler.order === 'YZX' ) {
  8050. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8051. te[ 0 ] = c * e;
  8052. te[ 4 ] = bd - ac * f;
  8053. te[ 8 ] = bc * f + ad;
  8054. te[ 1 ] = f;
  8055. te[ 5 ] = a * e;
  8056. te[ 9 ] = - b * e;
  8057. te[ 2 ] = - d * e;
  8058. te[ 6 ] = ad * f + bc;
  8059. te[ 10 ] = ac - bd * f;
  8060. } else if ( euler.order === 'XZY' ) {
  8061. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8062. te[ 0 ] = c * e;
  8063. te[ 4 ] = - f;
  8064. te[ 8 ] = d * e;
  8065. te[ 1 ] = ac * f + bd;
  8066. te[ 5 ] = a * e;
  8067. te[ 9 ] = ad * f - bc;
  8068. te[ 2 ] = bc * f - ad;
  8069. te[ 6 ] = b * e;
  8070. te[ 10 ] = bd * f + ac;
  8071. }
  8072. // bottom row
  8073. te[ 3 ] = 0;
  8074. te[ 7 ] = 0;
  8075. te[ 11 ] = 0;
  8076. // last column
  8077. te[ 12 ] = 0;
  8078. te[ 13 ] = 0;
  8079. te[ 14 ] = 0;
  8080. te[ 15 ] = 1;
  8081. return this;
  8082. },
  8083. makeRotationFromQuaternion: function ( q ) {
  8084. return this.compose( _zero, q, _one );
  8085. },
  8086. lookAt: function ( eye, target, up ) {
  8087. var te = this.elements;
  8088. _z.subVectors( eye, target );
  8089. if ( _z.lengthSq() === 0 ) {
  8090. // eye and target are in the same position
  8091. _z.z = 1;
  8092. }
  8093. _z.normalize();
  8094. _x.crossVectors( up, _z );
  8095. if ( _x.lengthSq() === 0 ) {
  8096. // up and z are parallel
  8097. if ( Math.abs( up.z ) === 1 ) {
  8098. _z.x += 0.0001;
  8099. } else {
  8100. _z.z += 0.0001;
  8101. }
  8102. _z.normalize();
  8103. _x.crossVectors( up, _z );
  8104. }
  8105. _x.normalize();
  8106. _y.crossVectors( _z, _x );
  8107. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8108. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8109. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8110. return this;
  8111. },
  8112. multiply: function ( m, n ) {
  8113. if ( n !== undefined ) {
  8114. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  8115. return this.multiplyMatrices( m, n );
  8116. }
  8117. return this.multiplyMatrices( this, m );
  8118. },
  8119. premultiply: function ( m ) {
  8120. return this.multiplyMatrices( m, this );
  8121. },
  8122. multiplyMatrices: function ( a, b ) {
  8123. var ae = a.elements;
  8124. var be = b.elements;
  8125. var te = this.elements;
  8126. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8127. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8128. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8129. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8130. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8131. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8132. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8133. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8134. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8135. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8136. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8137. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8138. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8139. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8140. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8141. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8142. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8143. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8144. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8145. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8146. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8147. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8148. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8149. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8150. return this;
  8151. },
  8152. multiplyScalar: function ( s ) {
  8153. var te = this.elements;
  8154. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8155. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8156. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8157. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8158. return this;
  8159. },
  8160. applyToBufferAttribute: function ( attribute ) {
  8161. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  8162. _v1.x = attribute.getX( i );
  8163. _v1.y = attribute.getY( i );
  8164. _v1.z = attribute.getZ( i );
  8165. _v1.applyMatrix4( this );
  8166. attribute.setXYZ( i, _v1.x, _v1.y, _v1.z );
  8167. }
  8168. return attribute;
  8169. },
  8170. determinant: function () {
  8171. var te = this.elements;
  8172. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8173. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8174. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8175. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8176. //TODO: make this more efficient
  8177. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  8178. return (
  8179. n41 * (
  8180. + n14 * n23 * n32
  8181. - n13 * n24 * n32
  8182. - n14 * n22 * n33
  8183. + n12 * n24 * n33
  8184. + n13 * n22 * n34
  8185. - n12 * n23 * n34
  8186. ) +
  8187. n42 * (
  8188. + n11 * n23 * n34
  8189. - n11 * n24 * n33
  8190. + n14 * n21 * n33
  8191. - n13 * n21 * n34
  8192. + n13 * n24 * n31
  8193. - n14 * n23 * n31
  8194. ) +
  8195. n43 * (
  8196. + n11 * n24 * n32
  8197. - n11 * n22 * n34
  8198. - n14 * n21 * n32
  8199. + n12 * n21 * n34
  8200. + n14 * n22 * n31
  8201. - n12 * n24 * n31
  8202. ) +
  8203. n44 * (
  8204. - n13 * n22 * n31
  8205. - n11 * n23 * n32
  8206. + n11 * n22 * n33
  8207. + n13 * n21 * n32
  8208. - n12 * n21 * n33
  8209. + n12 * n23 * n31
  8210. )
  8211. );
  8212. },
  8213. transpose: function () {
  8214. var te = this.elements;
  8215. var tmp;
  8216. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8217. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8218. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8219. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8220. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8221. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8222. return this;
  8223. },
  8224. setPosition: function ( x, y, z ) {
  8225. var te = this.elements;
  8226. if ( x.isVector3 ) {
  8227. te[ 12 ] = x.x;
  8228. te[ 13 ] = x.y;
  8229. te[ 14 ] = x.z;
  8230. } else {
  8231. te[ 12 ] = x;
  8232. te[ 13 ] = y;
  8233. te[ 14 ] = z;
  8234. }
  8235. return this;
  8236. },
  8237. getInverse: function ( m, throwOnDegenerate ) {
  8238. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  8239. var te = this.elements,
  8240. me = m.elements,
  8241. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  8242. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  8243. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  8244. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  8245. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  8246. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  8247. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  8248. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  8249. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  8250. if ( det === 0 ) {
  8251. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  8252. if ( throwOnDegenerate === true ) {
  8253. throw new Error( msg );
  8254. } else {
  8255. console.warn( msg );
  8256. }
  8257. return this.identity();
  8258. }
  8259. var detInv = 1 / det;
  8260. te[ 0 ] = t11 * detInv;
  8261. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  8262. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  8263. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  8264. te[ 4 ] = t12 * detInv;
  8265. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  8266. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  8267. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  8268. te[ 8 ] = t13 * detInv;
  8269. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  8270. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  8271. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  8272. te[ 12 ] = t14 * detInv;
  8273. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  8274. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  8275. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  8276. return this;
  8277. },
  8278. scale: function ( v ) {
  8279. var te = this.elements;
  8280. var x = v.x, y = v.y, z = v.z;
  8281. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8282. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8283. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8284. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8285. return this;
  8286. },
  8287. getMaxScaleOnAxis: function () {
  8288. var te = this.elements;
  8289. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8290. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8291. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8292. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8293. },
  8294. makeTranslation: function ( x, y, z ) {
  8295. this.set(
  8296. 1, 0, 0, x,
  8297. 0, 1, 0, y,
  8298. 0, 0, 1, z,
  8299. 0, 0, 0, 1
  8300. );
  8301. return this;
  8302. },
  8303. makeRotationX: function ( theta ) {
  8304. var c = Math.cos( theta ), s = Math.sin( theta );
  8305. this.set(
  8306. 1, 0, 0, 0,
  8307. 0, c, - s, 0,
  8308. 0, s, c, 0,
  8309. 0, 0, 0, 1
  8310. );
  8311. return this;
  8312. },
  8313. makeRotationY: function ( theta ) {
  8314. var c = Math.cos( theta ), s = Math.sin( theta );
  8315. this.set(
  8316. c, 0, s, 0,
  8317. 0, 1, 0, 0,
  8318. - s, 0, c, 0,
  8319. 0, 0, 0, 1
  8320. );
  8321. return this;
  8322. },
  8323. makeRotationZ: function ( theta ) {
  8324. var c = Math.cos( theta ), s = Math.sin( theta );
  8325. this.set(
  8326. c, - s, 0, 0,
  8327. s, c, 0, 0,
  8328. 0, 0, 1, 0,
  8329. 0, 0, 0, 1
  8330. );
  8331. return this;
  8332. },
  8333. makeRotationAxis: function ( axis, angle ) {
  8334. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8335. var c = Math.cos( angle );
  8336. var s = Math.sin( angle );
  8337. var t = 1 - c;
  8338. var x = axis.x, y = axis.y, z = axis.z;
  8339. var tx = t * x, ty = t * y;
  8340. this.set(
  8341. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8342. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8343. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8344. 0, 0, 0, 1
  8345. );
  8346. return this;
  8347. },
  8348. makeScale: function ( x, y, z ) {
  8349. this.set(
  8350. x, 0, 0, 0,
  8351. 0, y, 0, 0,
  8352. 0, 0, z, 0,
  8353. 0, 0, 0, 1
  8354. );
  8355. return this;
  8356. },
  8357. makeShear: function ( x, y, z ) {
  8358. this.set(
  8359. 1, y, z, 0,
  8360. x, 1, z, 0,
  8361. x, y, 1, 0,
  8362. 0, 0, 0, 1
  8363. );
  8364. return this;
  8365. },
  8366. compose: function ( position, quaternion, scale ) {
  8367. var te = this.elements;
  8368. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8369. var x2 = x + x, y2 = y + y, z2 = z + z;
  8370. var xx = x * x2, xy = x * y2, xz = x * z2;
  8371. var yy = y * y2, yz = y * z2, zz = z * z2;
  8372. var wx = w * x2, wy = w * y2, wz = w * z2;
  8373. var sx = scale.x, sy = scale.y, sz = scale.z;
  8374. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8375. te[ 1 ] = ( xy + wz ) * sx;
  8376. te[ 2 ] = ( xz - wy ) * sx;
  8377. te[ 3 ] = 0;
  8378. te[ 4 ] = ( xy - wz ) * sy;
  8379. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8380. te[ 6 ] = ( yz + wx ) * sy;
  8381. te[ 7 ] = 0;
  8382. te[ 8 ] = ( xz + wy ) * sz;
  8383. te[ 9 ] = ( yz - wx ) * sz;
  8384. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8385. te[ 11 ] = 0;
  8386. te[ 12 ] = position.x;
  8387. te[ 13 ] = position.y;
  8388. te[ 14 ] = position.z;
  8389. te[ 15 ] = 1;
  8390. return this;
  8391. },
  8392. decompose: function ( position, quaternion, scale ) {
  8393. var te = this.elements;
  8394. var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8395. var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8396. var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8397. // if determine is negative, we need to invert one scale
  8398. var det = this.determinant();
  8399. if ( det < 0 ) { sx = - sx; }
  8400. position.x = te[ 12 ];
  8401. position.y = te[ 13 ];
  8402. position.z = te[ 14 ];
  8403. // scale the rotation part
  8404. _m1.copy( this );
  8405. var invSX = 1 / sx;
  8406. var invSY = 1 / sy;
  8407. var invSZ = 1 / sz;
  8408. _m1.elements[ 0 ] *= invSX;
  8409. _m1.elements[ 1 ] *= invSX;
  8410. _m1.elements[ 2 ] *= invSX;
  8411. _m1.elements[ 4 ] *= invSY;
  8412. _m1.elements[ 5 ] *= invSY;
  8413. _m1.elements[ 6 ] *= invSY;
  8414. _m1.elements[ 8 ] *= invSZ;
  8415. _m1.elements[ 9 ] *= invSZ;
  8416. _m1.elements[ 10 ] *= invSZ;
  8417. quaternion.setFromRotationMatrix( _m1 );
  8418. scale.x = sx;
  8419. scale.y = sy;
  8420. scale.z = sz;
  8421. return this;
  8422. },
  8423. makePerspective: function ( left, right, top, bottom, near, far ) {
  8424. if ( far === undefined ) {
  8425. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  8426. }
  8427. var te = this.elements;
  8428. var x = 2 * near / ( right - left );
  8429. var y = 2 * near / ( top - bottom );
  8430. var a = ( right + left ) / ( right - left );
  8431. var b = ( top + bottom ) / ( top - bottom );
  8432. var c = - ( far + near ) / ( far - near );
  8433. var d = - 2 * far * near / ( far - near );
  8434. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8435. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8436. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8437. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  8438. return this;
  8439. },
  8440. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  8441. var te = this.elements;
  8442. var w = 1.0 / ( right - left );
  8443. var h = 1.0 / ( top - bottom );
  8444. var p = 1.0 / ( far - near );
  8445. var x = ( right + left ) * w;
  8446. var y = ( top + bottom ) * h;
  8447. var z = ( far + near ) * p;
  8448. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  8449. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  8450. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  8451. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8452. return this;
  8453. },
  8454. equals: function ( matrix ) {
  8455. var te = this.elements;
  8456. var me = matrix.elements;
  8457. for ( var i = 0; i < 16; i ++ ) {
  8458. if ( te[ i ] !== me[ i ] ) { return false; }
  8459. }
  8460. return true;
  8461. },
  8462. fromArray: function ( array, offset ) {
  8463. if ( offset === undefined ) { offset = 0; }
  8464. for ( var i = 0; i < 16; i ++ ) {
  8465. this.elements[ i ] = array[ i + offset ];
  8466. }
  8467. return this;
  8468. },
  8469. toArray: function ( array, offset ) {
  8470. if ( array === undefined ) { array = []; }
  8471. if ( offset === undefined ) { offset = 0; }
  8472. var te = this.elements;
  8473. array[ offset ] = te[ 0 ];
  8474. array[ offset + 1 ] = te[ 1 ];
  8475. array[ offset + 2 ] = te[ 2 ];
  8476. array[ offset + 3 ] = te[ 3 ];
  8477. array[ offset + 4 ] = te[ 4 ];
  8478. array[ offset + 5 ] = te[ 5 ];
  8479. array[ offset + 6 ] = te[ 6 ];
  8480. array[ offset + 7 ] = te[ 7 ];
  8481. array[ offset + 8 ] = te[ 8 ];
  8482. array[ offset + 9 ] = te[ 9 ];
  8483. array[ offset + 10 ] = te[ 10 ];
  8484. array[ offset + 11 ] = te[ 11 ];
  8485. array[ offset + 12 ] = te[ 12 ];
  8486. array[ offset + 13 ] = te[ 13 ];
  8487. array[ offset + 14 ] = te[ 14 ];
  8488. array[ offset + 15 ] = te[ 15 ];
  8489. return array;
  8490. }
  8491. } );
  8492. /**
  8493. * @author mrdoob / http://mrdoob.com/
  8494. * @author WestLangley / http://github.com/WestLangley
  8495. * @author bhouston / http://clara.io
  8496. */
  8497. var _matrix = new Matrix4();
  8498. var _quaternion$1 = new Quaternion();
  8499. function Euler( x, y, z, order ) {
  8500. this._x = x || 0;
  8501. this._y = y || 0;
  8502. this._z = z || 0;
  8503. this._order = order || Euler.DefaultOrder;
  8504. }
  8505. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  8506. Euler.DefaultOrder = 'XYZ';
  8507. Object.defineProperties( Euler.prototype, {
  8508. x: {
  8509. get: function () {
  8510. return this._x;
  8511. },
  8512. set: function ( value ) {
  8513. this._x = value;
  8514. this._onChangeCallback();
  8515. }
  8516. },
  8517. y: {
  8518. get: function () {
  8519. return this._y;
  8520. },
  8521. set: function ( value ) {
  8522. this._y = value;
  8523. this._onChangeCallback();
  8524. }
  8525. },
  8526. z: {
  8527. get: function () {
  8528. return this._z;
  8529. },
  8530. set: function ( value ) {
  8531. this._z = value;
  8532. this._onChangeCallback();
  8533. }
  8534. },
  8535. order: {
  8536. get: function () {
  8537. return this._order;
  8538. },
  8539. set: function ( value ) {
  8540. this._order = value;
  8541. this._onChangeCallback();
  8542. }
  8543. }
  8544. } );
  8545. Object.assign( Euler.prototype, {
  8546. isEuler: true,
  8547. set: function ( x, y, z, order ) {
  8548. this._x = x;
  8549. this._y = y;
  8550. this._z = z;
  8551. this._order = order || this._order;
  8552. this._onChangeCallback();
  8553. return this;
  8554. },
  8555. clone: function () {
  8556. return new this.constructor( this._x, this._y, this._z, this._order );
  8557. },
  8558. copy: function ( euler ) {
  8559. this._x = euler._x;
  8560. this._y = euler._y;
  8561. this._z = euler._z;
  8562. this._order = euler._order;
  8563. this._onChangeCallback();
  8564. return this;
  8565. },
  8566. setFromRotationMatrix: function ( m, order, update ) {
  8567. var clamp = _Math.clamp;
  8568. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8569. var te = m.elements;
  8570. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8571. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8572. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8573. order = order || this._order;
  8574. if ( order === 'XYZ' ) {
  8575. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  8576. if ( Math.abs( m13 ) < 0.9999999 ) {
  8577. this._x = Math.atan2( - m23, m33 );
  8578. this._z = Math.atan2( - m12, m11 );
  8579. } else {
  8580. this._x = Math.atan2( m32, m22 );
  8581. this._z = 0;
  8582. }
  8583. } else if ( order === 'YXZ' ) {
  8584. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  8585. if ( Math.abs( m23 ) < 0.9999999 ) {
  8586. this._y = Math.atan2( m13, m33 );
  8587. this._z = Math.atan2( m21, m22 );
  8588. } else {
  8589. this._y = Math.atan2( - m31, m11 );
  8590. this._z = 0;
  8591. }
  8592. } else if ( order === 'ZXY' ) {
  8593. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  8594. if ( Math.abs( m32 ) < 0.9999999 ) {
  8595. this._y = Math.atan2( - m31, m33 );
  8596. this._z = Math.atan2( - m12, m22 );
  8597. } else {
  8598. this._y = 0;
  8599. this._z = Math.atan2( m21, m11 );
  8600. }
  8601. } else if ( order === 'ZYX' ) {
  8602. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  8603. if ( Math.abs( m31 ) < 0.9999999 ) {
  8604. this._x = Math.atan2( m32, m33 );
  8605. this._z = Math.atan2( m21, m11 );
  8606. } else {
  8607. this._x = 0;
  8608. this._z = Math.atan2( - m12, m22 );
  8609. }
  8610. } else if ( order === 'YZX' ) {
  8611. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  8612. if ( Math.abs( m21 ) < 0.9999999 ) {
  8613. this._x = Math.atan2( - m23, m22 );
  8614. this._y = Math.atan2( - m31, m11 );
  8615. } else {
  8616. this._x = 0;
  8617. this._y = Math.atan2( m13, m33 );
  8618. }
  8619. } else if ( order === 'XZY' ) {
  8620. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  8621. if ( Math.abs( m12 ) < 0.9999999 ) {
  8622. this._x = Math.atan2( m32, m22 );
  8623. this._y = Math.atan2( m13, m11 );
  8624. } else {
  8625. this._x = Math.atan2( - m23, m33 );
  8626. this._y = 0;
  8627. }
  8628. } else {
  8629. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  8630. }
  8631. this._order = order;
  8632. if ( update !== false ) { this._onChangeCallback(); }
  8633. return this;
  8634. },
  8635. setFromQuaternion: function ( q, order, update ) {
  8636. _matrix.makeRotationFromQuaternion( q );
  8637. return this.setFromRotationMatrix( _matrix, order, update );
  8638. },
  8639. setFromVector3: function ( v, order ) {
  8640. return this.set( v.x, v.y, v.z, order || this._order );
  8641. },
  8642. reorder: function ( newOrder ) {
  8643. // WARNING: this discards revolution information -bhouston
  8644. _quaternion$1.setFromEuler( this );
  8645. return this.setFromQuaternion( _quaternion$1, newOrder );
  8646. },
  8647. equals: function ( euler ) {
  8648. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8649. },
  8650. fromArray: function ( array ) {
  8651. this._x = array[ 0 ];
  8652. this._y = array[ 1 ];
  8653. this._z = array[ 2 ];
  8654. if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; }
  8655. this._onChangeCallback();
  8656. return this;
  8657. },
  8658. toArray: function ( array, offset ) {
  8659. if ( array === undefined ) { array = []; }
  8660. if ( offset === undefined ) { offset = 0; }
  8661. array[ offset ] = this._x;
  8662. array[ offset + 1 ] = this._y;
  8663. array[ offset + 2 ] = this._z;
  8664. array[ offset + 3 ] = this._order;
  8665. return array;
  8666. },
  8667. toVector3: function ( optionalResult ) {
  8668. if ( optionalResult ) {
  8669. return optionalResult.set( this._x, this._y, this._z );
  8670. } else {
  8671. return new Vector3( this._x, this._y, this._z );
  8672. }
  8673. },
  8674. _onChange: function ( callback ) {
  8675. this._onChangeCallback = callback;
  8676. return this;
  8677. },
  8678. _onChangeCallback: function () {}
  8679. } );
  8680. /**
  8681. * @author mrdoob / http://mrdoob.com/
  8682. */
  8683. function Layers() {
  8684. this.mask = 1 | 0;
  8685. }
  8686. Object.assign( Layers.prototype, {
  8687. set: function ( channel ) {
  8688. this.mask = 1 << channel | 0;
  8689. },
  8690. enable: function ( channel ) {
  8691. this.mask |= 1 << channel | 0;
  8692. },
  8693. enableAll: function () {
  8694. this.mask = 0xffffffff | 0;
  8695. },
  8696. toggle: function ( channel ) {
  8697. this.mask ^= 1 << channel | 0;
  8698. },
  8699. disable: function ( channel ) {
  8700. this.mask &= ~ ( 1 << channel | 0 );
  8701. },
  8702. disableAll: function () {
  8703. this.mask = 0;
  8704. },
  8705. test: function ( layers ) {
  8706. return ( this.mask & layers.mask ) !== 0;
  8707. }
  8708. } );
  8709. var _object3DId = 0;
  8710. var _v1$1 = new Vector3();
  8711. var _q1 = new Quaternion();
  8712. var _m1$1 = new Matrix4();
  8713. var _target = new Vector3();
  8714. var _position = new Vector3();
  8715. var _scale = new Vector3();
  8716. var _quaternion$2 = new Quaternion();
  8717. var _xAxis = new Vector3( 1, 0, 0 );
  8718. var _yAxis = new Vector3( 0, 1, 0 );
  8719. var _zAxis = new Vector3( 0, 0, 1 );
  8720. var _addedEvent = { type: 'added' };
  8721. var _removedEvent = { type: 'removed' };
  8722. /**
  8723. * @author mrdoob / http://mrdoob.com/
  8724. * @author mikael emtinger / http://gomo.se/
  8725. * @author alteredq / http://alteredqualia.com/
  8726. * @author WestLangley / http://github.com/WestLangley
  8727. * @author elephantatwork / www.elephantatwork.ch
  8728. */
  8729. function Object3D() {
  8730. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  8731. this.uuid = _Math.generateUUID();
  8732. this.name = '';
  8733. this.type = 'Object3D';
  8734. this.parent = null;
  8735. this.children = [];
  8736. this.up = Object3D.DefaultUp.clone();
  8737. var position = new Vector3();
  8738. var rotation = new Euler();
  8739. var quaternion = new Quaternion();
  8740. var scale = new Vector3( 1, 1, 1 );
  8741. function onRotationChange() {
  8742. quaternion.setFromEuler( rotation, false );
  8743. }
  8744. function onQuaternionChange() {
  8745. rotation.setFromQuaternion( quaternion, undefined, false );
  8746. }
  8747. rotation._onChange( onRotationChange );
  8748. quaternion._onChange( onQuaternionChange );
  8749. Object.defineProperties( this, {
  8750. position: {
  8751. configurable: true,
  8752. enumerable: true,
  8753. value: position
  8754. },
  8755. rotation: {
  8756. configurable: true,
  8757. enumerable: true,
  8758. value: rotation
  8759. },
  8760. quaternion: {
  8761. configurable: true,
  8762. enumerable: true,
  8763. value: quaternion
  8764. },
  8765. scale: {
  8766. configurable: true,
  8767. enumerable: true,
  8768. value: scale
  8769. },
  8770. modelViewMatrix: {
  8771. value: new Matrix4()
  8772. },
  8773. normalMatrix: {
  8774. value: new Matrix3()
  8775. }
  8776. } );
  8777. this.matrix = new Matrix4();
  8778. this.matrixWorld = new Matrix4();
  8779. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  8780. this.matrixWorldNeedsUpdate = false;
  8781. this.layers = new Layers();
  8782. this.visible = true;
  8783. this.castShadow = false;
  8784. this.receiveShadow = false;
  8785. this.frustumCulled = true;
  8786. this.renderOrder = 0;
  8787. this.userData = {};
  8788. }
  8789. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  8790. Object3D.DefaultMatrixAutoUpdate = true;
  8791. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  8792. constructor: Object3D,
  8793. isObject3D: true,
  8794. onBeforeRender: function () {},
  8795. onAfterRender: function () {},
  8796. applyMatrix: function ( matrix ) {
  8797. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  8798. this.matrix.premultiply( matrix );
  8799. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8800. },
  8801. applyQuaternion: function ( q ) {
  8802. this.quaternion.premultiply( q );
  8803. return this;
  8804. },
  8805. setRotationFromAxisAngle: function ( axis, angle ) {
  8806. // assumes axis is normalized
  8807. this.quaternion.setFromAxisAngle( axis, angle );
  8808. },
  8809. setRotationFromEuler: function ( euler ) {
  8810. this.quaternion.setFromEuler( euler, true );
  8811. },
  8812. setRotationFromMatrix: function ( m ) {
  8813. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8814. this.quaternion.setFromRotationMatrix( m );
  8815. },
  8816. setRotationFromQuaternion: function ( q ) {
  8817. // assumes q is normalized
  8818. this.quaternion.copy( q );
  8819. },
  8820. rotateOnAxis: function ( axis, angle ) {
  8821. // rotate object on axis in object space
  8822. // axis is assumed to be normalized
  8823. _q1.setFromAxisAngle( axis, angle );
  8824. this.quaternion.multiply( _q1 );
  8825. return this;
  8826. },
  8827. rotateOnWorldAxis: function ( axis, angle ) {
  8828. // rotate object on axis in world space
  8829. // axis is assumed to be normalized
  8830. // method assumes no rotated parent
  8831. _q1.setFromAxisAngle( axis, angle );
  8832. this.quaternion.premultiply( _q1 );
  8833. return this;
  8834. },
  8835. rotateX: function ( angle ) {
  8836. return this.rotateOnAxis( _xAxis, angle );
  8837. },
  8838. rotateY: function ( angle ) {
  8839. return this.rotateOnAxis( _yAxis, angle );
  8840. },
  8841. rotateZ: function ( angle ) {
  8842. return this.rotateOnAxis( _zAxis, angle );
  8843. },
  8844. translateOnAxis: function ( axis, distance ) {
  8845. // translate object by distance along axis in object space
  8846. // axis is assumed to be normalized
  8847. _v1$1.copy( axis ).applyQuaternion( this.quaternion );
  8848. this.position.add( _v1$1.multiplyScalar( distance ) );
  8849. return this;
  8850. },
  8851. translateX: function ( distance ) {
  8852. return this.translateOnAxis( _xAxis, distance );
  8853. },
  8854. translateY: function ( distance ) {
  8855. return this.translateOnAxis( _yAxis, distance );
  8856. },
  8857. translateZ: function ( distance ) {
  8858. return this.translateOnAxis( _zAxis, distance );
  8859. },
  8860. localToWorld: function ( vector ) {
  8861. return vector.applyMatrix4( this.matrixWorld );
  8862. },
  8863. worldToLocal: function ( vector ) {
  8864. return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );
  8865. },
  8866. lookAt: function ( x, y, z ) {
  8867. // This method does not support objects having non-uniformly-scaled parent(s)
  8868. if ( x.isVector3 ) {
  8869. _target.copy( x );
  8870. } else {
  8871. _target.set( x, y, z );
  8872. }
  8873. var parent = this.parent;
  8874. this.updateWorldMatrix( true, false );
  8875. _position.setFromMatrixPosition( this.matrixWorld );
  8876. if ( this.isCamera || this.isLight ) {
  8877. _m1$1.lookAt( _position, _target, this.up );
  8878. } else {
  8879. _m1$1.lookAt( _target, _position, this.up );
  8880. }
  8881. this.quaternion.setFromRotationMatrix( _m1$1 );
  8882. if ( parent ) {
  8883. _m1$1.extractRotation( parent.matrixWorld );
  8884. _q1.setFromRotationMatrix( _m1$1 );
  8885. this.quaternion.premultiply( _q1.inverse() );
  8886. }
  8887. },
  8888. add: function ( object ) {
  8889. if ( arguments.length > 1 ) {
  8890. for ( var i = 0; i < arguments.length; i ++ ) {
  8891. this.add( arguments[ i ] );
  8892. }
  8893. return this;
  8894. }
  8895. if ( object === this ) {
  8896. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8897. return this;
  8898. }
  8899. if ( ( object && object.isObject3D ) ) {
  8900. if ( object.parent !== null ) {
  8901. object.parent.remove( object );
  8902. }
  8903. object.parent = this;
  8904. this.children.push( object );
  8905. object.dispatchEvent( _addedEvent );
  8906. } else {
  8907. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8908. }
  8909. return this;
  8910. },
  8911. remove: function ( object ) {
  8912. if ( arguments.length > 1 ) {
  8913. for ( var i = 0; i < arguments.length; i ++ ) {
  8914. this.remove( arguments[ i ] );
  8915. }
  8916. return this;
  8917. }
  8918. var index = this.children.indexOf( object );
  8919. if ( index !== - 1 ) {
  8920. object.parent = null;
  8921. this.children.splice( index, 1 );
  8922. object.dispatchEvent( _removedEvent );
  8923. }
  8924. return this;
  8925. },
  8926. attach: function ( object ) {
  8927. // adds object as a child of this, while maintaining the object's world transform
  8928. this.updateWorldMatrix( true, false );
  8929. _m1$1.getInverse( this.matrixWorld );
  8930. if ( object.parent !== null ) {
  8931. object.parent.updateWorldMatrix( true, false );
  8932. _m1$1.multiply( object.parent.matrixWorld );
  8933. }
  8934. object.applyMatrix( _m1$1 );
  8935. object.updateWorldMatrix( false, false );
  8936. this.add( object );
  8937. return this;
  8938. },
  8939. getObjectById: function ( id ) {
  8940. return this.getObjectByProperty( 'id', id );
  8941. },
  8942. getObjectByName: function ( name ) {
  8943. return this.getObjectByProperty( 'name', name );
  8944. },
  8945. getObjectByProperty: function ( name, value ) {
  8946. if ( this[ name ] === value ) { return this; }
  8947. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8948. var child = this.children[ i ];
  8949. var object = child.getObjectByProperty( name, value );
  8950. if ( object !== undefined ) {
  8951. return object;
  8952. }
  8953. }
  8954. return undefined;
  8955. },
  8956. getWorldPosition: function ( target ) {
  8957. if ( target === undefined ) {
  8958. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  8959. target = new Vector3();
  8960. }
  8961. this.updateMatrixWorld( true );
  8962. return target.setFromMatrixPosition( this.matrixWorld );
  8963. },
  8964. getWorldQuaternion: function ( target ) {
  8965. if ( target === undefined ) {
  8966. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  8967. target = new Quaternion();
  8968. }
  8969. this.updateMatrixWorld( true );
  8970. this.matrixWorld.decompose( _position, target, _scale );
  8971. return target;
  8972. },
  8973. getWorldScale: function ( target ) {
  8974. if ( target === undefined ) {
  8975. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  8976. target = new Vector3();
  8977. }
  8978. this.updateMatrixWorld( true );
  8979. this.matrixWorld.decompose( _position, _quaternion$2, target );
  8980. return target;
  8981. },
  8982. getWorldDirection: function ( target ) {
  8983. if ( target === undefined ) {
  8984. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  8985. target = new Vector3();
  8986. }
  8987. this.updateMatrixWorld( true );
  8988. var e = this.matrixWorld.elements;
  8989. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  8990. },
  8991. raycast: function () {},
  8992. traverse: function ( callback ) {
  8993. callback( this );
  8994. var children = this.children;
  8995. for ( var i = 0, l = children.length; i < l; i ++ ) {
  8996. children[ i ].traverse( callback );
  8997. }
  8998. },
  8999. traverseVisible: function ( callback ) {
  9000. if ( this.visible === false ) { return; }
  9001. callback( this );
  9002. var children = this.children;
  9003. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9004. children[ i ].traverseVisible( callback );
  9005. }
  9006. },
  9007. traverseAncestors: function ( callback ) {
  9008. var parent = this.parent;
  9009. if ( parent !== null ) {
  9010. callback( parent );
  9011. parent.traverseAncestors( callback );
  9012. }
  9013. },
  9014. updateMatrix: function () {
  9015. this.matrix.compose( this.position, this.quaternion, this.scale );
  9016. this.matrixWorldNeedsUpdate = true;
  9017. },
  9018. updateMatrixWorld: function ( force ) {
  9019. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9020. if ( this.matrixWorldNeedsUpdate || force ) {
  9021. if ( this.parent === null ) {
  9022. this.matrixWorld.copy( this.matrix );
  9023. } else {
  9024. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9025. }
  9026. this.matrixWorldNeedsUpdate = false;
  9027. force = true;
  9028. }
  9029. // update children
  9030. var children = this.children;
  9031. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9032. children[ i ].updateMatrixWorld( force );
  9033. }
  9034. },
  9035. updateWorldMatrix: function ( updateParents, updateChildren ) {
  9036. var parent = this.parent;
  9037. if ( updateParents === true && parent !== null ) {
  9038. parent.updateWorldMatrix( true, false );
  9039. }
  9040. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9041. if ( this.parent === null ) {
  9042. this.matrixWorld.copy( this.matrix );
  9043. } else {
  9044. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9045. }
  9046. // update children
  9047. if ( updateChildren === true ) {
  9048. var children = this.children;
  9049. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9050. children[ i ].updateWorldMatrix( false, true );
  9051. }
  9052. }
  9053. },
  9054. toJSON: function ( meta ) {
  9055. // meta is a string when called from JSON.stringify
  9056. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9057. var output = {};
  9058. // meta is a hash used to collect geometries, materials.
  9059. // not providing it implies that this is the root object
  9060. // being serialized.
  9061. if ( isRootObject ) {
  9062. // initialize meta obj
  9063. meta = {
  9064. geometries: {},
  9065. materials: {},
  9066. textures: {},
  9067. images: {},
  9068. shapes: {}
  9069. };
  9070. output.metadata = {
  9071. version: 4.5,
  9072. type: 'Object',
  9073. generator: 'Object3D.toJSON'
  9074. };
  9075. }
  9076. // standard Object3D serialization
  9077. var object = {};
  9078. object.uuid = this.uuid;
  9079. object.type = this.type;
  9080. if ( this.name !== '' ) { object.name = this.name; }
  9081. if ( this.castShadow === true ) { object.castShadow = true; }
  9082. if ( this.receiveShadow === true ) { object.receiveShadow = true; }
  9083. if ( this.visible === false ) { object.visible = false; }
  9084. if ( this.frustumCulled === false ) { object.frustumCulled = false; }
  9085. if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; }
  9086. if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; }
  9087. object.layers = this.layers.mask;
  9088. object.matrix = this.matrix.toArray();
  9089. if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; }
  9090. // object specific properties
  9091. if ( this.isMesh && this.drawMode !== TrianglesDrawMode ) { object.drawMode = this.drawMode; }
  9092. //
  9093. function serialize( library, element ) {
  9094. if ( library[ element.uuid ] === undefined ) {
  9095. library[ element.uuid ] = element.toJSON( meta );
  9096. }
  9097. return element.uuid;
  9098. }
  9099. if ( this.isMesh || this.isLine || this.isPoints ) {
  9100. object.geometry = serialize( meta.geometries, this.geometry );
  9101. var parameters = this.geometry.parameters;
  9102. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9103. var shapes = parameters.shapes;
  9104. if ( Array.isArray( shapes ) ) {
  9105. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9106. var shape = shapes[ i ];
  9107. serialize( meta.shapes, shape );
  9108. }
  9109. } else {
  9110. serialize( meta.shapes, shapes );
  9111. }
  9112. }
  9113. }
  9114. if ( this.material !== undefined ) {
  9115. if ( Array.isArray( this.material ) ) {
  9116. var uuids = [];
  9117. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  9118. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9119. }
  9120. object.material = uuids;
  9121. } else {
  9122. object.material = serialize( meta.materials, this.material );
  9123. }
  9124. }
  9125. //
  9126. if ( this.children.length > 0 ) {
  9127. object.children = [];
  9128. for ( var i = 0; i < this.children.length; i ++ ) {
  9129. object.children.push( this.children[ i ].toJSON( meta ).object );
  9130. }
  9131. }
  9132. if ( isRootObject ) {
  9133. var geometries = extractFromCache( meta.geometries );
  9134. var materials = extractFromCache( meta.materials );
  9135. var textures = extractFromCache( meta.textures );
  9136. var images = extractFromCache( meta.images );
  9137. var shapes = extractFromCache( meta.shapes );
  9138. if ( geometries.length > 0 ) { output.geometries = geometries; }
  9139. if ( materials.length > 0 ) { output.materials = materials; }
  9140. if ( textures.length > 0 ) { output.textures = textures; }
  9141. if ( images.length > 0 ) { output.images = images; }
  9142. if ( shapes.length > 0 ) { output.shapes = shapes; }
  9143. }
  9144. output.object = object;
  9145. return output;
  9146. // extract data from the cache hash
  9147. // remove metadata on each item
  9148. // and return as array
  9149. function extractFromCache( cache ) {
  9150. var values = [];
  9151. for ( var key in cache ) {
  9152. var data = cache[ key ];
  9153. delete data.metadata;
  9154. values.push( data );
  9155. }
  9156. return values;
  9157. }
  9158. },
  9159. clone: function ( recursive ) {
  9160. return new this.constructor().copy( this, recursive );
  9161. },
  9162. copy: function ( source, recursive ) {
  9163. if ( recursive === undefined ) { recursive = true; }
  9164. this.name = source.name;
  9165. this.up.copy( source.up );
  9166. this.position.copy( source.position );
  9167. this.quaternion.copy( source.quaternion );
  9168. this.scale.copy( source.scale );
  9169. this.matrix.copy( source.matrix );
  9170. this.matrixWorld.copy( source.matrixWorld );
  9171. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9172. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9173. this.layers.mask = source.layers.mask;
  9174. this.visible = source.visible;
  9175. this.castShadow = source.castShadow;
  9176. this.receiveShadow = source.receiveShadow;
  9177. this.frustumCulled = source.frustumCulled;
  9178. this.renderOrder = source.renderOrder;
  9179. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9180. if ( recursive === true ) {
  9181. for ( var i = 0; i < source.children.length; i ++ ) {
  9182. var child = source.children[ i ];
  9183. this.add( child.clone() );
  9184. }
  9185. }
  9186. return this;
  9187. }
  9188. } );
  9189. /**
  9190. * @author mrdoob / http://mrdoob.com/
  9191. */
  9192. function Scene() {
  9193. Object3D.call( this );
  9194. this.type = 'Scene';
  9195. this.background = null;
  9196. this.fog = null;
  9197. this.overrideMaterial = null;
  9198. this.autoUpdate = true; // checked by the renderer
  9199. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  9200. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  9201. }
  9202. }
  9203. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9204. constructor: Scene,
  9205. isScene: true,
  9206. copy: function ( source, recursive ) {
  9207. Object3D.prototype.copy.call( this, source, recursive );
  9208. if ( source.background !== null ) { this.background = source.background.clone(); }
  9209. if ( source.fog !== null ) { this.fog = source.fog.clone(); }
  9210. if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); }
  9211. this.autoUpdate = source.autoUpdate;
  9212. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9213. return this;
  9214. },
  9215. toJSON: function ( meta ) {
  9216. var data = Object3D.prototype.toJSON.call( this, meta );
  9217. if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); }
  9218. if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); }
  9219. return data;
  9220. },
  9221. dispose: function () {
  9222. this.dispatchEvent( { type: 'dispose' } );
  9223. }
  9224. } );
  9225. var _points = [
  9226. new Vector3(),
  9227. new Vector3(),
  9228. new Vector3(),
  9229. new Vector3(),
  9230. new Vector3(),
  9231. new Vector3(),
  9232. new Vector3(),
  9233. new Vector3()
  9234. ];
  9235. var _vector$2 = new Vector3();
  9236. // triangle centered vertices
  9237. var _v0 = new Vector3();
  9238. var _v1$2 = new Vector3();
  9239. var _v2 = new Vector3();
  9240. // triangle edge vectors
  9241. var _f0 = new Vector3();
  9242. var _f1 = new Vector3();
  9243. var _f2 = new Vector3();
  9244. var _center = new Vector3();
  9245. var _extents = new Vector3();
  9246. var _triangleNormal = new Vector3();
  9247. var _testAxis = new Vector3();
  9248. /**
  9249. * @author bhouston / http://clara.io
  9250. * @author WestLangley / http://github.com/WestLangley
  9251. */
  9252. function Box3( min, max ) {
  9253. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9254. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9255. }
  9256. Object.assign( Box3.prototype, {
  9257. isBox3: true,
  9258. set: function ( min, max ) {
  9259. this.min.copy( min );
  9260. this.max.copy( max );
  9261. return this;
  9262. },
  9263. setFromArray: function ( array ) {
  9264. var minX = + Infinity;
  9265. var minY = + Infinity;
  9266. var minZ = + Infinity;
  9267. var maxX = - Infinity;
  9268. var maxY = - Infinity;
  9269. var maxZ = - Infinity;
  9270. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9271. var x = array[ i ];
  9272. var y = array[ i + 1 ];
  9273. var z = array[ i + 2 ];
  9274. if ( x < minX ) { minX = x; }
  9275. if ( y < minY ) { minY = y; }
  9276. if ( z < minZ ) { minZ = z; }
  9277. if ( x > maxX ) { maxX = x; }
  9278. if ( y > maxY ) { maxY = y; }
  9279. if ( z > maxZ ) { maxZ = z; }
  9280. }
  9281. this.min.set( minX, minY, minZ );
  9282. this.max.set( maxX, maxY, maxZ );
  9283. return this;
  9284. },
  9285. setFromBufferAttribute: function ( attribute ) {
  9286. var minX = + Infinity;
  9287. var minY = + Infinity;
  9288. var minZ = + Infinity;
  9289. var maxX = - Infinity;
  9290. var maxY = - Infinity;
  9291. var maxZ = - Infinity;
  9292. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9293. var x = attribute.getX( i );
  9294. var y = attribute.getY( i );
  9295. var z = attribute.getZ( i );
  9296. if ( x < minX ) { minX = x; }
  9297. if ( y < minY ) { minY = y; }
  9298. if ( z < minZ ) { minZ = z; }
  9299. if ( x > maxX ) { maxX = x; }
  9300. if ( y > maxY ) { maxY = y; }
  9301. if ( z > maxZ ) { maxZ = z; }
  9302. }
  9303. this.min.set( minX, minY, minZ );
  9304. this.max.set( maxX, maxY, maxZ );
  9305. return this;
  9306. },
  9307. setFromPoints: function ( points ) {
  9308. this.makeEmpty();
  9309. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9310. this.expandByPoint( points[ i ] );
  9311. }
  9312. return this;
  9313. },
  9314. setFromCenterAndSize: function ( center, size ) {
  9315. var halfSize = _vector$2.copy( size ).multiplyScalar( 0.5 );
  9316. this.min.copy( center ).sub( halfSize );
  9317. this.max.copy( center ).add( halfSize );
  9318. return this;
  9319. },
  9320. setFromObject: function ( object ) {
  9321. this.makeEmpty();
  9322. return this.expandByObject( object );
  9323. },
  9324. clone: function () {
  9325. return new this.constructor().copy( this );
  9326. },
  9327. copy: function ( box ) {
  9328. this.min.copy( box.min );
  9329. this.max.copy( box.max );
  9330. return this;
  9331. },
  9332. makeEmpty: function () {
  9333. this.min.x = this.min.y = this.min.z = + Infinity;
  9334. this.max.x = this.max.y = this.max.z = - Infinity;
  9335. return this;
  9336. },
  9337. isEmpty: function () {
  9338. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9339. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9340. },
  9341. getCenter: function ( target ) {
  9342. if ( target === undefined ) {
  9343. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  9344. target = new Vector3();
  9345. }
  9346. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9347. },
  9348. getSize: function ( target ) {
  9349. if ( target === undefined ) {
  9350. console.warn( 'THREE.Box3: .getSize() target is now required' );
  9351. target = new Vector3();
  9352. }
  9353. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  9354. },
  9355. expandByPoint: function ( point ) {
  9356. this.min.min( point );
  9357. this.max.max( point );
  9358. return this;
  9359. },
  9360. expandByVector: function ( vector ) {
  9361. this.min.sub( vector );
  9362. this.max.add( vector );
  9363. return this;
  9364. },
  9365. expandByScalar: function ( scalar ) {
  9366. this.min.addScalar( - scalar );
  9367. this.max.addScalar( scalar );
  9368. return this;
  9369. },
  9370. expandByObject: function ( object ) {
  9371. var i, l;
  9372. // Computes the world-axis-aligned bounding box of an object (including its children),
  9373. // accounting for both the object's, and children's, world transforms
  9374. object.updateWorldMatrix( false, false );
  9375. var geometry = object.geometry;
  9376. if ( geometry !== undefined ) {
  9377. if ( geometry.isGeometry ) {
  9378. var vertices = geometry.vertices;
  9379. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  9380. _vector$2.copy( vertices[ i ] );
  9381. _vector$2.applyMatrix4( object.matrixWorld );
  9382. this.expandByPoint( _vector$2 );
  9383. }
  9384. } else if ( geometry.isBufferGeometry ) {
  9385. var attribute = geometry.attributes.position;
  9386. if ( attribute !== undefined ) {
  9387. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  9388. _vector$2.fromBufferAttribute( attribute, i ).applyMatrix4( object.matrixWorld );
  9389. this.expandByPoint( _vector$2 );
  9390. }
  9391. }
  9392. }
  9393. }
  9394. //
  9395. var children = object.children;
  9396. for ( i = 0, l = children.length; i < l; i ++ ) {
  9397. this.expandByObject( children[ i ] );
  9398. }
  9399. return this;
  9400. },
  9401. containsPoint: function ( point ) {
  9402. return point.x < this.min.x || point.x > this.max.x ||
  9403. point.y < this.min.y || point.y > this.max.y ||
  9404. point.z < this.min.z || point.z > this.max.z ? false : true;
  9405. },
  9406. containsBox: function ( box ) {
  9407. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9408. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9409. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9410. },
  9411. getParameter: function ( point, target ) {
  9412. // This can potentially have a divide by zero if the box
  9413. // has a size dimension of 0.
  9414. if ( target === undefined ) {
  9415. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  9416. target = new Vector3();
  9417. }
  9418. return target.set(
  9419. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9420. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9421. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9422. );
  9423. },
  9424. intersectsBox: function ( box ) {
  9425. // using 6 splitting planes to rule out intersections.
  9426. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9427. box.max.y < this.min.y || box.min.y > this.max.y ||
  9428. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9429. },
  9430. intersectsSphere: function ( sphere ) {
  9431. // Find the point on the AABB closest to the sphere center.
  9432. this.clampPoint( sphere.center, _vector$2 );
  9433. // If that point is inside the sphere, the AABB and sphere intersect.
  9434. return _vector$2.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9435. },
  9436. intersectsPlane: function ( plane ) {
  9437. // We compute the minimum and maximum dot product values. If those values
  9438. // are on the same side (back or front) of the plane, then there is no intersection.
  9439. var min, max;
  9440. if ( plane.normal.x > 0 ) {
  9441. min = plane.normal.x * this.min.x;
  9442. max = plane.normal.x * this.max.x;
  9443. } else {
  9444. min = plane.normal.x * this.max.x;
  9445. max = plane.normal.x * this.min.x;
  9446. }
  9447. if ( plane.normal.y > 0 ) {
  9448. min += plane.normal.y * this.min.y;
  9449. max += plane.normal.y * this.max.y;
  9450. } else {
  9451. min += plane.normal.y * this.max.y;
  9452. max += plane.normal.y * this.min.y;
  9453. }
  9454. if ( plane.normal.z > 0 ) {
  9455. min += plane.normal.z * this.min.z;
  9456. max += plane.normal.z * this.max.z;
  9457. } else {
  9458. min += plane.normal.z * this.max.z;
  9459. max += plane.normal.z * this.min.z;
  9460. }
  9461. return ( min <= - plane.constant && max >= - plane.constant );
  9462. },
  9463. intersectsTriangle: function ( triangle ) {
  9464. if ( this.isEmpty() ) {
  9465. return false;
  9466. }
  9467. // compute box center and extents
  9468. this.getCenter( _center );
  9469. _extents.subVectors( this.max, _center );
  9470. // translate triangle to aabb origin
  9471. _v0.subVectors( triangle.a, _center );
  9472. _v1$2.subVectors( triangle.b, _center );
  9473. _v2.subVectors( triangle.c, _center );
  9474. // compute edge vectors for triangle
  9475. _f0.subVectors( _v1$2, _v0 );
  9476. _f1.subVectors( _v2, _v1$2 );
  9477. _f2.subVectors( _v0, _v2 );
  9478. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  9479. // 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
  9480. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  9481. var axes = [
  9482. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  9483. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  9484. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  9485. ];
  9486. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9487. return false;
  9488. }
  9489. // test 3 face normals from the aabb
  9490. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  9491. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9492. return false;
  9493. }
  9494. // finally testing the face normal of the triangle
  9495. // use already existing triangle edge vectors here
  9496. _triangleNormal.crossVectors( _f0, _f1 );
  9497. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  9498. return satForAxes( axes, _v0, _v1$2, _v2, _extents );
  9499. },
  9500. clampPoint: function ( point, target ) {
  9501. if ( target === undefined ) {
  9502. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  9503. target = new Vector3();
  9504. }
  9505. return target.copy( point ).clamp( this.min, this.max );
  9506. },
  9507. distanceToPoint: function ( point ) {
  9508. var clampedPoint = _vector$2.copy( point ).clamp( this.min, this.max );
  9509. return clampedPoint.sub( point ).length();
  9510. },
  9511. getBoundingSphere: function ( target ) {
  9512. if ( target === undefined ) {
  9513. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  9514. //target = new Sphere(); // removed to avoid cyclic dependency
  9515. }
  9516. this.getCenter( target.center );
  9517. target.radius = this.getSize( _vector$2 ).length() * 0.5;
  9518. return target;
  9519. },
  9520. intersect: function ( box ) {
  9521. this.min.max( box.min );
  9522. this.max.min( box.max );
  9523. // 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.
  9524. if ( this.isEmpty() ) { this.makeEmpty(); }
  9525. return this;
  9526. },
  9527. union: function ( box ) {
  9528. this.min.min( box.min );
  9529. this.max.max( box.max );
  9530. return this;
  9531. },
  9532. applyMatrix4: function ( matrix ) {
  9533. // transform of empty box is an empty box.
  9534. if ( this.isEmpty() ) { return this; }
  9535. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9536. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9537. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9538. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9539. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9540. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9541. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9542. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9543. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9544. this.setFromPoints( _points );
  9545. return this;
  9546. },
  9547. translate: function ( offset ) {
  9548. this.min.add( offset );
  9549. this.max.add( offset );
  9550. return this;
  9551. },
  9552. equals: function ( box ) {
  9553. return box.min.equals( this.min ) && box.max.equals( this.max );
  9554. }
  9555. } );
  9556. function satForAxes( axes, v0, v1, v2, extents ) {
  9557. var i, j;
  9558. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  9559. _testAxis.fromArray( axes, i );
  9560. // project the aabb onto the seperating axis
  9561. var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  9562. // project all 3 vertices of the triangle onto the seperating axis
  9563. var p0 = v0.dot( _testAxis );
  9564. var p1 = v1.dot( _testAxis );
  9565. var p2 = v2.dot( _testAxis );
  9566. // actual test, basically see if either of the most extreme of the triangle points intersects r
  9567. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  9568. // points of the projected triangle are outside the projected half-length of the aabb
  9569. // the axis is seperating and we can exit
  9570. return false;
  9571. }
  9572. }
  9573. return true;
  9574. }
  9575. var _box = new Box3();
  9576. /**
  9577. * @author bhouston / http://clara.io
  9578. * @author mrdoob / http://mrdoob.com/
  9579. */
  9580. function Sphere( center, radius ) {
  9581. this.center = ( center !== undefined ) ? center : new Vector3();
  9582. this.radius = ( radius !== undefined ) ? radius : 0;
  9583. }
  9584. Object.assign( Sphere.prototype, {
  9585. set: function ( center, radius ) {
  9586. this.center.copy( center );
  9587. this.radius = radius;
  9588. return this;
  9589. },
  9590. setFromPoints: function ( points, optionalCenter ) {
  9591. var center = this.center;
  9592. if ( optionalCenter !== undefined ) {
  9593. center.copy( optionalCenter );
  9594. } else {
  9595. _box.setFromPoints( points ).getCenter( center );
  9596. }
  9597. var maxRadiusSq = 0;
  9598. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9599. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9600. }
  9601. this.radius = Math.sqrt( maxRadiusSq );
  9602. return this;
  9603. },
  9604. clone: function () {
  9605. return new this.constructor().copy( this );
  9606. },
  9607. copy: function ( sphere ) {
  9608. this.center.copy( sphere.center );
  9609. this.radius = sphere.radius;
  9610. return this;
  9611. },
  9612. empty: function () {
  9613. return ( this.radius <= 0 );
  9614. },
  9615. containsPoint: function ( point ) {
  9616. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9617. },
  9618. distanceToPoint: function ( point ) {
  9619. return ( point.distanceTo( this.center ) - this.radius );
  9620. },
  9621. intersectsSphere: function ( sphere ) {
  9622. var radiusSum = this.radius + sphere.radius;
  9623. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9624. },
  9625. intersectsBox: function ( box ) {
  9626. return box.intersectsSphere( this );
  9627. },
  9628. intersectsPlane: function ( plane ) {
  9629. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  9630. },
  9631. clampPoint: function ( point, target ) {
  9632. var deltaLengthSq = this.center.distanceToSquared( point );
  9633. if ( target === undefined ) {
  9634. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  9635. target = new Vector3();
  9636. }
  9637. target.copy( point );
  9638. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9639. target.sub( this.center ).normalize();
  9640. target.multiplyScalar( this.radius ).add( this.center );
  9641. }
  9642. return target;
  9643. },
  9644. getBoundingBox: function ( target ) {
  9645. if ( target === undefined ) {
  9646. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  9647. target = new Box3();
  9648. }
  9649. target.set( this.center, this.center );
  9650. target.expandByScalar( this.radius );
  9651. return target;
  9652. },
  9653. applyMatrix4: function ( matrix ) {
  9654. this.center.applyMatrix4( matrix );
  9655. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9656. return this;
  9657. },
  9658. translate: function ( offset ) {
  9659. this.center.add( offset );
  9660. return this;
  9661. },
  9662. equals: function ( sphere ) {
  9663. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9664. }
  9665. } );
  9666. var _vector$3 = new Vector3();
  9667. var _segCenter = new Vector3();
  9668. var _segDir = new Vector3();
  9669. var _diff = new Vector3();
  9670. var _edge1 = new Vector3();
  9671. var _edge2 = new Vector3();
  9672. var _normal = new Vector3();
  9673. /**
  9674. * @author bhouston / http://clara.io
  9675. */
  9676. function Ray( origin, direction ) {
  9677. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  9678. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  9679. }
  9680. Object.assign( Ray.prototype, {
  9681. set: function ( origin, direction ) {
  9682. this.origin.copy( origin );
  9683. this.direction.copy( direction );
  9684. return this;
  9685. },
  9686. clone: function () {
  9687. return new this.constructor().copy( this );
  9688. },
  9689. copy: function ( ray ) {
  9690. this.origin.copy( ray.origin );
  9691. this.direction.copy( ray.direction );
  9692. return this;
  9693. },
  9694. at: function ( t, target ) {
  9695. if ( target === undefined ) {
  9696. console.warn( 'THREE.Ray: .at() target is now required' );
  9697. target = new Vector3();
  9698. }
  9699. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9700. },
  9701. lookAt: function ( v ) {
  9702. this.direction.copy( v ).sub( this.origin ).normalize();
  9703. return this;
  9704. },
  9705. recast: function ( t ) {
  9706. this.origin.copy( this.at( t, _vector$3 ) );
  9707. return this;
  9708. },
  9709. closestPointToPoint: function ( point, target ) {
  9710. if ( target === undefined ) {
  9711. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  9712. target = new Vector3();
  9713. }
  9714. target.subVectors( point, this.origin );
  9715. var directionDistance = target.dot( this.direction );
  9716. if ( directionDistance < 0 ) {
  9717. return target.copy( this.origin );
  9718. }
  9719. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9720. },
  9721. distanceToPoint: function ( point ) {
  9722. return Math.sqrt( this.distanceSqToPoint( point ) );
  9723. },
  9724. distanceSqToPoint: function ( point ) {
  9725. var directionDistance = _vector$3.subVectors( point, this.origin ).dot( this.direction );
  9726. // point behind the ray
  9727. if ( directionDistance < 0 ) {
  9728. return this.origin.distanceToSquared( point );
  9729. }
  9730. _vector$3.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9731. return _vector$3.distanceToSquared( point );
  9732. },
  9733. distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9734. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9735. // It returns the min distance between the ray and the segment
  9736. // defined by v0 and v1
  9737. // It can also set two optional targets :
  9738. // - The closest point on the ray
  9739. // - The closest point on the segment
  9740. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9741. _segDir.copy( v1 ).sub( v0 ).normalize();
  9742. _diff.copy( this.origin ).sub( _segCenter );
  9743. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9744. var a01 = - this.direction.dot( _segDir );
  9745. var b0 = _diff.dot( this.direction );
  9746. var b1 = - _diff.dot( _segDir );
  9747. var c = _diff.lengthSq();
  9748. var det = Math.abs( 1 - a01 * a01 );
  9749. var s0, s1, sqrDist, extDet;
  9750. if ( det > 0 ) {
  9751. // The ray and segment are not parallel.
  9752. s0 = a01 * b1 - b0;
  9753. s1 = a01 * b0 - b1;
  9754. extDet = segExtent * det;
  9755. if ( s0 >= 0 ) {
  9756. if ( s1 >= - extDet ) {
  9757. if ( s1 <= extDet ) {
  9758. // region 0
  9759. // Minimum at interior points of ray and segment.
  9760. var invDet = 1 / det;
  9761. s0 *= invDet;
  9762. s1 *= invDet;
  9763. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9764. } else {
  9765. // region 1
  9766. s1 = segExtent;
  9767. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9768. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9769. }
  9770. } else {
  9771. // region 5
  9772. s1 = - segExtent;
  9773. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9774. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9775. }
  9776. } else {
  9777. if ( s1 <= - extDet ) {
  9778. // region 4
  9779. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9780. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9781. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9782. } else if ( s1 <= extDet ) {
  9783. // region 3
  9784. s0 = 0;
  9785. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9786. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9787. } else {
  9788. // region 2
  9789. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9790. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9791. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9792. }
  9793. }
  9794. } else {
  9795. // Ray and segment are parallel.
  9796. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9797. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9798. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9799. }
  9800. if ( optionalPointOnRay ) {
  9801. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9802. }
  9803. if ( optionalPointOnSegment ) {
  9804. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  9805. }
  9806. return sqrDist;
  9807. },
  9808. intersectSphere: function ( sphere, target ) {
  9809. _vector$3.subVectors( sphere.center, this.origin );
  9810. var tca = _vector$3.dot( this.direction );
  9811. var d2 = _vector$3.dot( _vector$3 ) - tca * tca;
  9812. var radius2 = sphere.radius * sphere.radius;
  9813. if ( d2 > radius2 ) { return null; }
  9814. var thc = Math.sqrt( radius2 - d2 );
  9815. // t0 = first intersect point - entrance on front of sphere
  9816. var t0 = tca - thc;
  9817. // t1 = second intersect point - exit point on back of sphere
  9818. var t1 = tca + thc;
  9819. // test to see if both t0 and t1 are behind the ray - if so, return null
  9820. if ( t0 < 0 && t1 < 0 ) { return null; }
  9821. // test to see if t0 is behind the ray:
  9822. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9823. // in order to always return an intersect point that is in front of the ray.
  9824. if ( t0 < 0 ) { return this.at( t1, target ); }
  9825. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9826. return this.at( t0, target );
  9827. },
  9828. intersectsSphere: function ( sphere ) {
  9829. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  9830. },
  9831. distanceToPlane: function ( plane ) {
  9832. var denominator = plane.normal.dot( this.direction );
  9833. if ( denominator === 0 ) {
  9834. // line is coplanar, return origin
  9835. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9836. return 0;
  9837. }
  9838. // Null is preferable to undefined since undefined means.... it is undefined
  9839. return null;
  9840. }
  9841. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9842. // Return if the ray never intersects the plane
  9843. return t >= 0 ? t : null;
  9844. },
  9845. intersectPlane: function ( plane, target ) {
  9846. var t = this.distanceToPlane( plane );
  9847. if ( t === null ) {
  9848. return null;
  9849. }
  9850. return this.at( t, target );
  9851. },
  9852. intersectsPlane: function ( plane ) {
  9853. // check if the ray lies on the plane first
  9854. var distToPoint = plane.distanceToPoint( this.origin );
  9855. if ( distToPoint === 0 ) {
  9856. return true;
  9857. }
  9858. var denominator = plane.normal.dot( this.direction );
  9859. if ( denominator * distToPoint < 0 ) {
  9860. return true;
  9861. }
  9862. // ray origin is behind the plane (and is pointing behind it)
  9863. return false;
  9864. },
  9865. intersectBox: function ( box, target ) {
  9866. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9867. var invdirx = 1 / this.direction.x,
  9868. invdiry = 1 / this.direction.y,
  9869. invdirz = 1 / this.direction.z;
  9870. var origin = this.origin;
  9871. if ( invdirx >= 0 ) {
  9872. tmin = ( box.min.x - origin.x ) * invdirx;
  9873. tmax = ( box.max.x - origin.x ) * invdirx;
  9874. } else {
  9875. tmin = ( box.max.x - origin.x ) * invdirx;
  9876. tmax = ( box.min.x - origin.x ) * invdirx;
  9877. }
  9878. if ( invdiry >= 0 ) {
  9879. tymin = ( box.min.y - origin.y ) * invdiry;
  9880. tymax = ( box.max.y - origin.y ) * invdiry;
  9881. } else {
  9882. tymin = ( box.max.y - origin.y ) * invdiry;
  9883. tymax = ( box.min.y - origin.y ) * invdiry;
  9884. }
  9885. if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; }
  9886. // These lines also handle the case where tmin or tmax is NaN
  9887. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9888. if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; }
  9889. if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; }
  9890. if ( invdirz >= 0 ) {
  9891. tzmin = ( box.min.z - origin.z ) * invdirz;
  9892. tzmax = ( box.max.z - origin.z ) * invdirz;
  9893. } else {
  9894. tzmin = ( box.max.z - origin.z ) * invdirz;
  9895. tzmax = ( box.min.z - origin.z ) * invdirz;
  9896. }
  9897. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; }
  9898. if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; }
  9899. if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; }
  9900. //return point closest to the ray (positive side)
  9901. if ( tmax < 0 ) { return null; }
  9902. return this.at( tmin >= 0 ? tmin : tmax, target );
  9903. },
  9904. intersectsBox: function ( box ) {
  9905. return this.intersectBox( box, _vector$3 ) !== null;
  9906. },
  9907. intersectTriangle: function ( a, b, c, backfaceCulling, target ) {
  9908. // Compute the offset origin, edges, and normal.
  9909. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9910. _edge1.subVectors( b, a );
  9911. _edge2.subVectors( c, a );
  9912. _normal.crossVectors( _edge1, _edge2 );
  9913. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9914. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9915. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9916. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9917. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9918. var DdN = this.direction.dot( _normal );
  9919. var sign;
  9920. if ( DdN > 0 ) {
  9921. if ( backfaceCulling ) { return null; }
  9922. sign = 1;
  9923. } else if ( DdN < 0 ) {
  9924. sign = - 1;
  9925. DdN = - DdN;
  9926. } else {
  9927. return null;
  9928. }
  9929. _diff.subVectors( this.origin, a );
  9930. var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  9931. // b1 < 0, no intersection
  9932. if ( DdQxE2 < 0 ) {
  9933. return null;
  9934. }
  9935. var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  9936. // b2 < 0, no intersection
  9937. if ( DdE1xQ < 0 ) {
  9938. return null;
  9939. }
  9940. // b1+b2 > 1, no intersection
  9941. if ( DdQxE2 + DdE1xQ > DdN ) {
  9942. return null;
  9943. }
  9944. // Line intersects triangle, check if ray does.
  9945. var QdN = - sign * _diff.dot( _normal );
  9946. // t < 0, no intersection
  9947. if ( QdN < 0 ) {
  9948. return null;
  9949. }
  9950. // Ray intersects triangle.
  9951. return this.at( QdN / DdN, target );
  9952. },
  9953. applyMatrix4: function ( matrix4 ) {
  9954. this.origin.applyMatrix4( matrix4 );
  9955. this.direction.transformDirection( matrix4 );
  9956. return this;
  9957. },
  9958. equals: function ( ray ) {
  9959. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9960. }
  9961. } );
  9962. /**
  9963. * @author bhouston / http://clara.io
  9964. * @author mrdoob / http://mrdoob.com/
  9965. */
  9966. var _v0$1 = new Vector3();
  9967. var _v1$3 = new Vector3();
  9968. var _v2$1 = new Vector3();
  9969. var _v3 = new Vector3();
  9970. var _vab = new Vector3();
  9971. var _vac = new Vector3();
  9972. var _vbc = new Vector3();
  9973. var _vap = new Vector3();
  9974. var _vbp = new Vector3();
  9975. var _vcp = new Vector3();
  9976. function Triangle( a, b, c ) {
  9977. this.a = ( a !== undefined ) ? a : new Vector3();
  9978. this.b = ( b !== undefined ) ? b : new Vector3();
  9979. this.c = ( c !== undefined ) ? c : new Vector3();
  9980. }
  9981. Object.assign( Triangle, {
  9982. getNormal: function ( a, b, c, target ) {
  9983. if ( target === undefined ) {
  9984. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  9985. target = new Vector3();
  9986. }
  9987. target.subVectors( c, b );
  9988. _v0$1.subVectors( a, b );
  9989. target.cross( _v0$1 );
  9990. var targetLengthSq = target.lengthSq();
  9991. if ( targetLengthSq > 0 ) {
  9992. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  9993. }
  9994. return target.set( 0, 0, 0 );
  9995. },
  9996. // static/instance method to calculate barycentric coordinates
  9997. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9998. getBarycoord: function ( point, a, b, c, target ) {
  9999. _v0$1.subVectors( c, a );
  10000. _v1$3.subVectors( b, a );
  10001. _v2$1.subVectors( point, a );
  10002. var dot00 = _v0$1.dot( _v0$1 );
  10003. var dot01 = _v0$1.dot( _v1$3 );
  10004. var dot02 = _v0$1.dot( _v2$1 );
  10005. var dot11 = _v1$3.dot( _v1$3 );
  10006. var dot12 = _v1$3.dot( _v2$1 );
  10007. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10008. if ( target === undefined ) {
  10009. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  10010. target = new Vector3();
  10011. }
  10012. // collinear or singular triangle
  10013. if ( denom === 0 ) {
  10014. // arbitrary location outside of triangle?
  10015. // not sure if this is the best idea, maybe should be returning undefined
  10016. return target.set( - 2, - 1, - 1 );
  10017. }
  10018. var invDenom = 1 / denom;
  10019. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10020. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10021. // barycentric coordinates must always sum to 1
  10022. return target.set( 1 - u - v, v, u );
  10023. },
  10024. containsPoint: function ( point, a, b, c ) {
  10025. Triangle.getBarycoord( point, a, b, c, _v3 );
  10026. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  10027. },
  10028. getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  10029. this.getBarycoord( point, p1, p2, p3, _v3 );
  10030. target.set( 0, 0 );
  10031. target.addScaledVector( uv1, _v3.x );
  10032. target.addScaledVector( uv2, _v3.y );
  10033. target.addScaledVector( uv3, _v3.z );
  10034. return target;
  10035. },
  10036. isFrontFacing: function ( a, b, c, direction ) {
  10037. _v0$1.subVectors( c, b );
  10038. _v1$3.subVectors( a, b );
  10039. // strictly front facing
  10040. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  10041. }
  10042. } );
  10043. Object.assign( Triangle.prototype, {
  10044. set: function ( a, b, c ) {
  10045. this.a.copy( a );
  10046. this.b.copy( b );
  10047. this.c.copy( c );
  10048. return this;
  10049. },
  10050. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10051. this.a.copy( points[ i0 ] );
  10052. this.b.copy( points[ i1 ] );
  10053. this.c.copy( points[ i2 ] );
  10054. return this;
  10055. },
  10056. clone: function () {
  10057. return new this.constructor().copy( this );
  10058. },
  10059. copy: function ( triangle ) {
  10060. this.a.copy( triangle.a );
  10061. this.b.copy( triangle.b );
  10062. this.c.copy( triangle.c );
  10063. return this;
  10064. },
  10065. getArea: function () {
  10066. _v0$1.subVectors( this.c, this.b );
  10067. _v1$3.subVectors( this.a, this.b );
  10068. return _v0$1.cross( _v1$3 ).length() * 0.5;
  10069. },
  10070. getMidpoint: function ( target ) {
  10071. if ( target === undefined ) {
  10072. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  10073. target = new Vector3();
  10074. }
  10075. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10076. },
  10077. getNormal: function ( target ) {
  10078. return Triangle.getNormal( this.a, this.b, this.c, target );
  10079. },
  10080. getPlane: function ( target ) {
  10081. if ( target === undefined ) {
  10082. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  10083. target = new Vector3();
  10084. }
  10085. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  10086. },
  10087. getBarycoord: function ( point, target ) {
  10088. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  10089. },
  10090. getUV: function ( point, uv1, uv2, uv3, target ) {
  10091. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  10092. },
  10093. containsPoint: function ( point ) {
  10094. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10095. },
  10096. isFrontFacing: function ( direction ) {
  10097. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  10098. },
  10099. intersectsBox: function ( box ) {
  10100. return box.intersectsTriangle( this );
  10101. },
  10102. closestPointToPoint: function ( p, target ) {
  10103. if ( target === undefined ) {
  10104. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  10105. target = new Vector3();
  10106. }
  10107. var a = this.a, b = this.b, c = this.c;
  10108. var v, w;
  10109. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  10110. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  10111. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  10112. // basically, we're distinguishing which of the voronoi regions of the triangle
  10113. // the point lies in with the minimum amount of redundant computation.
  10114. _vab.subVectors( b, a );
  10115. _vac.subVectors( c, a );
  10116. _vap.subVectors( p, a );
  10117. var d1 = _vab.dot( _vap );
  10118. var d2 = _vac.dot( _vap );
  10119. if ( d1 <= 0 && d2 <= 0 ) {
  10120. // vertex region of A; barycentric coords (1, 0, 0)
  10121. return target.copy( a );
  10122. }
  10123. _vbp.subVectors( p, b );
  10124. var d3 = _vab.dot( _vbp );
  10125. var d4 = _vac.dot( _vbp );
  10126. if ( d3 >= 0 && d4 <= d3 ) {
  10127. // vertex region of B; barycentric coords (0, 1, 0)
  10128. return target.copy( b );
  10129. }
  10130. var vc = d1 * d4 - d3 * d2;
  10131. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  10132. v = d1 / ( d1 - d3 );
  10133. // edge region of AB; barycentric coords (1-v, v, 0)
  10134. return target.copy( a ).addScaledVector( _vab, v );
  10135. }
  10136. _vcp.subVectors( p, c );
  10137. var d5 = _vab.dot( _vcp );
  10138. var d6 = _vac.dot( _vcp );
  10139. if ( d6 >= 0 && d5 <= d6 ) {
  10140. // vertex region of C; barycentric coords (0, 0, 1)
  10141. return target.copy( c );
  10142. }
  10143. var vb = d5 * d2 - d1 * d6;
  10144. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  10145. w = d2 / ( d2 - d6 );
  10146. // edge region of AC; barycentric coords (1-w, 0, w)
  10147. return target.copy( a ).addScaledVector( _vac, w );
  10148. }
  10149. var va = d3 * d6 - d5 * d4;
  10150. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  10151. _vbc.subVectors( c, b );
  10152. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  10153. // edge region of BC; barycentric coords (0, 1-w, w)
  10154. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  10155. }
  10156. // face region
  10157. var denom = 1 / ( va + vb + vc );
  10158. // u = va * denom
  10159. v = vb * denom;
  10160. w = vc * denom;
  10161. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  10162. },
  10163. equals: function ( triangle ) {
  10164. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  10165. }
  10166. } );
  10167. /**
  10168. * @author mrdoob / http://mrdoob.com/
  10169. */
  10170. var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10171. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10172. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10173. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10174. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10175. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10176. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10177. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10178. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10179. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10180. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10181. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10182. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10183. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10184. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10185. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10186. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10187. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10188. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10189. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10190. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10191. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10192. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10193. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10194. var _hslA = { h: 0, s: 0, l: 0 };
  10195. var _hslB = { h: 0, s: 0, l: 0 };
  10196. function Color( r, g, b ) {
  10197. if ( g === undefined && b === undefined ) {
  10198. // r is THREE.Color, hex or string
  10199. return this.set( r );
  10200. }
  10201. return this.setRGB( r, g, b );
  10202. }
  10203. function hue2rgb( p, q, t ) {
  10204. if ( t < 0 ) { t += 1; }
  10205. if ( t > 1 ) { t -= 1; }
  10206. if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; }
  10207. if ( t < 1 / 2 ) { return q; }
  10208. if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); }
  10209. return p;
  10210. }
  10211. function SRGBToLinear( c ) {
  10212. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  10213. }
  10214. function LinearToSRGB( c ) {
  10215. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  10216. }
  10217. Object.assign( Color.prototype, {
  10218. isColor: true,
  10219. r: 1, g: 1, b: 1,
  10220. set: function ( value ) {
  10221. if ( value && value.isColor ) {
  10222. this.copy( value );
  10223. } else if ( typeof value === 'number' ) {
  10224. this.setHex( value );
  10225. } else if ( typeof value === 'string' ) {
  10226. this.setStyle( value );
  10227. }
  10228. return this;
  10229. },
  10230. setScalar: function ( scalar ) {
  10231. this.r = scalar;
  10232. this.g = scalar;
  10233. this.b = scalar;
  10234. return this;
  10235. },
  10236. setHex: function ( hex ) {
  10237. hex = Math.floor( hex );
  10238. this.r = ( hex >> 16 & 255 ) / 255;
  10239. this.g = ( hex >> 8 & 255 ) / 255;
  10240. this.b = ( hex & 255 ) / 255;
  10241. return this;
  10242. },
  10243. setRGB: function ( r, g, b ) {
  10244. this.r = r;
  10245. this.g = g;
  10246. this.b = b;
  10247. return this;
  10248. },
  10249. setHSL: function ( h, s, l ) {
  10250. // h,s,l ranges are in 0.0 - 1.0
  10251. h = _Math.euclideanModulo( h, 1 );
  10252. s = _Math.clamp( s, 0, 1 );
  10253. l = _Math.clamp( l, 0, 1 );
  10254. if ( s === 0 ) {
  10255. this.r = this.g = this.b = l;
  10256. } else {
  10257. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10258. var q = ( 2 * l ) - p;
  10259. this.r = hue2rgb( q, p, h + 1 / 3 );
  10260. this.g = hue2rgb( q, p, h );
  10261. this.b = hue2rgb( q, p, h - 1 / 3 );
  10262. }
  10263. return this;
  10264. },
  10265. setStyle: function ( style ) {
  10266. function handleAlpha( string ) {
  10267. if ( string === undefined ) { return; }
  10268. if ( parseFloat( string ) < 1 ) {
  10269. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  10270. }
  10271. }
  10272. var m;
  10273. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  10274. // rgb / hsl
  10275. var color;
  10276. var name = m[ 1 ];
  10277. var components = m[ 2 ];
  10278. switch ( name ) {
  10279. case 'rgb':
  10280. case 'rgba':
  10281. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10282. // rgb(255,0,0) rgba(255,0,0,0.5)
  10283. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  10284. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  10285. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  10286. handleAlpha( color[ 5 ] );
  10287. return this;
  10288. }
  10289. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10290. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10291. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  10292. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  10293. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  10294. handleAlpha( color[ 5 ] );
  10295. return this;
  10296. }
  10297. break;
  10298. case 'hsl':
  10299. case 'hsla':
  10300. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10301. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10302. var h = parseFloat( color[ 1 ] ) / 360;
  10303. var s = parseInt( color[ 2 ], 10 ) / 100;
  10304. var l = parseInt( color[ 3 ], 10 ) / 100;
  10305. handleAlpha( color[ 5 ] );
  10306. return this.setHSL( h, s, l );
  10307. }
  10308. break;
  10309. }
  10310. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  10311. // hex color
  10312. var hex = m[ 1 ];
  10313. var size = hex.length;
  10314. if ( size === 3 ) {
  10315. // #ff0
  10316. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  10317. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  10318. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  10319. return this;
  10320. } else if ( size === 6 ) {
  10321. // #ff0000
  10322. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  10323. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  10324. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  10325. return this;
  10326. }
  10327. }
  10328. if ( style && style.length > 0 ) {
  10329. // color keywords
  10330. var hex = _colorKeywords[ style ];
  10331. if ( hex !== undefined ) {
  10332. // red
  10333. this.setHex( hex );
  10334. } else {
  10335. // unknown color
  10336. console.warn( 'THREE.Color: Unknown color ' + style );
  10337. }
  10338. }
  10339. return this;
  10340. },
  10341. clone: function () {
  10342. return new this.constructor( this.r, this.g, this.b );
  10343. },
  10344. copy: function ( color ) {
  10345. this.r = color.r;
  10346. this.g = color.g;
  10347. this.b = color.b;
  10348. return this;
  10349. },
  10350. copyGammaToLinear: function ( color, gammaFactor ) {
  10351. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10352. this.r = Math.pow( color.r, gammaFactor );
  10353. this.g = Math.pow( color.g, gammaFactor );
  10354. this.b = Math.pow( color.b, gammaFactor );
  10355. return this;
  10356. },
  10357. copyLinearToGamma: function ( color, gammaFactor ) {
  10358. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10359. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  10360. this.r = Math.pow( color.r, safeInverse );
  10361. this.g = Math.pow( color.g, safeInverse );
  10362. this.b = Math.pow( color.b, safeInverse );
  10363. return this;
  10364. },
  10365. convertGammaToLinear: function ( gammaFactor ) {
  10366. this.copyGammaToLinear( this, gammaFactor );
  10367. return this;
  10368. },
  10369. convertLinearToGamma: function ( gammaFactor ) {
  10370. this.copyLinearToGamma( this, gammaFactor );
  10371. return this;
  10372. },
  10373. copySRGBToLinear: function ( color ) {
  10374. this.r = SRGBToLinear( color.r );
  10375. this.g = SRGBToLinear( color.g );
  10376. this.b = SRGBToLinear( color.b );
  10377. return this;
  10378. },
  10379. copyLinearToSRGB: function ( color ) {
  10380. this.r = LinearToSRGB( color.r );
  10381. this.g = LinearToSRGB( color.g );
  10382. this.b = LinearToSRGB( color.b );
  10383. return this;
  10384. },
  10385. convertSRGBToLinear: function () {
  10386. this.copySRGBToLinear( this );
  10387. return this;
  10388. },
  10389. convertLinearToSRGB: function () {
  10390. this.copyLinearToSRGB( this );
  10391. return this;
  10392. },
  10393. getHex: function () {
  10394. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  10395. },
  10396. getHexString: function () {
  10397. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  10398. },
  10399. getHSL: function ( target ) {
  10400. // h,s,l ranges are in 0.0 - 1.0
  10401. if ( target === undefined ) {
  10402. console.warn( 'THREE.Color: .getHSL() target is now required' );
  10403. target = { h: 0, s: 0, l: 0 };
  10404. }
  10405. var r = this.r, g = this.g, b = this.b;
  10406. var max = Math.max( r, g, b );
  10407. var min = Math.min( r, g, b );
  10408. var hue, saturation;
  10409. var lightness = ( min + max ) / 2.0;
  10410. if ( min === max ) {
  10411. hue = 0;
  10412. saturation = 0;
  10413. } else {
  10414. var delta = max - min;
  10415. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10416. switch ( max ) {
  10417. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10418. case g: hue = ( b - r ) / delta + 2; break;
  10419. case b: hue = ( r - g ) / delta + 4; break;
  10420. }
  10421. hue /= 6;
  10422. }
  10423. target.h = hue;
  10424. target.s = saturation;
  10425. target.l = lightness;
  10426. return target;
  10427. },
  10428. getStyle: function () {
  10429. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  10430. },
  10431. offsetHSL: function ( h, s, l ) {
  10432. this.getHSL( _hslA );
  10433. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  10434. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  10435. return this;
  10436. },
  10437. add: function ( color ) {
  10438. this.r += color.r;
  10439. this.g += color.g;
  10440. this.b += color.b;
  10441. return this;
  10442. },
  10443. addColors: function ( color1, color2 ) {
  10444. this.r = color1.r + color2.r;
  10445. this.g = color1.g + color2.g;
  10446. this.b = color1.b + color2.b;
  10447. return this;
  10448. },
  10449. addScalar: function ( s ) {
  10450. this.r += s;
  10451. this.g += s;
  10452. this.b += s;
  10453. return this;
  10454. },
  10455. sub: function ( color ) {
  10456. this.r = Math.max( 0, this.r - color.r );
  10457. this.g = Math.max( 0, this.g - color.g );
  10458. this.b = Math.max( 0, this.b - color.b );
  10459. return this;
  10460. },
  10461. multiply: function ( color ) {
  10462. this.r *= color.r;
  10463. this.g *= color.g;
  10464. this.b *= color.b;
  10465. return this;
  10466. },
  10467. multiplyScalar: function ( s ) {
  10468. this.r *= s;
  10469. this.g *= s;
  10470. this.b *= s;
  10471. return this;
  10472. },
  10473. lerp: function ( color, alpha ) {
  10474. this.r += ( color.r - this.r ) * alpha;
  10475. this.g += ( color.g - this.g ) * alpha;
  10476. this.b += ( color.b - this.b ) * alpha;
  10477. return this;
  10478. },
  10479. lerpHSL: function ( color, alpha ) {
  10480. this.getHSL( _hslA );
  10481. color.getHSL( _hslB );
  10482. var h = _Math.lerp( _hslA.h, _hslB.h, alpha );
  10483. var s = _Math.lerp( _hslA.s, _hslB.s, alpha );
  10484. var l = _Math.lerp( _hslA.l, _hslB.l, alpha );
  10485. this.setHSL( h, s, l );
  10486. return this;
  10487. },
  10488. equals: function ( c ) {
  10489. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  10490. },
  10491. fromArray: function ( array, offset ) {
  10492. if ( offset === undefined ) { offset = 0; }
  10493. this.r = array[ offset ];
  10494. this.g = array[ offset + 1 ];
  10495. this.b = array[ offset + 2 ];
  10496. return this;
  10497. },
  10498. toArray: function ( array, offset ) {
  10499. if ( array === undefined ) { array = []; }
  10500. if ( offset === undefined ) { offset = 0; }
  10501. array[ offset ] = this.r;
  10502. array[ offset + 1 ] = this.g;
  10503. array[ offset + 2 ] = this.b;
  10504. return array;
  10505. },
  10506. toJSON: function () {
  10507. return this.getHex();
  10508. }
  10509. } );
  10510. /**
  10511. * @author mrdoob / http://mrdoob.com/
  10512. * @author alteredq / http://alteredqualia.com/
  10513. */
  10514. function Face3( a, b, c, normal, color, materialIndex ) {
  10515. this.a = a;
  10516. this.b = b;
  10517. this.c = c;
  10518. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  10519. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  10520. this.color = ( color && color.isColor ) ? color : new Color();
  10521. this.vertexColors = Array.isArray( color ) ? color : [];
  10522. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  10523. }
  10524. Object.assign( Face3.prototype, {
  10525. clone: function () {
  10526. return new this.constructor().copy( this );
  10527. },
  10528. copy: function ( source ) {
  10529. this.a = source.a;
  10530. this.b = source.b;
  10531. this.c = source.c;
  10532. this.normal.copy( source.normal );
  10533. this.color.copy( source.color );
  10534. this.materialIndex = source.materialIndex;
  10535. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  10536. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  10537. }
  10538. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  10539. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  10540. }
  10541. return this;
  10542. }
  10543. } );
  10544. /**
  10545. * @author mrdoob / http://mrdoob.com/
  10546. * @author alteredq / http://alteredqualia.com/
  10547. */
  10548. var materialId = 0;
  10549. function Material() {
  10550. Object.defineProperty( this, 'id', { value: materialId ++ } );
  10551. this.uuid = _Math.generateUUID();
  10552. this.name = '';
  10553. this.type = 'Material';
  10554. this.fog = true;
  10555. this.lights = true;
  10556. this.blending = NormalBlending;
  10557. this.side = FrontSide;
  10558. this.flatShading = false;
  10559. this.vertexTangents = false;
  10560. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  10561. this.opacity = 1;
  10562. this.transparent = false;
  10563. this.blendSrc = SrcAlphaFactor;
  10564. this.blendDst = OneMinusSrcAlphaFactor;
  10565. this.blendEquation = AddEquation;
  10566. this.blendSrcAlpha = null;
  10567. this.blendDstAlpha = null;
  10568. this.blendEquationAlpha = null;
  10569. this.depthFunc = LessEqualDepth;
  10570. this.depthTest = true;
  10571. this.depthWrite = true;
  10572. this.stencilWriteMask = 0xff;
  10573. this.stencilFunc = AlwaysStencilFunc;
  10574. this.stencilRef = 0;
  10575. this.stencilFuncMask = 0xff;
  10576. this.stencilFail = KeepStencilOp;
  10577. this.stencilZFail = KeepStencilOp;
  10578. this.stencilZPass = KeepStencilOp;
  10579. this.stencilWrite = false;
  10580. this.clippingPlanes = null;
  10581. this.clipIntersection = false;
  10582. this.clipShadows = false;
  10583. this.shadowSide = null;
  10584. this.colorWrite = true;
  10585. this.precision = null; // override the renderer's default precision for this material
  10586. this.polygonOffset = false;
  10587. this.polygonOffsetFactor = 0;
  10588. this.polygonOffsetUnits = 0;
  10589. this.dithering = false;
  10590. this.alphaTest = 0;
  10591. this.premultipliedAlpha = false;
  10592. this.visible = true;
  10593. this.toneMapped = true;
  10594. this.userData = {};
  10595. this.needsUpdate = true;
  10596. }
  10597. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10598. constructor: Material,
  10599. isMaterial: true,
  10600. onBeforeCompile: function () {},
  10601. setValues: function ( values ) {
  10602. if ( values === undefined ) { return; }
  10603. for ( var key in values ) {
  10604. var newValue = values[ key ];
  10605. if ( newValue === undefined ) {
  10606. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  10607. continue;
  10608. }
  10609. // for backward compatability if shading is set in the constructor
  10610. if ( key === 'shading' ) {
  10611. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  10612. this.flatShading = ( newValue === FlatShading ) ? true : false;
  10613. continue;
  10614. }
  10615. var currentValue = this[ key ];
  10616. if ( currentValue === undefined ) {
  10617. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  10618. continue;
  10619. }
  10620. if ( currentValue && currentValue.isColor ) {
  10621. currentValue.set( newValue );
  10622. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10623. currentValue.copy( newValue );
  10624. } else {
  10625. this[ key ] = newValue;
  10626. }
  10627. }
  10628. },
  10629. toJSON: function ( meta ) {
  10630. var isRoot = ( meta === undefined || typeof meta === 'string' );
  10631. if ( isRoot ) {
  10632. meta = {
  10633. textures: {},
  10634. images: {}
  10635. };
  10636. }
  10637. var data = {
  10638. metadata: {
  10639. version: 4.5,
  10640. type: 'Material',
  10641. generator: 'Material.toJSON'
  10642. }
  10643. };
  10644. // standard Material serialization
  10645. data.uuid = this.uuid;
  10646. data.type = this.type;
  10647. if ( this.name !== '' ) { data.name = this.name; }
  10648. if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); }
  10649. if ( this.roughness !== undefined ) { data.roughness = this.roughness; }
  10650. if ( this.metalness !== undefined ) { data.metalness = this.metalness; }
  10651. if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); }
  10652. if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); }
  10653. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; }
  10654. if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); }
  10655. if ( this.shininess !== undefined ) { data.shininess = this.shininess; }
  10656. if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; }
  10657. if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; }
  10658. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10659. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10660. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10661. }
  10662. if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; }
  10663. if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; }
  10664. if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; }
  10665. if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; }
  10666. if ( this.aoMap && this.aoMap.isTexture ) {
  10667. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10668. data.aoMapIntensity = this.aoMapIntensity;
  10669. }
  10670. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10671. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10672. data.bumpScale = this.bumpScale;
  10673. }
  10674. if ( this.normalMap && this.normalMap.isTexture ) {
  10675. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10676. data.normalMapType = this.normalMapType;
  10677. data.normalScale = this.normalScale.toArray();
  10678. }
  10679. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10680. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10681. data.displacementScale = this.displacementScale;
  10682. data.displacementBias = this.displacementBias;
  10683. }
  10684. if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; }
  10685. if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; }
  10686. if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; }
  10687. if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; }
  10688. if ( this.envMap && this.envMap.isTexture ) {
  10689. data.envMap = this.envMap.toJSON( meta ).uuid;
  10690. data.reflectivity = this.reflectivity; // Scale behind envMap
  10691. data.refractionRatio = this.refractionRatio;
  10692. if ( this.combine !== undefined ) { data.combine = this.combine; }
  10693. if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; }
  10694. }
  10695. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10696. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10697. }
  10698. if ( this.size !== undefined ) { data.size = this.size; }
  10699. if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; }
  10700. if ( this.blending !== NormalBlending ) { data.blending = this.blending; }
  10701. if ( this.flatShading === true ) { data.flatShading = this.flatShading; }
  10702. if ( this.side !== FrontSide ) { data.side = this.side; }
  10703. if ( this.vertexColors !== NoColors ) { data.vertexColors = this.vertexColors; }
  10704. if ( this.opacity < 1 ) { data.opacity = this.opacity; }
  10705. if ( this.transparent === true ) { data.transparent = this.transparent; }
  10706. data.depthFunc = this.depthFunc;
  10707. data.depthTest = this.depthTest;
  10708. data.depthWrite = this.depthWrite;
  10709. data.stencilWrite = this.stencilWrite;
  10710. data.stencilWriteMask = this.stencilWriteMask;
  10711. data.stencilFunc = this.stencilFunc;
  10712. data.stencilRef = this.stencilRef;
  10713. data.stencilFuncMask = this.stencilFuncMask;
  10714. data.stencilFail = this.stencilFail;
  10715. data.stencilZFail = this.stencilZFail;
  10716. data.stencilZPass = this.stencilZPass;
  10717. // rotation (SpriteMaterial)
  10718. if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; }
  10719. if ( this.polygonOffset === true ) { data.polygonOffset = true; }
  10720. if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; }
  10721. if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; }
  10722. if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; }
  10723. if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; }
  10724. if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; }
  10725. if ( this.scale !== undefined ) { data.scale = this.scale; }
  10726. if ( this.dithering === true ) { data.dithering = true; }
  10727. if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; }
  10728. if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; }
  10729. if ( this.wireframe === true ) { data.wireframe = this.wireframe; }
  10730. if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; }
  10731. if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; }
  10732. if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; }
  10733. if ( this.morphTargets === true ) { data.morphTargets = true; }
  10734. if ( this.morphNormals === true ) { data.morphNormals = true; }
  10735. if ( this.skinning === true ) { data.skinning = true; }
  10736. if ( this.visible === false ) { data.visible = false; }
  10737. if ( this.toneMapped === false ) { data.toneMapped = false; }
  10738. if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; }
  10739. // TODO: Copied from Object3D.toJSON
  10740. function extractFromCache( cache ) {
  10741. var values = [];
  10742. for ( var key in cache ) {
  10743. var data = cache[ key ];
  10744. delete data.metadata;
  10745. values.push( data );
  10746. }
  10747. return values;
  10748. }
  10749. if ( isRoot ) {
  10750. var textures = extractFromCache( meta.textures );
  10751. var images = extractFromCache( meta.images );
  10752. if ( textures.length > 0 ) { data.textures = textures; }
  10753. if ( images.length > 0 ) { data.images = images; }
  10754. }
  10755. return data;
  10756. },
  10757. clone: function () {
  10758. return new this.constructor().copy( this );
  10759. },
  10760. copy: function ( source ) {
  10761. this.name = source.name;
  10762. this.fog = source.fog;
  10763. this.lights = source.lights;
  10764. this.blending = source.blending;
  10765. this.side = source.side;
  10766. this.flatShading = source.flatShading;
  10767. this.vertexColors = source.vertexColors;
  10768. this.opacity = source.opacity;
  10769. this.transparent = source.transparent;
  10770. this.blendSrc = source.blendSrc;
  10771. this.blendDst = source.blendDst;
  10772. this.blendEquation = source.blendEquation;
  10773. this.blendSrcAlpha = source.blendSrcAlpha;
  10774. this.blendDstAlpha = source.blendDstAlpha;
  10775. this.blendEquationAlpha = source.blendEquationAlpha;
  10776. this.depthFunc = source.depthFunc;
  10777. this.depthTest = source.depthTest;
  10778. this.depthWrite = source.depthWrite;
  10779. this.stencilWrite = source.stencilWrite;
  10780. this.stencilWriteMask = source.stencilWriteMask;
  10781. this.stencilFunc = source.stencilFunc;
  10782. this.stencilRef = source.stencilRef;
  10783. this.stencilFuncMask = source.stencilFuncMask;
  10784. this.stencilFail = source.stencilFail;
  10785. this.stencilZFail = source.stencilZFail;
  10786. this.stencilZPass = source.stencilZPass;
  10787. this.colorWrite = source.colorWrite;
  10788. this.precision = source.precision;
  10789. this.polygonOffset = source.polygonOffset;
  10790. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10791. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10792. this.dithering = source.dithering;
  10793. this.alphaTest = source.alphaTest;
  10794. this.premultipliedAlpha = source.premultipliedAlpha;
  10795. this.visible = source.visible;
  10796. this.toneMapped = source.toneMapped;
  10797. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10798. this.clipShadows = source.clipShadows;
  10799. this.clipIntersection = source.clipIntersection;
  10800. var srcPlanes = source.clippingPlanes,
  10801. dstPlanes = null;
  10802. if ( srcPlanes !== null ) {
  10803. var n = srcPlanes.length;
  10804. dstPlanes = new Array( n );
  10805. for ( var i = 0; i !== n; ++ i )
  10806. { dstPlanes[ i ] = srcPlanes[ i ].clone(); }
  10807. }
  10808. this.clippingPlanes = dstPlanes;
  10809. this.shadowSide = source.shadowSide;
  10810. return this;
  10811. },
  10812. dispose: function () {
  10813. this.dispatchEvent( { type: 'dispose' } );
  10814. }
  10815. } );
  10816. /**
  10817. * @author mrdoob / http://mrdoob.com/
  10818. * @author alteredq / http://alteredqualia.com/
  10819. *
  10820. * parameters = {
  10821. * color: <hex>,
  10822. * opacity: <float>,
  10823. * map: new THREE.Texture( <Image> ),
  10824. *
  10825. * lightMap: new THREE.Texture( <Image> ),
  10826. * lightMapIntensity: <float>
  10827. *
  10828. * aoMap: new THREE.Texture( <Image> ),
  10829. * aoMapIntensity: <float>
  10830. *
  10831. * specularMap: new THREE.Texture( <Image> ),
  10832. *
  10833. * alphaMap: new THREE.Texture( <Image> ),
  10834. *
  10835. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  10836. * combine: THREE.Multiply,
  10837. * reflectivity: <float>,
  10838. * refractionRatio: <float>,
  10839. *
  10840. * depthTest: <bool>,
  10841. * depthWrite: <bool>,
  10842. *
  10843. * wireframe: <boolean>,
  10844. * wireframeLinewidth: <float>,
  10845. *
  10846. * skinning: <bool>,
  10847. * morphTargets: <bool>
  10848. * }
  10849. */
  10850. function MeshBasicMaterial( parameters ) {
  10851. Material.call( this );
  10852. this.type = 'MeshBasicMaterial';
  10853. this.color = new Color( 0xffffff ); // emissive
  10854. this.map = null;
  10855. this.lightMap = null;
  10856. this.lightMapIntensity = 1.0;
  10857. this.aoMap = null;
  10858. this.aoMapIntensity = 1.0;
  10859. this.specularMap = null;
  10860. this.alphaMap = null;
  10861. this.envMap = null;
  10862. this.combine = MultiplyOperation;
  10863. this.reflectivity = 1;
  10864. this.refractionRatio = 0.98;
  10865. this.wireframe = false;
  10866. this.wireframeLinewidth = 1;
  10867. this.wireframeLinecap = 'round';
  10868. this.wireframeLinejoin = 'round';
  10869. this.skinning = false;
  10870. this.morphTargets = false;
  10871. this.lights = false;
  10872. this.setValues( parameters );
  10873. }
  10874. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  10875. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  10876. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  10877. MeshBasicMaterial.prototype.copy = function ( source ) {
  10878. Material.prototype.copy.call( this, source );
  10879. this.color.copy( source.color );
  10880. this.map = source.map;
  10881. this.lightMap = source.lightMap;
  10882. this.lightMapIntensity = source.lightMapIntensity;
  10883. this.aoMap = source.aoMap;
  10884. this.aoMapIntensity = source.aoMapIntensity;
  10885. this.specularMap = source.specularMap;
  10886. this.alphaMap = source.alphaMap;
  10887. this.envMap = source.envMap;
  10888. this.combine = source.combine;
  10889. this.reflectivity = source.reflectivity;
  10890. this.refractionRatio = source.refractionRatio;
  10891. this.wireframe = source.wireframe;
  10892. this.wireframeLinewidth = source.wireframeLinewidth;
  10893. this.wireframeLinecap = source.wireframeLinecap;
  10894. this.wireframeLinejoin = source.wireframeLinejoin;
  10895. this.skinning = source.skinning;
  10896. this.morphTargets = source.morphTargets;
  10897. return this;
  10898. };
  10899. /**
  10900. * @author mrdoob / http://mrdoob.com/
  10901. */
  10902. function BufferAttribute( array, itemSize, normalized ) {
  10903. if ( Array.isArray( array ) ) {
  10904. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10905. }
  10906. this.name = '';
  10907. this.array = array;
  10908. this.itemSize = itemSize;
  10909. this.count = array !== undefined ? array.length / itemSize : 0;
  10910. this.normalized = normalized === true;
  10911. this.dynamic = false;
  10912. this.updateRange = { offset: 0, count: - 1 };
  10913. this.version = 0;
  10914. }
  10915. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  10916. set: function ( value ) {
  10917. if ( value === true ) { this.version ++; }
  10918. }
  10919. } );
  10920. Object.assign( BufferAttribute.prototype, {
  10921. isBufferAttribute: true,
  10922. onUploadCallback: function () {},
  10923. setDynamic: function ( value ) {
  10924. this.dynamic = value;
  10925. return this;
  10926. },
  10927. copy: function ( source ) {
  10928. this.name = source.name;
  10929. this.array = new source.array.constructor( source.array );
  10930. this.itemSize = source.itemSize;
  10931. this.count = source.count;
  10932. this.normalized = source.normalized;
  10933. this.dynamic = source.dynamic;
  10934. return this;
  10935. },
  10936. copyAt: function ( index1, attribute, index2 ) {
  10937. index1 *= this.itemSize;
  10938. index2 *= attribute.itemSize;
  10939. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  10940. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  10941. }
  10942. return this;
  10943. },
  10944. copyArray: function ( array ) {
  10945. this.array.set( array );
  10946. return this;
  10947. },
  10948. copyColorsArray: function ( colors ) {
  10949. var array = this.array, offset = 0;
  10950. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  10951. var color = colors[ i ];
  10952. if ( color === undefined ) {
  10953. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  10954. color = new Color();
  10955. }
  10956. array[ offset ++ ] = color.r;
  10957. array[ offset ++ ] = color.g;
  10958. array[ offset ++ ] = color.b;
  10959. }
  10960. return this;
  10961. },
  10962. copyVector2sArray: function ( vectors ) {
  10963. var array = this.array, offset = 0;
  10964. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10965. var vector = vectors[ i ];
  10966. if ( vector === undefined ) {
  10967. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  10968. vector = new Vector2();
  10969. }
  10970. array[ offset ++ ] = vector.x;
  10971. array[ offset ++ ] = vector.y;
  10972. }
  10973. return this;
  10974. },
  10975. copyVector3sArray: function ( vectors ) {
  10976. var array = this.array, offset = 0;
  10977. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10978. var vector = vectors[ i ];
  10979. if ( vector === undefined ) {
  10980. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  10981. vector = new Vector3();
  10982. }
  10983. array[ offset ++ ] = vector.x;
  10984. array[ offset ++ ] = vector.y;
  10985. array[ offset ++ ] = vector.z;
  10986. }
  10987. return this;
  10988. },
  10989. copyVector4sArray: function ( vectors ) {
  10990. var array = this.array, offset = 0;
  10991. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10992. var vector = vectors[ i ];
  10993. if ( vector === undefined ) {
  10994. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  10995. vector = new Vector4();
  10996. }
  10997. array[ offset ++ ] = vector.x;
  10998. array[ offset ++ ] = vector.y;
  10999. array[ offset ++ ] = vector.z;
  11000. array[ offset ++ ] = vector.w;
  11001. }
  11002. return this;
  11003. },
  11004. set: function ( value, offset ) {
  11005. if ( offset === undefined ) { offset = 0; }
  11006. this.array.set( value, offset );
  11007. return this;
  11008. },
  11009. getX: function ( index ) {
  11010. return this.array[ index * this.itemSize ];
  11011. },
  11012. setX: function ( index, x ) {
  11013. this.array[ index * this.itemSize ] = x;
  11014. return this;
  11015. },
  11016. getY: function ( index ) {
  11017. return this.array[ index * this.itemSize + 1 ];
  11018. },
  11019. setY: function ( index, y ) {
  11020. this.array[ index * this.itemSize + 1 ] = y;
  11021. return this;
  11022. },
  11023. getZ: function ( index ) {
  11024. return this.array[ index * this.itemSize + 2 ];
  11025. },
  11026. setZ: function ( index, z ) {
  11027. this.array[ index * this.itemSize + 2 ] = z;
  11028. return this;
  11029. },
  11030. getW: function ( index ) {
  11031. return this.array[ index * this.itemSize + 3 ];
  11032. },
  11033. setW: function ( index, w ) {
  11034. this.array[ index * this.itemSize + 3 ] = w;
  11035. return this;
  11036. },
  11037. setXY: function ( index, x, y ) {
  11038. index *= this.itemSize;
  11039. this.array[ index + 0 ] = x;
  11040. this.array[ index + 1 ] = y;
  11041. return this;
  11042. },
  11043. setXYZ: function ( index, x, y, z ) {
  11044. index *= this.itemSize;
  11045. this.array[ index + 0 ] = x;
  11046. this.array[ index + 1 ] = y;
  11047. this.array[ index + 2 ] = z;
  11048. return this;
  11049. },
  11050. setXYZW: function ( index, x, y, z, w ) {
  11051. index *= this.itemSize;
  11052. this.array[ index + 0 ] = x;
  11053. this.array[ index + 1 ] = y;
  11054. this.array[ index + 2 ] = z;
  11055. this.array[ index + 3 ] = w;
  11056. return this;
  11057. },
  11058. onUpload: function ( callback ) {
  11059. this.onUploadCallback = callback;
  11060. return this;
  11061. },
  11062. clone: function () {
  11063. return new this.constructor( this.array, this.itemSize ).copy( this );
  11064. },
  11065. toJSON: function () {
  11066. return {
  11067. itemSize: this.itemSize,
  11068. type: this.array.constructor.name,
  11069. array: Array.prototype.slice.call( this.array ),
  11070. normalized: this.normalized
  11071. };
  11072. }
  11073. } );
  11074. //
  11075. function Int8BufferAttribute( array, itemSize, normalized ) {
  11076. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  11077. }
  11078. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11079. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11080. function Uint8BufferAttribute( array, itemSize, normalized ) {
  11081. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11082. }
  11083. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11084. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11085. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  11086. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  11087. }
  11088. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11089. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11090. function Int16BufferAttribute( array, itemSize, normalized ) {
  11091. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  11092. }
  11093. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11094. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11095. function Uint16BufferAttribute( array, itemSize, normalized ) {
  11096. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  11097. }
  11098. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11099. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11100. function Int32BufferAttribute( array, itemSize, normalized ) {
  11101. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  11102. }
  11103. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11104. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11105. function Uint32BufferAttribute( array, itemSize, normalized ) {
  11106. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  11107. }
  11108. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11109. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11110. function Float32BufferAttribute( array, itemSize, normalized ) {
  11111. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  11112. }
  11113. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11114. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11115. function Float64BufferAttribute( array, itemSize, normalized ) {
  11116. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  11117. }
  11118. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11119. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11120. /**
  11121. * @author mrdoob / http://mrdoob.com/
  11122. */
  11123. function DirectGeometry() {
  11124. this.vertices = [];
  11125. this.normals = [];
  11126. this.colors = [];
  11127. this.uvs = [];
  11128. this.uvs2 = [];
  11129. this.groups = [];
  11130. this.morphTargets = {};
  11131. this.skinWeights = [];
  11132. this.skinIndices = [];
  11133. // this.lineDistances = [];
  11134. this.boundingBox = null;
  11135. this.boundingSphere = null;
  11136. // update flags
  11137. this.verticesNeedUpdate = false;
  11138. this.normalsNeedUpdate = false;
  11139. this.colorsNeedUpdate = false;
  11140. this.uvsNeedUpdate = false;
  11141. this.groupsNeedUpdate = false;
  11142. }
  11143. Object.assign( DirectGeometry.prototype, {
  11144. computeGroups: function ( geometry ) {
  11145. var group;
  11146. var groups = [];
  11147. var materialIndex = undefined;
  11148. var faces = geometry.faces;
  11149. for ( var i = 0; i < faces.length; i ++ ) {
  11150. var face = faces[ i ];
  11151. // materials
  11152. if ( face.materialIndex !== materialIndex ) {
  11153. materialIndex = face.materialIndex;
  11154. if ( group !== undefined ) {
  11155. group.count = ( i * 3 ) - group.start;
  11156. groups.push( group );
  11157. }
  11158. group = {
  11159. start: i * 3,
  11160. materialIndex: materialIndex
  11161. };
  11162. }
  11163. }
  11164. if ( group !== undefined ) {
  11165. group.count = ( i * 3 ) - group.start;
  11166. groups.push( group );
  11167. }
  11168. this.groups = groups;
  11169. },
  11170. fromGeometry: function ( geometry ) {
  11171. var faces = geometry.faces;
  11172. var vertices = geometry.vertices;
  11173. var faceVertexUvs = geometry.faceVertexUvs;
  11174. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11175. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11176. // morphs
  11177. var morphTargets = geometry.morphTargets;
  11178. var morphTargetsLength = morphTargets.length;
  11179. var morphTargetsPosition;
  11180. if ( morphTargetsLength > 0 ) {
  11181. morphTargetsPosition = [];
  11182. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11183. morphTargetsPosition[ i ] = {
  11184. name: morphTargets[ i ].name,
  11185. data: []
  11186. };
  11187. }
  11188. this.morphTargets.position = morphTargetsPosition;
  11189. }
  11190. var morphNormals = geometry.morphNormals;
  11191. var morphNormalsLength = morphNormals.length;
  11192. var morphTargetsNormal;
  11193. if ( morphNormalsLength > 0 ) {
  11194. morphTargetsNormal = [];
  11195. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11196. morphTargetsNormal[ i ] = {
  11197. name: morphNormals[ i ].name,
  11198. data: []
  11199. };
  11200. }
  11201. this.morphTargets.normal = morphTargetsNormal;
  11202. }
  11203. // skins
  11204. var skinIndices = geometry.skinIndices;
  11205. var skinWeights = geometry.skinWeights;
  11206. var hasSkinIndices = skinIndices.length === vertices.length;
  11207. var hasSkinWeights = skinWeights.length === vertices.length;
  11208. //
  11209. if ( vertices.length > 0 && faces.length === 0 ) {
  11210. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  11211. }
  11212. for ( var i = 0; i < faces.length; i ++ ) {
  11213. var face = faces[ i ];
  11214. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11215. var vertexNormals = face.vertexNormals;
  11216. if ( vertexNormals.length === 3 ) {
  11217. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11218. } else {
  11219. var normal = face.normal;
  11220. this.normals.push( normal, normal, normal );
  11221. }
  11222. var vertexColors = face.vertexColors;
  11223. if ( vertexColors.length === 3 ) {
  11224. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11225. } else {
  11226. var color = face.color;
  11227. this.colors.push( color, color, color );
  11228. }
  11229. if ( hasFaceVertexUv === true ) {
  11230. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11231. if ( vertexUvs !== undefined ) {
  11232. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11233. } else {
  11234. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11235. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11236. }
  11237. }
  11238. if ( hasFaceVertexUv2 === true ) {
  11239. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11240. if ( vertexUvs !== undefined ) {
  11241. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11242. } else {
  11243. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11244. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11245. }
  11246. }
  11247. // morphs
  11248. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11249. var morphTarget = morphTargets[ j ].vertices;
  11250. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11251. }
  11252. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11253. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11254. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  11255. }
  11256. // skins
  11257. if ( hasSkinIndices ) {
  11258. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11259. }
  11260. if ( hasSkinWeights ) {
  11261. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11262. }
  11263. }
  11264. this.computeGroups( geometry );
  11265. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11266. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11267. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11268. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11269. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11270. if ( geometry.boundingSphere !== null ) {
  11271. this.boundingSphere = geometry.boundingSphere.clone();
  11272. }
  11273. if ( geometry.boundingBox !== null ) {
  11274. this.boundingBox = geometry.boundingBox.clone();
  11275. }
  11276. return this;
  11277. }
  11278. } );
  11279. /**
  11280. * @author mrdoob / http://mrdoob.com/
  11281. */
  11282. function arrayMax( array ) {
  11283. if ( array.length === 0 ) { return - Infinity; }
  11284. var max = array[ 0 ];
  11285. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11286. if ( array[ i ] > max ) { max = array[ i ]; }
  11287. }
  11288. return max;
  11289. }
  11290. /**
  11291. * @author alteredq / http://alteredqualia.com/
  11292. * @author mrdoob / http://mrdoob.com/
  11293. */
  11294. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11295. var _m1$2 = new Matrix4();
  11296. var _obj = new Object3D();
  11297. var _offset = new Vector3();
  11298. var _box$1 = new Box3();
  11299. var _boxMorphTargets = new Box3();
  11300. var _vector$4 = new Vector3();
  11301. function BufferGeometry() {
  11302. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  11303. this.uuid = _Math.generateUUID();
  11304. this.name = '';
  11305. this.type = 'BufferGeometry';
  11306. this.index = null;
  11307. this.attributes = {};
  11308. this.morphAttributes = {};
  11309. this.groups = [];
  11310. this.boundingBox = null;
  11311. this.boundingSphere = null;
  11312. this.drawRange = { start: 0, count: Infinity };
  11313. this.userData = {};
  11314. }
  11315. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11316. constructor: BufferGeometry,
  11317. isBufferGeometry: true,
  11318. getIndex: function () {
  11319. return this.index;
  11320. },
  11321. setIndex: function ( index ) {
  11322. if ( Array.isArray( index ) ) {
  11323. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11324. } else {
  11325. this.index = index;
  11326. }
  11327. },
  11328. addAttribute: function ( name, attribute ) {
  11329. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  11330. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  11331. return this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  11332. }
  11333. if ( name === 'index' ) {
  11334. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  11335. this.setIndex( attribute );
  11336. return this;
  11337. }
  11338. return this.setAttribute( name, attribute );
  11339. },
  11340. getAttribute: function ( name ) {
  11341. return this.attributes[ name ];
  11342. },
  11343. setAttribute: function ( name, attribute ) {
  11344. this.attributes[ name ] = attribute;
  11345. return this;
  11346. },
  11347. removeAttribute: function ( name ) {
  11348. delete this.attributes[ name ];
  11349. return this;
  11350. },
  11351. addGroup: function ( start, count, materialIndex ) {
  11352. this.groups.push( {
  11353. start: start,
  11354. count: count,
  11355. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11356. } );
  11357. },
  11358. clearGroups: function () {
  11359. this.groups = [];
  11360. },
  11361. setDrawRange: function ( start, count ) {
  11362. this.drawRange.start = start;
  11363. this.drawRange.count = count;
  11364. },
  11365. applyMatrix: function ( matrix ) {
  11366. var position = this.attributes.position;
  11367. if ( position !== undefined ) {
  11368. matrix.applyToBufferAttribute( position );
  11369. position.needsUpdate = true;
  11370. }
  11371. var normal = this.attributes.normal;
  11372. if ( normal !== undefined ) {
  11373. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11374. normalMatrix.applyToBufferAttribute( normal );
  11375. normal.needsUpdate = true;
  11376. }
  11377. var tangent = this.attributes.tangent;
  11378. if ( tangent !== undefined ) {
  11379. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11380. // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  11381. normalMatrix.applyToBufferAttribute( tangent );
  11382. tangent.needsUpdate = true;
  11383. }
  11384. if ( this.boundingBox !== null ) {
  11385. this.computeBoundingBox();
  11386. }
  11387. if ( this.boundingSphere !== null ) {
  11388. this.computeBoundingSphere();
  11389. }
  11390. return this;
  11391. },
  11392. rotateX: function ( angle ) {
  11393. // rotate geometry around world x-axis
  11394. _m1$2.makeRotationX( angle );
  11395. this.applyMatrix( _m1$2 );
  11396. return this;
  11397. },
  11398. rotateY: function ( angle ) {
  11399. // rotate geometry around world y-axis
  11400. _m1$2.makeRotationY( angle );
  11401. this.applyMatrix( _m1$2 );
  11402. return this;
  11403. },
  11404. rotateZ: function ( angle ) {
  11405. // rotate geometry around world z-axis
  11406. _m1$2.makeRotationZ( angle );
  11407. this.applyMatrix( _m1$2 );
  11408. return this;
  11409. },
  11410. translate: function ( x, y, z ) {
  11411. // translate geometry
  11412. _m1$2.makeTranslation( x, y, z );
  11413. this.applyMatrix( _m1$2 );
  11414. return this;
  11415. },
  11416. scale: function ( x, y, z ) {
  11417. // scale geometry
  11418. _m1$2.makeScale( x, y, z );
  11419. this.applyMatrix( _m1$2 );
  11420. return this;
  11421. },
  11422. lookAt: function ( vector ) {
  11423. _obj.lookAt( vector );
  11424. _obj.updateMatrix();
  11425. this.applyMatrix( _obj.matrix );
  11426. return this;
  11427. },
  11428. center: function () {
  11429. this.computeBoundingBox();
  11430. this.boundingBox.getCenter( _offset ).negate();
  11431. this.translate( _offset.x, _offset.y, _offset.z );
  11432. return this;
  11433. },
  11434. setFromObject: function ( object ) {
  11435. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11436. var geometry = object.geometry;
  11437. if ( object.isPoints || object.isLine ) {
  11438. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11439. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11440. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11441. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11442. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11443. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11444. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11445. }
  11446. if ( geometry.boundingSphere !== null ) {
  11447. this.boundingSphere = geometry.boundingSphere.clone();
  11448. }
  11449. if ( geometry.boundingBox !== null ) {
  11450. this.boundingBox = geometry.boundingBox.clone();
  11451. }
  11452. } else if ( object.isMesh ) {
  11453. if ( geometry && geometry.isGeometry ) {
  11454. this.fromGeometry( geometry );
  11455. }
  11456. }
  11457. return this;
  11458. },
  11459. setFromPoints: function ( points ) {
  11460. var position = [];
  11461. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11462. var point = points[ i ];
  11463. position.push( point.x, point.y, point.z || 0 );
  11464. }
  11465. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11466. return this;
  11467. },
  11468. updateFromObject: function ( object ) {
  11469. var geometry = object.geometry;
  11470. if ( object.isMesh ) {
  11471. var direct = geometry.__directGeometry;
  11472. if ( geometry.elementsNeedUpdate === true ) {
  11473. direct = undefined;
  11474. geometry.elementsNeedUpdate = false;
  11475. }
  11476. if ( direct === undefined ) {
  11477. return this.fromGeometry( geometry );
  11478. }
  11479. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11480. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11481. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11482. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11483. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11484. geometry.verticesNeedUpdate = false;
  11485. geometry.normalsNeedUpdate = false;
  11486. geometry.colorsNeedUpdate = false;
  11487. geometry.uvsNeedUpdate = false;
  11488. geometry.groupsNeedUpdate = false;
  11489. geometry = direct;
  11490. }
  11491. var attribute;
  11492. if ( geometry.verticesNeedUpdate === true ) {
  11493. attribute = this.attributes.position;
  11494. if ( attribute !== undefined ) {
  11495. attribute.copyVector3sArray( geometry.vertices );
  11496. attribute.needsUpdate = true;
  11497. }
  11498. geometry.verticesNeedUpdate = false;
  11499. }
  11500. if ( geometry.normalsNeedUpdate === true ) {
  11501. attribute = this.attributes.normal;
  11502. if ( attribute !== undefined ) {
  11503. attribute.copyVector3sArray( geometry.normals );
  11504. attribute.needsUpdate = true;
  11505. }
  11506. geometry.normalsNeedUpdate = false;
  11507. }
  11508. if ( geometry.colorsNeedUpdate === true ) {
  11509. attribute = this.attributes.color;
  11510. if ( attribute !== undefined ) {
  11511. attribute.copyColorsArray( geometry.colors );
  11512. attribute.needsUpdate = true;
  11513. }
  11514. geometry.colorsNeedUpdate = false;
  11515. }
  11516. if ( geometry.uvsNeedUpdate ) {
  11517. attribute = this.attributes.uv;
  11518. if ( attribute !== undefined ) {
  11519. attribute.copyVector2sArray( geometry.uvs );
  11520. attribute.needsUpdate = true;
  11521. }
  11522. geometry.uvsNeedUpdate = false;
  11523. }
  11524. if ( geometry.lineDistancesNeedUpdate ) {
  11525. attribute = this.attributes.lineDistance;
  11526. if ( attribute !== undefined ) {
  11527. attribute.copyArray( geometry.lineDistances );
  11528. attribute.needsUpdate = true;
  11529. }
  11530. geometry.lineDistancesNeedUpdate = false;
  11531. }
  11532. if ( geometry.groupsNeedUpdate ) {
  11533. geometry.computeGroups( object.geometry );
  11534. this.groups = geometry.groups;
  11535. geometry.groupsNeedUpdate = false;
  11536. }
  11537. return this;
  11538. },
  11539. fromGeometry: function ( geometry ) {
  11540. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11541. return this.fromDirectGeometry( geometry.__directGeometry );
  11542. },
  11543. fromDirectGeometry: function ( geometry ) {
  11544. var positions = new Float32Array( geometry.vertices.length * 3 );
  11545. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11546. if ( geometry.normals.length > 0 ) {
  11547. var normals = new Float32Array( geometry.normals.length * 3 );
  11548. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11549. }
  11550. if ( geometry.colors.length > 0 ) {
  11551. var colors = new Float32Array( geometry.colors.length * 3 );
  11552. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11553. }
  11554. if ( geometry.uvs.length > 0 ) {
  11555. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11556. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11557. }
  11558. if ( geometry.uvs2.length > 0 ) {
  11559. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11560. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11561. }
  11562. // groups
  11563. this.groups = geometry.groups;
  11564. // morphs
  11565. for ( var name in geometry.morphTargets ) {
  11566. var array = [];
  11567. var morphTargets = geometry.morphTargets[ name ];
  11568. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11569. var morphTarget = morphTargets[ i ];
  11570. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  11571. attribute.name = morphTarget.name;
  11572. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  11573. }
  11574. this.morphAttributes[ name ] = array;
  11575. }
  11576. // skinning
  11577. if ( geometry.skinIndices.length > 0 ) {
  11578. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11579. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11580. }
  11581. if ( geometry.skinWeights.length > 0 ) {
  11582. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11583. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11584. }
  11585. //
  11586. if ( geometry.boundingSphere !== null ) {
  11587. this.boundingSphere = geometry.boundingSphere.clone();
  11588. }
  11589. if ( geometry.boundingBox !== null ) {
  11590. this.boundingBox = geometry.boundingBox.clone();
  11591. }
  11592. return this;
  11593. },
  11594. computeBoundingBox: function () {
  11595. if ( this.boundingBox === null ) {
  11596. this.boundingBox = new Box3();
  11597. }
  11598. var position = this.attributes.position;
  11599. var morphAttributesPosition = this.morphAttributes.position;
  11600. if ( position !== undefined ) {
  11601. this.boundingBox.setFromBufferAttribute( position );
  11602. // process morph attributes if present
  11603. if ( morphAttributesPosition ) {
  11604. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11605. var morphAttribute = morphAttributesPosition[ i ];
  11606. _box$1.setFromBufferAttribute( morphAttribute );
  11607. this.boundingBox.expandByPoint( _box$1.min );
  11608. this.boundingBox.expandByPoint( _box$1.max );
  11609. }
  11610. }
  11611. } else {
  11612. this.boundingBox.makeEmpty();
  11613. }
  11614. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11615. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11616. }
  11617. },
  11618. computeBoundingSphere: function () {
  11619. if ( this.boundingSphere === null ) {
  11620. this.boundingSphere = new Sphere();
  11621. }
  11622. var position = this.attributes.position;
  11623. var morphAttributesPosition = this.morphAttributes.position;
  11624. if ( position ) {
  11625. // first, find the center of the bounding sphere
  11626. var center = this.boundingSphere.center;
  11627. _box$1.setFromBufferAttribute( position );
  11628. // process morph attributes if present
  11629. if ( morphAttributesPosition ) {
  11630. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11631. var morphAttribute = morphAttributesPosition[ i ];
  11632. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11633. _box$1.expandByPoint( _boxMorphTargets.min );
  11634. _box$1.expandByPoint( _boxMorphTargets.max );
  11635. }
  11636. }
  11637. _box$1.getCenter( center );
  11638. // second, try to find a boundingSphere with a radius smaller than the
  11639. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11640. var maxRadiusSq = 0;
  11641. for ( var i = 0, il = position.count; i < il; i ++ ) {
  11642. _vector$4.fromBufferAttribute( position, i );
  11643. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11644. }
  11645. // process morph attributes if present
  11646. if ( morphAttributesPosition ) {
  11647. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11648. var morphAttribute = morphAttributesPosition[ i ];
  11649. for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11650. _vector$4.fromBufferAttribute( morphAttribute, j );
  11651. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11652. }
  11653. }
  11654. }
  11655. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11656. if ( isNaN( this.boundingSphere.radius ) ) {
  11657. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11658. }
  11659. }
  11660. },
  11661. computeFaceNormals: function () {
  11662. // backwards compatibility
  11663. },
  11664. computeVertexNormals: function () {
  11665. var index = this.index;
  11666. var attributes = this.attributes;
  11667. if ( attributes.position ) {
  11668. var positions = attributes.position.array;
  11669. if ( attributes.normal === undefined ) {
  11670. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  11671. } else {
  11672. // reset existing normals to zero
  11673. var array = attributes.normal.array;
  11674. for ( var i = 0, il = array.length; i < il; i ++ ) {
  11675. array[ i ] = 0;
  11676. }
  11677. }
  11678. var normals = attributes.normal.array;
  11679. var vA, vB, vC;
  11680. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11681. var cb = new Vector3(), ab = new Vector3();
  11682. // indexed elements
  11683. if ( index ) {
  11684. var indices = index.array;
  11685. for ( var i = 0, il = index.count; i < il; i += 3 ) {
  11686. vA = indices[ i + 0 ] * 3;
  11687. vB = indices[ i + 1 ] * 3;
  11688. vC = indices[ i + 2 ] * 3;
  11689. pA.fromArray( positions, vA );
  11690. pB.fromArray( positions, vB );
  11691. pC.fromArray( positions, vC );
  11692. cb.subVectors( pC, pB );
  11693. ab.subVectors( pA, pB );
  11694. cb.cross( ab );
  11695. normals[ vA ] += cb.x;
  11696. normals[ vA + 1 ] += cb.y;
  11697. normals[ vA + 2 ] += cb.z;
  11698. normals[ vB ] += cb.x;
  11699. normals[ vB + 1 ] += cb.y;
  11700. normals[ vB + 2 ] += cb.z;
  11701. normals[ vC ] += cb.x;
  11702. normals[ vC + 1 ] += cb.y;
  11703. normals[ vC + 2 ] += cb.z;
  11704. }
  11705. } else {
  11706. // non-indexed elements (unconnected triangle soup)
  11707. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  11708. pA.fromArray( positions, i );
  11709. pB.fromArray( positions, i + 3 );
  11710. pC.fromArray( positions, i + 6 );
  11711. cb.subVectors( pC, pB );
  11712. ab.subVectors( pA, pB );
  11713. cb.cross( ab );
  11714. normals[ i ] = cb.x;
  11715. normals[ i + 1 ] = cb.y;
  11716. normals[ i + 2 ] = cb.z;
  11717. normals[ i + 3 ] = cb.x;
  11718. normals[ i + 4 ] = cb.y;
  11719. normals[ i + 5 ] = cb.z;
  11720. normals[ i + 6 ] = cb.x;
  11721. normals[ i + 7 ] = cb.y;
  11722. normals[ i + 8 ] = cb.z;
  11723. }
  11724. }
  11725. this.normalizeNormals();
  11726. attributes.normal.needsUpdate = true;
  11727. }
  11728. },
  11729. merge: function ( geometry, offset ) {
  11730. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11731. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11732. return;
  11733. }
  11734. if ( offset === undefined ) {
  11735. offset = 0;
  11736. console.warn(
  11737. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11738. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11739. );
  11740. }
  11741. var attributes = this.attributes;
  11742. for ( var key in attributes ) {
  11743. if ( geometry.attributes[ key ] === undefined ) { continue; }
  11744. var attribute1 = attributes[ key ];
  11745. var attributeArray1 = attribute1.array;
  11746. var attribute2 = geometry.attributes[ key ];
  11747. var attributeArray2 = attribute2.array;
  11748. var attributeOffset = attribute2.itemSize * offset;
  11749. var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  11750. for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  11751. attributeArray1[ j ] = attributeArray2[ i ];
  11752. }
  11753. }
  11754. return this;
  11755. },
  11756. normalizeNormals: function () {
  11757. var normals = this.attributes.normal;
  11758. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11759. _vector$4.x = normals.getX( i );
  11760. _vector$4.y = normals.getY( i );
  11761. _vector$4.z = normals.getZ( i );
  11762. _vector$4.normalize();
  11763. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  11764. }
  11765. },
  11766. toNonIndexed: function () {
  11767. function convertBufferAttribute( attribute, indices ) {
  11768. var array = attribute.array;
  11769. var itemSize = attribute.itemSize;
  11770. var array2 = new array.constructor( indices.length * itemSize );
  11771. var index = 0, index2 = 0;
  11772. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11773. index = indices[ i ] * itemSize;
  11774. for ( var j = 0; j < itemSize; j ++ ) {
  11775. array2[ index2 ++ ] = array[ index ++ ];
  11776. }
  11777. }
  11778. return new BufferAttribute( array2, itemSize );
  11779. }
  11780. //
  11781. if ( this.index === null ) {
  11782. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  11783. return this;
  11784. }
  11785. var geometry2 = new BufferGeometry();
  11786. var indices = this.index.array;
  11787. var attributes = this.attributes;
  11788. // attributes
  11789. for ( var name in attributes ) {
  11790. var attribute = attributes[ name ];
  11791. var newAttribute = convertBufferAttribute( attribute, indices );
  11792. geometry2.addAttribute( name, newAttribute );
  11793. }
  11794. // morph attributes
  11795. var morphAttributes = this.morphAttributes;
  11796. for ( name in morphAttributes ) {
  11797. var morphArray = [];
  11798. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11799. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11800. var attribute = morphAttribute[ i ];
  11801. var newAttribute = convertBufferAttribute( attribute, indices );
  11802. morphArray.push( newAttribute );
  11803. }
  11804. geometry2.morphAttributes[ name ] = morphArray;
  11805. }
  11806. // groups
  11807. var groups = this.groups;
  11808. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  11809. var group = groups[ i ];
  11810. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11811. }
  11812. return geometry2;
  11813. },
  11814. toJSON: function () {
  11815. var data = {
  11816. metadata: {
  11817. version: 4.5,
  11818. type: 'BufferGeometry',
  11819. generator: 'BufferGeometry.toJSON'
  11820. }
  11821. };
  11822. // standard BufferGeometry serialization
  11823. data.uuid = this.uuid;
  11824. data.type = this.type;
  11825. if ( this.name !== '' ) { data.name = this.name; }
  11826. if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; }
  11827. if ( this.parameters !== undefined ) {
  11828. var parameters = this.parameters;
  11829. for ( var key in parameters ) {
  11830. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  11831. }
  11832. return data;
  11833. }
  11834. data.data = { attributes: {} };
  11835. var index = this.index;
  11836. if ( index !== null ) {
  11837. data.data.index = {
  11838. type: index.array.constructor.name,
  11839. array: Array.prototype.slice.call( index.array )
  11840. };
  11841. }
  11842. var attributes = this.attributes;
  11843. for ( var key in attributes ) {
  11844. var attribute = attributes[ key ];
  11845. var attributeData = attribute.toJSON();
  11846. if ( attribute.name !== '' ) { attributeData.name = attribute.name; }
  11847. data.data.attributes[ key ] = attributeData;
  11848. }
  11849. var morphAttributes = {};
  11850. var hasMorphAttributes = false;
  11851. for ( var key in this.morphAttributes ) {
  11852. var attributeArray = this.morphAttributes[ key ];
  11853. var array = [];
  11854. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  11855. var attribute = attributeArray[ i ];
  11856. var attributeData = attribute.toJSON();
  11857. if ( attribute.name !== '' ) { attributeData.name = attribute.name; }
  11858. array.push( attributeData );
  11859. }
  11860. if ( array.length > 0 ) {
  11861. morphAttributes[ key ] = array;
  11862. hasMorphAttributes = true;
  11863. }
  11864. }
  11865. if ( hasMorphAttributes ) { data.data.morphAttributes = morphAttributes; }
  11866. var groups = this.groups;
  11867. if ( groups.length > 0 ) {
  11868. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11869. }
  11870. var boundingSphere = this.boundingSphere;
  11871. if ( boundingSphere !== null ) {
  11872. data.data.boundingSphere = {
  11873. center: boundingSphere.center.toArray(),
  11874. radius: boundingSphere.radius
  11875. };
  11876. }
  11877. return data;
  11878. },
  11879. clone: function () {
  11880. /*
  11881. // Handle primitives
  11882. var parameters = this.parameters;
  11883. if ( parameters !== undefined ) {
  11884. var values = [];
  11885. for ( var key in parameters ) {
  11886. values.push( parameters[ key ] );
  11887. }
  11888. var geometry = Object.create( this.constructor.prototype );
  11889. this.constructor.apply( geometry, values );
  11890. return geometry;
  11891. }
  11892. return new this.constructor().copy( this );
  11893. */
  11894. return new BufferGeometry().copy( this );
  11895. },
  11896. copy: function ( source ) {
  11897. var name, i, l;
  11898. // reset
  11899. this.index = null;
  11900. this.attributes = {};
  11901. this.morphAttributes = {};
  11902. this.groups = [];
  11903. this.boundingBox = null;
  11904. this.boundingSphere = null;
  11905. // name
  11906. this.name = source.name;
  11907. // index
  11908. var index = source.index;
  11909. if ( index !== null ) {
  11910. this.setIndex( index.clone() );
  11911. }
  11912. // attributes
  11913. var attributes = source.attributes;
  11914. for ( name in attributes ) {
  11915. var attribute = attributes[ name ];
  11916. this.addAttribute( name, attribute.clone() );
  11917. }
  11918. // morph attributes
  11919. var morphAttributes = source.morphAttributes;
  11920. for ( name in morphAttributes ) {
  11921. var array = [];
  11922. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11923. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11924. array.push( morphAttribute[ i ].clone() );
  11925. }
  11926. this.morphAttributes[ name ] = array;
  11927. }
  11928. // groups
  11929. var groups = source.groups;
  11930. for ( i = 0, l = groups.length; i < l; i ++ ) {
  11931. var group = groups[ i ];
  11932. this.addGroup( group.start, group.count, group.materialIndex );
  11933. }
  11934. // bounding box
  11935. var boundingBox = source.boundingBox;
  11936. if ( boundingBox !== null ) {
  11937. this.boundingBox = boundingBox.clone();
  11938. }
  11939. // bounding sphere
  11940. var boundingSphere = source.boundingSphere;
  11941. if ( boundingSphere !== null ) {
  11942. this.boundingSphere = boundingSphere.clone();
  11943. }
  11944. // draw range
  11945. this.drawRange.start = source.drawRange.start;
  11946. this.drawRange.count = source.drawRange.count;
  11947. // user data
  11948. this.userData = source.userData;
  11949. return this;
  11950. },
  11951. dispose: function () {
  11952. this.dispatchEvent( { type: 'dispose' } );
  11953. }
  11954. } );
  11955. /**
  11956. * @author mrdoob / http://mrdoob.com/
  11957. * @author alteredq / http://alteredqualia.com/
  11958. * @author mikael emtinger / http://gomo.se/
  11959. * @author jonobr1 / http://jonobr1.com/
  11960. */
  11961. var _inverseMatrix = new Matrix4();
  11962. var _ray = new Ray();
  11963. var _sphere = new Sphere();
  11964. var _vA = new Vector3();
  11965. var _vB = new Vector3();
  11966. var _vC = new Vector3();
  11967. var _tempA = new Vector3();
  11968. var _tempB = new Vector3();
  11969. var _tempC = new Vector3();
  11970. var _morphA = new Vector3();
  11971. var _morphB = new Vector3();
  11972. var _morphC = new Vector3();
  11973. var _uvA = new Vector2();
  11974. var _uvB = new Vector2();
  11975. var _uvC = new Vector2();
  11976. var _intersectionPoint = new Vector3();
  11977. var _intersectionPointWorld = new Vector3();
  11978. function Mesh( geometry, material ) {
  11979. Object3D.call( this );
  11980. this.type = 'Mesh';
  11981. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  11982. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  11983. this.drawMode = TrianglesDrawMode;
  11984. this.updateMorphTargets();
  11985. }
  11986. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  11987. constructor: Mesh,
  11988. isMesh: true,
  11989. setDrawMode: function ( value ) {
  11990. this.drawMode = value;
  11991. },
  11992. copy: function ( source ) {
  11993. Object3D.prototype.copy.call( this, source );
  11994. this.drawMode = source.drawMode;
  11995. if ( source.morphTargetInfluences !== undefined ) {
  11996. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  11997. }
  11998. if ( source.morphTargetDictionary !== undefined ) {
  11999. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12000. }
  12001. return this;
  12002. },
  12003. updateMorphTargets: function () {
  12004. var geometry = this.geometry;
  12005. var m, ml, name;
  12006. if ( geometry.isBufferGeometry ) {
  12007. var morphAttributes = geometry.morphAttributes;
  12008. var keys = Object.keys( morphAttributes );
  12009. if ( keys.length > 0 ) {
  12010. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12011. if ( morphAttribute !== undefined ) {
  12012. this.morphTargetInfluences = [];
  12013. this.morphTargetDictionary = {};
  12014. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12015. name = morphAttribute[ m ].name || String( m );
  12016. this.morphTargetInfluences.push( 0 );
  12017. this.morphTargetDictionary[ name ] = m;
  12018. }
  12019. }
  12020. }
  12021. } else {
  12022. var morphTargets = geometry.morphTargets;
  12023. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12024. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  12025. }
  12026. }
  12027. },
  12028. raycast: function ( raycaster, intersects ) {
  12029. var geometry = this.geometry;
  12030. var material = this.material;
  12031. var matrixWorld = this.matrixWorld;
  12032. if ( material === undefined ) { return; }
  12033. // Checking boundingSphere distance to ray
  12034. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  12035. _sphere.copy( geometry.boundingSphere );
  12036. _sphere.applyMatrix4( matrixWorld );
  12037. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; }
  12038. //
  12039. _inverseMatrix.getInverse( matrixWorld );
  12040. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  12041. // Check boundingBox before continuing
  12042. if ( geometry.boundingBox !== null ) {
  12043. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; }
  12044. }
  12045. var intersection;
  12046. if ( geometry.isBufferGeometry ) {
  12047. var a, b, c;
  12048. var index = geometry.index;
  12049. var position = geometry.attributes.position;
  12050. var morphPosition = geometry.morphAttributes.position;
  12051. var uv = geometry.attributes.uv;
  12052. var uv2 = geometry.attributes.uv2;
  12053. var groups = geometry.groups;
  12054. var drawRange = geometry.drawRange;
  12055. var i, j, il, jl;
  12056. var group, groupMaterial;
  12057. var start, end;
  12058. if ( index !== null ) {
  12059. // indexed buffer geometry
  12060. if ( Array.isArray( material ) ) {
  12061. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12062. group = groups[ i ];
  12063. groupMaterial = material[ group.materialIndex ];
  12064. start = Math.max( group.start, drawRange.start );
  12065. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12066. for ( j = start, jl = end; j < jl; j += 3 ) {
  12067. a = index.getX( j );
  12068. b = index.getX( j + 1 );
  12069. c = index.getX( j + 2 );
  12070. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c );
  12071. if ( intersection ) {
  12072. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12073. intersection.face.materialIndex = group.materialIndex;
  12074. intersects.push( intersection );
  12075. }
  12076. }
  12077. }
  12078. } else {
  12079. start = Math.max( 0, drawRange.start );
  12080. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12081. for ( i = start, il = end; i < il; i += 3 ) {
  12082. a = index.getX( i );
  12083. b = index.getX( i + 1 );
  12084. c = index.getX( i + 2 );
  12085. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c );
  12086. if ( intersection ) {
  12087. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12088. intersects.push( intersection );
  12089. }
  12090. }
  12091. }
  12092. } else if ( position !== undefined ) {
  12093. // non-indexed buffer geometry
  12094. if ( Array.isArray( material ) ) {
  12095. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12096. group = groups[ i ];
  12097. groupMaterial = material[ group.materialIndex ];
  12098. start = Math.max( group.start, drawRange.start );
  12099. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12100. for ( j = start, jl = end; j < jl; j += 3 ) {
  12101. a = j;
  12102. b = j + 1;
  12103. c = j + 2;
  12104. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c );
  12105. if ( intersection ) {
  12106. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12107. intersection.face.materialIndex = group.materialIndex;
  12108. intersects.push( intersection );
  12109. }
  12110. }
  12111. }
  12112. } else {
  12113. start = Math.max( 0, drawRange.start );
  12114. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12115. for ( i = start, il = end; i < il; i += 3 ) {
  12116. a = i;
  12117. b = i + 1;
  12118. c = i + 2;
  12119. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c );
  12120. if ( intersection ) {
  12121. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12122. intersects.push( intersection );
  12123. }
  12124. }
  12125. }
  12126. }
  12127. } else if ( geometry.isGeometry ) {
  12128. var fvA, fvB, fvC;
  12129. var isMultiMaterial = Array.isArray( material );
  12130. var vertices = geometry.vertices;
  12131. var faces = geometry.faces;
  12132. var uvs;
  12133. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12134. if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; }
  12135. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12136. var face = faces[ f ];
  12137. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12138. if ( faceMaterial === undefined ) { continue; }
  12139. fvA = vertices[ face.a ];
  12140. fvB = vertices[ face.b ];
  12141. fvC = vertices[ face.c ];
  12142. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  12143. if ( intersection ) {
  12144. if ( uvs && uvs[ f ] ) {
  12145. var uvs_f = uvs[ f ];
  12146. _uvA.copy( uvs_f[ 0 ] );
  12147. _uvB.copy( uvs_f[ 1 ] );
  12148. _uvC.copy( uvs_f[ 2 ] );
  12149. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
  12150. }
  12151. intersection.face = face;
  12152. intersection.faceIndex = f;
  12153. intersects.push( intersection );
  12154. }
  12155. }
  12156. }
  12157. },
  12158. clone: function () {
  12159. return new this.constructor( this.geometry, this.material ).copy( this );
  12160. }
  12161. } );
  12162. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12163. var intersect;
  12164. if ( material.side === BackSide ) {
  12165. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12166. } else {
  12167. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12168. }
  12169. if ( intersect === null ) { return null; }
  12170. _intersectionPointWorld.copy( point );
  12171. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12172. var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12173. if ( distance < raycaster.near || distance > raycaster.far ) { return null; }
  12174. return {
  12175. distance: distance,
  12176. point: _intersectionPointWorld.clone(),
  12177. object: object
  12178. };
  12179. }
  12180. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c ) {
  12181. _vA.fromBufferAttribute( position, a );
  12182. _vB.fromBufferAttribute( position, b );
  12183. _vC.fromBufferAttribute( position, c );
  12184. var morphInfluences = object.morphTargetInfluences;
  12185. if ( material.morphTargets && morphPosition && morphInfluences ) {
  12186. _morphA.set( 0, 0, 0 );
  12187. _morphB.set( 0, 0, 0 );
  12188. _morphC.set( 0, 0, 0 );
  12189. for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
  12190. var influence = morphInfluences[ i ];
  12191. var morphAttribute = morphPosition[ i ];
  12192. if ( influence === 0 ) { continue; }
  12193. _tempA.fromBufferAttribute( morphAttribute, a );
  12194. _tempB.fromBufferAttribute( morphAttribute, b );
  12195. _tempC.fromBufferAttribute( morphAttribute, c );
  12196. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  12197. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  12198. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  12199. }
  12200. _vA.add( _morphA );
  12201. _vB.add( _morphB );
  12202. _vC.add( _morphC );
  12203. }
  12204. var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  12205. if ( intersection ) {
  12206. if ( uv ) {
  12207. _uvA.fromBufferAttribute( uv, a );
  12208. _uvB.fromBufferAttribute( uv, b );
  12209. _uvC.fromBufferAttribute( uv, c );
  12210. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12211. }
  12212. if ( uv2 ) {
  12213. _uvA.fromBufferAttribute( uv2, a );
  12214. _uvB.fromBufferAttribute( uv2, b );
  12215. _uvC.fromBufferAttribute( uv2, c );
  12216. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12217. }
  12218. var face = new Face3( a, b, c );
  12219. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  12220. intersection.face = face;
  12221. }
  12222. return intersection;
  12223. }
  12224. /**
  12225. * @author mrdoob / http://mrdoob.com/
  12226. * @author kile / http://kile.stravaganza.org/
  12227. * @author alteredq / http://alteredqualia.com/
  12228. * @author mikael emtinger / http://gomo.se/
  12229. * @author zz85 / http://www.lab4games.net/zz85/blog
  12230. * @author bhouston / http://clara.io
  12231. */
  12232. var _geometryId = 0; // Geometry uses even numbers as Id
  12233. var _m1$3 = new Matrix4();
  12234. var _obj$1 = new Object3D();
  12235. var _offset$1 = new Vector3();
  12236. function Geometry() {
  12237. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  12238. this.uuid = _Math.generateUUID();
  12239. this.name = '';
  12240. this.type = 'Geometry';
  12241. this.vertices = [];
  12242. this.colors = [];
  12243. this.faces = [];
  12244. this.faceVertexUvs = [[]];
  12245. this.morphTargets = [];
  12246. this.morphNormals = [];
  12247. this.skinWeights = [];
  12248. this.skinIndices = [];
  12249. this.lineDistances = [];
  12250. this.boundingBox = null;
  12251. this.boundingSphere = null;
  12252. // update flags
  12253. this.elementsNeedUpdate = false;
  12254. this.verticesNeedUpdate = false;
  12255. this.uvsNeedUpdate = false;
  12256. this.normalsNeedUpdate = false;
  12257. this.colorsNeedUpdate = false;
  12258. this.lineDistancesNeedUpdate = false;
  12259. this.groupsNeedUpdate = false;
  12260. }
  12261. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12262. constructor: Geometry,
  12263. isGeometry: true,
  12264. applyMatrix: function ( matrix ) {
  12265. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12266. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  12267. var vertex = this.vertices[ i ];
  12268. vertex.applyMatrix4( matrix );
  12269. }
  12270. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  12271. var face = this.faces[ i ];
  12272. face.normal.applyMatrix3( normalMatrix ).normalize();
  12273. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  12274. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  12275. }
  12276. }
  12277. if ( this.boundingBox !== null ) {
  12278. this.computeBoundingBox();
  12279. }
  12280. if ( this.boundingSphere !== null ) {
  12281. this.computeBoundingSphere();
  12282. }
  12283. this.verticesNeedUpdate = true;
  12284. this.normalsNeedUpdate = true;
  12285. return this;
  12286. },
  12287. rotateX: function ( angle ) {
  12288. // rotate geometry around world x-axis
  12289. _m1$3.makeRotationX( angle );
  12290. this.applyMatrix( _m1$3 );
  12291. return this;
  12292. },
  12293. rotateY: function ( angle ) {
  12294. // rotate geometry around world y-axis
  12295. _m1$3.makeRotationY( angle );
  12296. this.applyMatrix( _m1$3 );
  12297. return this;
  12298. },
  12299. rotateZ: function ( angle ) {
  12300. // rotate geometry around world z-axis
  12301. _m1$3.makeRotationZ( angle );
  12302. this.applyMatrix( _m1$3 );
  12303. return this;
  12304. },
  12305. translate: function ( x, y, z ) {
  12306. // translate geometry
  12307. _m1$3.makeTranslation( x, y, z );
  12308. this.applyMatrix( _m1$3 );
  12309. return this;
  12310. },
  12311. scale: function ( x, y, z ) {
  12312. // scale geometry
  12313. _m1$3.makeScale( x, y, z );
  12314. this.applyMatrix( _m1$3 );
  12315. return this;
  12316. },
  12317. lookAt: function ( vector ) {
  12318. _obj$1.lookAt( vector );
  12319. _obj$1.updateMatrix();
  12320. this.applyMatrix( _obj$1.matrix );
  12321. return this;
  12322. },
  12323. fromBufferGeometry: function ( geometry ) {
  12324. var scope = this;
  12325. var indices = geometry.index !== null ? geometry.index.array : undefined;
  12326. var attributes = geometry.attributes;
  12327. var positions = attributes.position.array;
  12328. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  12329. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  12330. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  12331. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  12332. if ( uvs2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; }
  12333. for ( var i = 0; i < positions.length; i += 3 ) {
  12334. scope.vertices.push( new Vector3().fromArray( positions, i ) );
  12335. if ( colors !== undefined ) {
  12336. scope.colors.push( new Color().fromArray( colors, i ) );
  12337. }
  12338. }
  12339. function addFace( a, b, c, materialIndex ) {
  12340. var vertexColors = ( colors === undefined ) ? [] : [
  12341. scope.colors[ a ].clone(),
  12342. scope.colors[ b ].clone(),
  12343. scope.colors[ c ].clone() ];
  12344. var vertexNormals = ( normals === undefined ) ? [] : [
  12345. new Vector3().fromArray( normals, a * 3 ),
  12346. new Vector3().fromArray( normals, b * 3 ),
  12347. new Vector3().fromArray( normals, c * 3 )
  12348. ];
  12349. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  12350. scope.faces.push( face );
  12351. if ( uvs !== undefined ) {
  12352. scope.faceVertexUvs[ 0 ].push( [
  12353. new Vector2().fromArray( uvs, a * 2 ),
  12354. new Vector2().fromArray( uvs, b * 2 ),
  12355. new Vector2().fromArray( uvs, c * 2 )
  12356. ] );
  12357. }
  12358. if ( uvs2 !== undefined ) {
  12359. scope.faceVertexUvs[ 1 ].push( [
  12360. new Vector2().fromArray( uvs2, a * 2 ),
  12361. new Vector2().fromArray( uvs2, b * 2 ),
  12362. new Vector2().fromArray( uvs2, c * 2 )
  12363. ] );
  12364. }
  12365. }
  12366. var groups = geometry.groups;
  12367. if ( groups.length > 0 ) {
  12368. for ( var i = 0; i < groups.length; i ++ ) {
  12369. var group = groups[ i ];
  12370. var start = group.start;
  12371. var count = group.count;
  12372. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  12373. if ( indices !== undefined ) {
  12374. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  12375. } else {
  12376. addFace( j, j + 1, j + 2, group.materialIndex );
  12377. }
  12378. }
  12379. }
  12380. } else {
  12381. if ( indices !== undefined ) {
  12382. for ( var i = 0; i < indices.length; i += 3 ) {
  12383. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  12384. }
  12385. } else {
  12386. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  12387. addFace( i, i + 1, i + 2 );
  12388. }
  12389. }
  12390. }
  12391. this.computeFaceNormals();
  12392. if ( geometry.boundingBox !== null ) {
  12393. this.boundingBox = geometry.boundingBox.clone();
  12394. }
  12395. if ( geometry.boundingSphere !== null ) {
  12396. this.boundingSphere = geometry.boundingSphere.clone();
  12397. }
  12398. return this;
  12399. },
  12400. center: function () {
  12401. this.computeBoundingBox();
  12402. this.boundingBox.getCenter( _offset$1 ).negate();
  12403. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  12404. return this;
  12405. },
  12406. normalize: function () {
  12407. this.computeBoundingSphere();
  12408. var center = this.boundingSphere.center;
  12409. var radius = this.boundingSphere.radius;
  12410. var s = radius === 0 ? 1 : 1.0 / radius;
  12411. var matrix = new Matrix4();
  12412. matrix.set(
  12413. s, 0, 0, - s * center.x,
  12414. 0, s, 0, - s * center.y,
  12415. 0, 0, s, - s * center.z,
  12416. 0, 0, 0, 1
  12417. );
  12418. this.applyMatrix( matrix );
  12419. return this;
  12420. },
  12421. computeFaceNormals: function () {
  12422. var cb = new Vector3(), ab = new Vector3();
  12423. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12424. var face = this.faces[ f ];
  12425. var vA = this.vertices[ face.a ];
  12426. var vB = this.vertices[ face.b ];
  12427. var vC = this.vertices[ face.c ];
  12428. cb.subVectors( vC, vB );
  12429. ab.subVectors( vA, vB );
  12430. cb.cross( ab );
  12431. cb.normalize();
  12432. face.normal.copy( cb );
  12433. }
  12434. },
  12435. computeVertexNormals: function ( areaWeighted ) {
  12436. if ( areaWeighted === undefined ) { areaWeighted = true; }
  12437. var v, vl, f, fl, face, vertices;
  12438. vertices = new Array( this.vertices.length );
  12439. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12440. vertices[ v ] = new Vector3();
  12441. }
  12442. if ( areaWeighted ) {
  12443. // vertex normals weighted by triangle areas
  12444. // http://www.iquilezles.org/www/articles/normals/normals.htm
  12445. var vA, vB, vC;
  12446. var cb = new Vector3(), ab = new Vector3();
  12447. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12448. face = this.faces[ f ];
  12449. vA = this.vertices[ face.a ];
  12450. vB = this.vertices[ face.b ];
  12451. vC = this.vertices[ face.c ];
  12452. cb.subVectors( vC, vB );
  12453. ab.subVectors( vA, vB );
  12454. cb.cross( ab );
  12455. vertices[ face.a ].add( cb );
  12456. vertices[ face.b ].add( cb );
  12457. vertices[ face.c ].add( cb );
  12458. }
  12459. } else {
  12460. this.computeFaceNormals();
  12461. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12462. face = this.faces[ f ];
  12463. vertices[ face.a ].add( face.normal );
  12464. vertices[ face.b ].add( face.normal );
  12465. vertices[ face.c ].add( face.normal );
  12466. }
  12467. }
  12468. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12469. vertices[ v ].normalize();
  12470. }
  12471. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12472. face = this.faces[ f ];
  12473. var vertexNormals = face.vertexNormals;
  12474. if ( vertexNormals.length === 3 ) {
  12475. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  12476. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  12477. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  12478. } else {
  12479. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  12480. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  12481. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  12482. }
  12483. }
  12484. if ( this.faces.length > 0 ) {
  12485. this.normalsNeedUpdate = true;
  12486. }
  12487. },
  12488. computeFlatVertexNormals: function () {
  12489. var f, fl, face;
  12490. this.computeFaceNormals();
  12491. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12492. face = this.faces[ f ];
  12493. var vertexNormals = face.vertexNormals;
  12494. if ( vertexNormals.length === 3 ) {
  12495. vertexNormals[ 0 ].copy( face.normal );
  12496. vertexNormals[ 1 ].copy( face.normal );
  12497. vertexNormals[ 2 ].copy( face.normal );
  12498. } else {
  12499. vertexNormals[ 0 ] = face.normal.clone();
  12500. vertexNormals[ 1 ] = face.normal.clone();
  12501. vertexNormals[ 2 ] = face.normal.clone();
  12502. }
  12503. }
  12504. if ( this.faces.length > 0 ) {
  12505. this.normalsNeedUpdate = true;
  12506. }
  12507. },
  12508. computeMorphNormals: function () {
  12509. var i, il, f, fl, face;
  12510. // save original normals
  12511. // - create temp variables on first access
  12512. // otherwise just copy (for faster repeated calls)
  12513. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12514. face = this.faces[ f ];
  12515. if ( ! face.__originalFaceNormal ) {
  12516. face.__originalFaceNormal = face.normal.clone();
  12517. } else {
  12518. face.__originalFaceNormal.copy( face.normal );
  12519. }
  12520. if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; }
  12521. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  12522. if ( ! face.__originalVertexNormals[ i ] ) {
  12523. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  12524. } else {
  12525. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  12526. }
  12527. }
  12528. }
  12529. // use temp geometry to compute face and vertex normals for each morph
  12530. var tmpGeo = new Geometry();
  12531. tmpGeo.faces = this.faces;
  12532. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  12533. // create on first access
  12534. if ( ! this.morphNormals[ i ] ) {
  12535. this.morphNormals[ i ] = {};
  12536. this.morphNormals[ i ].faceNormals = [];
  12537. this.morphNormals[ i ].vertexNormals = [];
  12538. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  12539. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  12540. var faceNormal, vertexNormals;
  12541. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12542. faceNormal = new Vector3();
  12543. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  12544. dstNormalsFace.push( faceNormal );
  12545. dstNormalsVertex.push( vertexNormals );
  12546. }
  12547. }
  12548. var morphNormals = this.morphNormals[ i ];
  12549. // set vertices to morph target
  12550. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  12551. // compute morph normals
  12552. tmpGeo.computeFaceNormals();
  12553. tmpGeo.computeVertexNormals();
  12554. // store morph normals
  12555. var faceNormal, vertexNormals;
  12556. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12557. face = this.faces[ f ];
  12558. faceNormal = morphNormals.faceNormals[ f ];
  12559. vertexNormals = morphNormals.vertexNormals[ f ];
  12560. faceNormal.copy( face.normal );
  12561. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  12562. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  12563. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  12564. }
  12565. }
  12566. // restore original normals
  12567. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12568. face = this.faces[ f ];
  12569. face.normal = face.__originalFaceNormal;
  12570. face.vertexNormals = face.__originalVertexNormals;
  12571. }
  12572. },
  12573. computeBoundingBox: function () {
  12574. if ( this.boundingBox === null ) {
  12575. this.boundingBox = new Box3();
  12576. }
  12577. this.boundingBox.setFromPoints( this.vertices );
  12578. },
  12579. computeBoundingSphere: function () {
  12580. if ( this.boundingSphere === null ) {
  12581. this.boundingSphere = new Sphere();
  12582. }
  12583. this.boundingSphere.setFromPoints( this.vertices );
  12584. },
  12585. merge: function ( geometry, matrix, materialIndexOffset ) {
  12586. if ( ! ( geometry && geometry.isGeometry ) ) {
  12587. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  12588. return;
  12589. }
  12590. var normalMatrix,
  12591. vertexOffset = this.vertices.length,
  12592. vertices1 = this.vertices,
  12593. vertices2 = geometry.vertices,
  12594. faces1 = this.faces,
  12595. faces2 = geometry.faces,
  12596. colors1 = this.colors,
  12597. colors2 = geometry.colors;
  12598. if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; }
  12599. if ( matrix !== undefined ) {
  12600. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12601. }
  12602. // vertices
  12603. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  12604. var vertex = vertices2[ i ];
  12605. var vertexCopy = vertex.clone();
  12606. if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); }
  12607. vertices1.push( vertexCopy );
  12608. }
  12609. // colors
  12610. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  12611. colors1.push( colors2[ i ].clone() );
  12612. }
  12613. // faces
  12614. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  12615. var face = faces2[ i ], faceCopy, normal, color,
  12616. faceVertexNormals = face.vertexNormals,
  12617. faceVertexColors = face.vertexColors;
  12618. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  12619. faceCopy.normal.copy( face.normal );
  12620. if ( normalMatrix !== undefined ) {
  12621. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  12622. }
  12623. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  12624. normal = faceVertexNormals[ j ].clone();
  12625. if ( normalMatrix !== undefined ) {
  12626. normal.applyMatrix3( normalMatrix ).normalize();
  12627. }
  12628. faceCopy.vertexNormals.push( normal );
  12629. }
  12630. faceCopy.color.copy( face.color );
  12631. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  12632. color = faceVertexColors[ j ];
  12633. faceCopy.vertexColors.push( color.clone() );
  12634. }
  12635. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  12636. faces1.push( faceCopy );
  12637. }
  12638. // uvs
  12639. for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  12640. var faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  12641. if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; }
  12642. for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  12643. var uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  12644. for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) {
  12645. uvsCopy.push( uvs2[ k ].clone() );
  12646. }
  12647. this.faceVertexUvs[ i ].push( uvsCopy );
  12648. }
  12649. }
  12650. },
  12651. mergeMesh: function ( mesh ) {
  12652. if ( ! ( mesh && mesh.isMesh ) ) {
  12653. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  12654. return;
  12655. }
  12656. if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); }
  12657. this.merge( mesh.geometry, mesh.matrix );
  12658. },
  12659. /*
  12660. * Checks for duplicate vertices with hashmap.
  12661. * Duplicated vertices are removed
  12662. * and faces' vertices are updated.
  12663. */
  12664. mergeVertices: function () {
  12665. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  12666. var unique = [], changes = [];
  12667. var v, key;
  12668. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  12669. var precision = Math.pow( 10, precisionPoints );
  12670. var i, il, face;
  12671. var indices, j, jl;
  12672. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  12673. v = this.vertices[ i ];
  12674. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12675. if ( verticesMap[ key ] === undefined ) {
  12676. verticesMap[ key ] = i;
  12677. unique.push( this.vertices[ i ] );
  12678. changes[ i ] = unique.length - 1;
  12679. } else {
  12680. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12681. changes[ i ] = changes[ verticesMap[ key ] ];
  12682. }
  12683. }
  12684. // if faces are completely degenerate after merging vertices, we
  12685. // have to remove them from the geometry.
  12686. var faceIndicesToRemove = [];
  12687. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  12688. face = this.faces[ i ];
  12689. face.a = changes[ face.a ];
  12690. face.b = changes[ face.b ];
  12691. face.c = changes[ face.c ];
  12692. indices = [ face.a, face.b, face.c ];
  12693. // if any duplicate vertices are found in a Face3
  12694. // we have to remove the face as nothing can be saved
  12695. for ( var n = 0; n < 3; n ++ ) {
  12696. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12697. faceIndicesToRemove.push( i );
  12698. break;
  12699. }
  12700. }
  12701. }
  12702. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  12703. var idx = faceIndicesToRemove[ i ];
  12704. this.faces.splice( idx, 1 );
  12705. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12706. this.faceVertexUvs[ j ].splice( idx, 1 );
  12707. }
  12708. }
  12709. // Use unique set of vertices
  12710. var diff = this.vertices.length - unique.length;
  12711. this.vertices = unique;
  12712. return diff;
  12713. },
  12714. setFromPoints: function ( points ) {
  12715. this.vertices = [];
  12716. for ( var i = 0, l = points.length; i < l; i ++ ) {
  12717. var point = points[ i ];
  12718. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  12719. }
  12720. return this;
  12721. },
  12722. sortFacesByMaterialIndex: function () {
  12723. var faces = this.faces;
  12724. var length = faces.length;
  12725. // tag faces
  12726. for ( var i = 0; i < length; i ++ ) {
  12727. faces[ i ]._id = i;
  12728. }
  12729. // sort faces
  12730. function materialIndexSort( a, b ) {
  12731. return a.materialIndex - b.materialIndex;
  12732. }
  12733. faces.sort( materialIndexSort );
  12734. // sort uvs
  12735. var uvs1 = this.faceVertexUvs[ 0 ];
  12736. var uvs2 = this.faceVertexUvs[ 1 ];
  12737. var newUvs1, newUvs2;
  12738. if ( uvs1 && uvs1.length === length ) { newUvs1 = []; }
  12739. if ( uvs2 && uvs2.length === length ) { newUvs2 = []; }
  12740. for ( var i = 0; i < length; i ++ ) {
  12741. var id = faces[ i ]._id;
  12742. if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); }
  12743. if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); }
  12744. }
  12745. if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; }
  12746. if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; }
  12747. },
  12748. toJSON: function () {
  12749. var data = {
  12750. metadata: {
  12751. version: 4.5,
  12752. type: 'Geometry',
  12753. generator: 'Geometry.toJSON'
  12754. }
  12755. };
  12756. // standard Geometry serialization
  12757. data.uuid = this.uuid;
  12758. data.type = this.type;
  12759. if ( this.name !== '' ) { data.name = this.name; }
  12760. if ( this.parameters !== undefined ) {
  12761. var parameters = this.parameters;
  12762. for ( var key in parameters ) {
  12763. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  12764. }
  12765. return data;
  12766. }
  12767. var vertices = [];
  12768. for ( var i = 0; i < this.vertices.length; i ++ ) {
  12769. var vertex = this.vertices[ i ];
  12770. vertices.push( vertex.x, vertex.y, vertex.z );
  12771. }
  12772. var faces = [];
  12773. var normals = [];
  12774. var normalsHash = {};
  12775. var colors = [];
  12776. var colorsHash = {};
  12777. var uvs = [];
  12778. var uvsHash = {};
  12779. for ( var i = 0; i < this.faces.length; i ++ ) {
  12780. var face = this.faces[ i ];
  12781. var hasMaterial = true;
  12782. var hasFaceUv = false; // deprecated
  12783. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  12784. var hasFaceNormal = face.normal.length() > 0;
  12785. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  12786. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  12787. var hasFaceVertexColor = face.vertexColors.length > 0;
  12788. var faceType = 0;
  12789. faceType = setBit( faceType, 0, 0 ); // isQuad
  12790. faceType = setBit( faceType, 1, hasMaterial );
  12791. faceType = setBit( faceType, 2, hasFaceUv );
  12792. faceType = setBit( faceType, 3, hasFaceVertexUv );
  12793. faceType = setBit( faceType, 4, hasFaceNormal );
  12794. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  12795. faceType = setBit( faceType, 6, hasFaceColor );
  12796. faceType = setBit( faceType, 7, hasFaceVertexColor );
  12797. faces.push( faceType );
  12798. faces.push( face.a, face.b, face.c );
  12799. faces.push( face.materialIndex );
  12800. if ( hasFaceVertexUv ) {
  12801. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  12802. faces.push(
  12803. getUvIndex( faceVertexUvs[ 0 ] ),
  12804. getUvIndex( faceVertexUvs[ 1 ] ),
  12805. getUvIndex( faceVertexUvs[ 2 ] )
  12806. );
  12807. }
  12808. if ( hasFaceNormal ) {
  12809. faces.push( getNormalIndex( face.normal ) );
  12810. }
  12811. if ( hasFaceVertexNormal ) {
  12812. var vertexNormals = face.vertexNormals;
  12813. faces.push(
  12814. getNormalIndex( vertexNormals[ 0 ] ),
  12815. getNormalIndex( vertexNormals[ 1 ] ),
  12816. getNormalIndex( vertexNormals[ 2 ] )
  12817. );
  12818. }
  12819. if ( hasFaceColor ) {
  12820. faces.push( getColorIndex( face.color ) );
  12821. }
  12822. if ( hasFaceVertexColor ) {
  12823. var vertexColors = face.vertexColors;
  12824. faces.push(
  12825. getColorIndex( vertexColors[ 0 ] ),
  12826. getColorIndex( vertexColors[ 1 ] ),
  12827. getColorIndex( vertexColors[ 2 ] )
  12828. );
  12829. }
  12830. }
  12831. function setBit( value, position, enabled ) {
  12832. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  12833. }
  12834. function getNormalIndex( normal ) {
  12835. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  12836. if ( normalsHash[ hash ] !== undefined ) {
  12837. return normalsHash[ hash ];
  12838. }
  12839. normalsHash[ hash ] = normals.length / 3;
  12840. normals.push( normal.x, normal.y, normal.z );
  12841. return normalsHash[ hash ];
  12842. }
  12843. function getColorIndex( color ) {
  12844. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  12845. if ( colorsHash[ hash ] !== undefined ) {
  12846. return colorsHash[ hash ];
  12847. }
  12848. colorsHash[ hash ] = colors.length;
  12849. colors.push( color.getHex() );
  12850. return colorsHash[ hash ];
  12851. }
  12852. function getUvIndex( uv ) {
  12853. var hash = uv.x.toString() + uv.y.toString();
  12854. if ( uvsHash[ hash ] !== undefined ) {
  12855. return uvsHash[ hash ];
  12856. }
  12857. uvsHash[ hash ] = uvs.length / 2;
  12858. uvs.push( uv.x, uv.y );
  12859. return uvsHash[ hash ];
  12860. }
  12861. data.data = {};
  12862. data.data.vertices = vertices;
  12863. data.data.normals = normals;
  12864. if ( colors.length > 0 ) { data.data.colors = colors; }
  12865. if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility
  12866. data.data.faces = faces;
  12867. return data;
  12868. },
  12869. clone: function () {
  12870. /*
  12871. // Handle primitives
  12872. var parameters = this.parameters;
  12873. if ( parameters !== undefined ) {
  12874. var values = [];
  12875. for ( var key in parameters ) {
  12876. values.push( parameters[ key ] );
  12877. }
  12878. var geometry = Object.create( this.constructor.prototype );
  12879. this.constructor.apply( geometry, values );
  12880. return geometry;
  12881. }
  12882. return new this.constructor().copy( this );
  12883. */
  12884. return new Geometry().copy( this );
  12885. },
  12886. copy: function ( source ) {
  12887. var i, il, j, jl, k, kl;
  12888. // reset
  12889. this.vertices = [];
  12890. this.colors = [];
  12891. this.faces = [];
  12892. this.faceVertexUvs = [[]];
  12893. this.morphTargets = [];
  12894. this.morphNormals = [];
  12895. this.skinWeights = [];
  12896. this.skinIndices = [];
  12897. this.lineDistances = [];
  12898. this.boundingBox = null;
  12899. this.boundingSphere = null;
  12900. // name
  12901. this.name = source.name;
  12902. // vertices
  12903. var vertices = source.vertices;
  12904. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  12905. this.vertices.push( vertices[ i ].clone() );
  12906. }
  12907. // colors
  12908. var colors = source.colors;
  12909. for ( i = 0, il = colors.length; i < il; i ++ ) {
  12910. this.colors.push( colors[ i ].clone() );
  12911. }
  12912. // faces
  12913. var faces = source.faces;
  12914. for ( i = 0, il = faces.length; i < il; i ++ ) {
  12915. this.faces.push( faces[ i ].clone() );
  12916. }
  12917. // face vertex uvs
  12918. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  12919. var faceVertexUvs = source.faceVertexUvs[ i ];
  12920. if ( this.faceVertexUvs[ i ] === undefined ) {
  12921. this.faceVertexUvs[ i ] = [];
  12922. }
  12923. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  12924. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  12925. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  12926. var uv = uvs[ k ];
  12927. uvsCopy.push( uv.clone() );
  12928. }
  12929. this.faceVertexUvs[ i ].push( uvsCopy );
  12930. }
  12931. }
  12932. // morph targets
  12933. var morphTargets = source.morphTargets;
  12934. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  12935. var morphTarget = {};
  12936. morphTarget.name = morphTargets[ i ].name;
  12937. // vertices
  12938. if ( morphTargets[ i ].vertices !== undefined ) {
  12939. morphTarget.vertices = [];
  12940. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  12941. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  12942. }
  12943. }
  12944. // normals
  12945. if ( morphTargets[ i ].normals !== undefined ) {
  12946. morphTarget.normals = [];
  12947. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  12948. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  12949. }
  12950. }
  12951. this.morphTargets.push( morphTarget );
  12952. }
  12953. // morph normals
  12954. var morphNormals = source.morphNormals;
  12955. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  12956. var morphNormal = {};
  12957. // vertex normals
  12958. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  12959. morphNormal.vertexNormals = [];
  12960. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  12961. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  12962. var destVertexNormal = {};
  12963. destVertexNormal.a = srcVertexNormal.a.clone();
  12964. destVertexNormal.b = srcVertexNormal.b.clone();
  12965. destVertexNormal.c = srcVertexNormal.c.clone();
  12966. morphNormal.vertexNormals.push( destVertexNormal );
  12967. }
  12968. }
  12969. // face normals
  12970. if ( morphNormals[ i ].faceNormals !== undefined ) {
  12971. morphNormal.faceNormals = [];
  12972. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  12973. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  12974. }
  12975. }
  12976. this.morphNormals.push( morphNormal );
  12977. }
  12978. // skin weights
  12979. var skinWeights = source.skinWeights;
  12980. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  12981. this.skinWeights.push( skinWeights[ i ].clone() );
  12982. }
  12983. // skin indices
  12984. var skinIndices = source.skinIndices;
  12985. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  12986. this.skinIndices.push( skinIndices[ i ].clone() );
  12987. }
  12988. // line distances
  12989. var lineDistances = source.lineDistances;
  12990. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  12991. this.lineDistances.push( lineDistances[ i ] );
  12992. }
  12993. // bounding box
  12994. var boundingBox = source.boundingBox;
  12995. if ( boundingBox !== null ) {
  12996. this.boundingBox = boundingBox.clone();
  12997. }
  12998. // bounding sphere
  12999. var boundingSphere = source.boundingSphere;
  13000. if ( boundingSphere !== null ) {
  13001. this.boundingSphere = boundingSphere.clone();
  13002. }
  13003. // update flags
  13004. this.elementsNeedUpdate = source.elementsNeedUpdate;
  13005. this.verticesNeedUpdate = source.verticesNeedUpdate;
  13006. this.uvsNeedUpdate = source.uvsNeedUpdate;
  13007. this.normalsNeedUpdate = source.normalsNeedUpdate;
  13008. this.colorsNeedUpdate = source.colorsNeedUpdate;
  13009. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  13010. this.groupsNeedUpdate = source.groupsNeedUpdate;
  13011. return this;
  13012. },
  13013. dispose: function () {
  13014. this.dispatchEvent( { type: 'dispose' } );
  13015. }
  13016. } );
  13017. /**
  13018. * @author mrdoob / http://mrdoob.com/
  13019. * @author Mugen87 / https://github.com/Mugen87
  13020. */
  13021. // BoxGeometry
  13022. var BoxGeometry = /*@__PURE__*/(function (Geometry) {
  13023. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13024. Geometry.call(this);
  13025. this.type = 'BoxGeometry';
  13026. this.parameters = {
  13027. width: width,
  13028. height: height,
  13029. depth: depth,
  13030. widthSegments: widthSegments,
  13031. heightSegments: heightSegments,
  13032. depthSegments: depthSegments
  13033. };
  13034. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13035. this.mergeVertices();
  13036. }
  13037. if ( Geometry ) BoxGeometry.__proto__ = Geometry;
  13038. BoxGeometry.prototype = Object.create( Geometry && Geometry.prototype );
  13039. BoxGeometry.prototype.constructor = BoxGeometry;
  13040. return BoxGeometry;
  13041. }(Geometry));
  13042. // BoxBufferGeometry
  13043. var BoxBufferGeometry = /*@__PURE__*/(function (BufferGeometry) {
  13044. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13045. BufferGeometry.call(this);
  13046. this.type = 'BoxBufferGeometry';
  13047. this.parameters = {
  13048. width: width,
  13049. height: height,
  13050. depth: depth,
  13051. widthSegments: widthSegments,
  13052. heightSegments: heightSegments,
  13053. depthSegments: depthSegments
  13054. };
  13055. var scope = this;
  13056. width = width || 1;
  13057. height = height || 1;
  13058. depth = depth || 1;
  13059. // segments
  13060. widthSegments = Math.floor( widthSegments ) || 1;
  13061. heightSegments = Math.floor( heightSegments ) || 1;
  13062. depthSegments = Math.floor( depthSegments ) || 1;
  13063. // buffers
  13064. var indices = [];
  13065. var vertices = [];
  13066. var normals = [];
  13067. var uvs = [];
  13068. // helper variables
  13069. var numberOfVertices = 0;
  13070. var groupStart = 0;
  13071. // build each side of the box geometry
  13072. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13073. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13074. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13075. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13076. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13077. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13078. // build geometry
  13079. this.setIndex( indices );
  13080. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13081. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13082. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13083. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13084. var segmentWidth = width / gridX;
  13085. var segmentHeight = height / gridY;
  13086. var widthHalf = width / 2;
  13087. var heightHalf = height / 2;
  13088. var depthHalf = depth / 2;
  13089. var gridX1 = gridX + 1;
  13090. var gridY1 = gridY + 1;
  13091. var vertexCounter = 0;
  13092. var groupCount = 0;
  13093. var ix, iy;
  13094. var vector = new Vector3();
  13095. // generate vertices, normals and uvs
  13096. for ( iy = 0; iy < gridY1; iy ++ ) {
  13097. var y = iy * segmentHeight - heightHalf;
  13098. for ( ix = 0; ix < gridX1; ix ++ ) {
  13099. var x = ix * segmentWidth - widthHalf;
  13100. // set values to correct vector component
  13101. vector[ u ] = x * udir;
  13102. vector[ v ] = y * vdir;
  13103. vector[ w ] = depthHalf;
  13104. // now apply vector to vertex buffer
  13105. vertices.push( vector.x, vector.y, vector.z );
  13106. // set values to correct vector component
  13107. vector[ u ] = 0;
  13108. vector[ v ] = 0;
  13109. vector[ w ] = depth > 0 ? 1 : - 1;
  13110. // now apply vector to normal buffer
  13111. normals.push( vector.x, vector.y, vector.z );
  13112. // uvs
  13113. uvs.push( ix / gridX );
  13114. uvs.push( 1 - ( iy / gridY ) );
  13115. // counters
  13116. vertexCounter += 1;
  13117. }
  13118. }
  13119. // indices
  13120. // 1. you need three indices to draw a single face
  13121. // 2. a single segment consists of two faces
  13122. // 3. so we need to generate six (2*3) indices per segment
  13123. for ( iy = 0; iy < gridY; iy ++ ) {
  13124. for ( ix = 0; ix < gridX; ix ++ ) {
  13125. var a = numberOfVertices + ix + gridX1 * iy;
  13126. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13127. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13128. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13129. // faces
  13130. indices.push( a, b, d );
  13131. indices.push( b, c, d );
  13132. // increase counter
  13133. groupCount += 6;
  13134. }
  13135. }
  13136. // add a group to the geometry. this will ensure multi material support
  13137. scope.addGroup( groupStart, groupCount, materialIndex );
  13138. // calculate new start value for groups
  13139. groupStart += groupCount;
  13140. // update total number of vertices
  13141. numberOfVertices += vertexCounter;
  13142. }
  13143. }
  13144. if ( BufferGeometry ) BoxBufferGeometry.__proto__ = BufferGeometry;
  13145. BoxBufferGeometry.prototype = Object.create( BufferGeometry && BufferGeometry.prototype );
  13146. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13147. return BoxBufferGeometry;
  13148. }(BufferGeometry));
  13149. /**
  13150. * Uniform Utilities
  13151. */
  13152. function cloneUniforms( src ) {
  13153. var dst = {};
  13154. for ( var u in src ) {
  13155. dst[ u ] = {};
  13156. for ( var p in src[ u ] ) {
  13157. var property = src[ u ][ p ];
  13158. if ( property && ( property.isColor ||
  13159. property.isMatrix3 || property.isMatrix4 ||
  13160. property.isVector2 || property.isVector3 || property.isVector4 ||
  13161. property.isTexture ) ) {
  13162. dst[ u ][ p ] = property.clone();
  13163. } else if ( Array.isArray( property ) ) {
  13164. dst[ u ][ p ] = property.slice();
  13165. } else {
  13166. dst[ u ][ p ] = property;
  13167. }
  13168. }
  13169. }
  13170. return dst;
  13171. }
  13172. function mergeUniforms( uniforms ) {
  13173. var merged = {};
  13174. for ( var u = 0; u < uniforms.length; u ++ ) {
  13175. var tmp = cloneUniforms( uniforms[ u ] );
  13176. for ( var p in tmp ) {
  13177. merged[ p ] = tmp[ p ];
  13178. }
  13179. }
  13180. return merged;
  13181. }
  13182. // Legacy
  13183. var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  13184. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  13185. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  13186. /**
  13187. * @author alteredq / http://alteredqualia.com/
  13188. *
  13189. * parameters = {
  13190. * defines: { "label" : "value" },
  13191. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13192. *
  13193. * fragmentShader: <string>,
  13194. * vertexShader: <string>,
  13195. *
  13196. * wireframe: <boolean>,
  13197. * wireframeLinewidth: <float>,
  13198. *
  13199. * lights: <bool>,
  13200. *
  13201. * skinning: <bool>,
  13202. * morphTargets: <bool>,
  13203. * morphNormals: <bool>
  13204. * }
  13205. */
  13206. function ShaderMaterial( parameters ) {
  13207. Material.call( this );
  13208. this.type = 'ShaderMaterial';
  13209. this.defines = {};
  13210. this.uniforms = {};
  13211. this.vertexShader = default_vertex;
  13212. this.fragmentShader = default_fragment;
  13213. this.linewidth = 1;
  13214. this.wireframe = false;
  13215. this.wireframeLinewidth = 1;
  13216. this.fog = false; // set to use scene fog
  13217. this.lights = false; // set to use scene lights
  13218. this.clipping = false; // set to use user-defined clipping planes
  13219. this.skinning = false; // set to use skinning attribute streams
  13220. this.morphTargets = false; // set to use morph targets
  13221. this.morphNormals = false; // set to use morph normals
  13222. this.extensions = {
  13223. derivatives: false, // set to use derivatives
  13224. fragDepth: false, // set to use fragment depth values
  13225. drawBuffers: false, // set to use draw buffers
  13226. shaderTextureLOD: false // set to use shader texture LOD
  13227. };
  13228. // When rendered geometry doesn't include these attributes but the material does,
  13229. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13230. this.defaultAttributeValues = {
  13231. 'color': [ 1, 1, 1 ],
  13232. 'uv': [ 0, 0 ],
  13233. 'uv2': [ 0, 0 ]
  13234. };
  13235. this.index0AttributeName = undefined;
  13236. this.uniformsNeedUpdate = false;
  13237. if ( parameters !== undefined ) {
  13238. if ( parameters.attributes !== undefined ) {
  13239. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  13240. }
  13241. this.setValues( parameters );
  13242. }
  13243. }
  13244. ShaderMaterial.prototype = Object.create( Material.prototype );
  13245. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13246. ShaderMaterial.prototype.isShaderMaterial = true;
  13247. ShaderMaterial.prototype.copy = function ( source ) {
  13248. Material.prototype.copy.call( this, source );
  13249. this.fragmentShader = source.fragmentShader;
  13250. this.vertexShader = source.vertexShader;
  13251. this.uniforms = cloneUniforms( source.uniforms );
  13252. this.defines = Object.assign( {}, source.defines );
  13253. this.wireframe = source.wireframe;
  13254. this.wireframeLinewidth = source.wireframeLinewidth;
  13255. this.lights = source.lights;
  13256. this.clipping = source.clipping;
  13257. this.skinning = source.skinning;
  13258. this.morphTargets = source.morphTargets;
  13259. this.morphNormals = source.morphNormals;
  13260. this.extensions = source.extensions;
  13261. return this;
  13262. };
  13263. ShaderMaterial.prototype.toJSON = function ( meta ) {
  13264. var data = Material.prototype.toJSON.call( this, meta );
  13265. data.uniforms = {};
  13266. for ( var name in this.uniforms ) {
  13267. var uniform = this.uniforms[ name ];
  13268. var value = uniform.value;
  13269. if ( value && value.isTexture ) {
  13270. data.uniforms[ name ] = {
  13271. type: 't',
  13272. value: value.toJSON( meta ).uuid
  13273. };
  13274. } else if ( value && value.isColor ) {
  13275. data.uniforms[ name ] = {
  13276. type: 'c',
  13277. value: value.getHex()
  13278. };
  13279. } else if ( value && value.isVector2 ) {
  13280. data.uniforms[ name ] = {
  13281. type: 'v2',
  13282. value: value.toArray()
  13283. };
  13284. } else if ( value && value.isVector3 ) {
  13285. data.uniforms[ name ] = {
  13286. type: 'v3',
  13287. value: value.toArray()
  13288. };
  13289. } else if ( value && value.isVector4 ) {
  13290. data.uniforms[ name ] = {
  13291. type: 'v4',
  13292. value: value.toArray()
  13293. };
  13294. } else if ( value && value.isMatrix3 ) {
  13295. data.uniforms[ name ] = {
  13296. type: 'm3',
  13297. value: value.toArray()
  13298. };
  13299. } else if ( value && value.isMatrix4 ) {
  13300. data.uniforms[ name ] = {
  13301. type: 'm4',
  13302. value: value.toArray()
  13303. };
  13304. } else {
  13305. data.uniforms[ name ] = {
  13306. value: value
  13307. };
  13308. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13309. }
  13310. }
  13311. if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; }
  13312. data.vertexShader = this.vertexShader;
  13313. data.fragmentShader = this.fragmentShader;
  13314. var extensions = {};
  13315. for ( var key in this.extensions ) {
  13316. if ( this.extensions[ key ] === true ) { extensions[ key ] = true; }
  13317. }
  13318. if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; }
  13319. return data;
  13320. };
  13321. /**
  13322. * @author mrdoob / http://mrdoob.com/
  13323. * @author mikael emtinger / http://gomo.se/
  13324. * @author WestLangley / http://github.com/WestLangley
  13325. */
  13326. function Camera() {
  13327. Object3D.call( this );
  13328. this.type = 'Camera';
  13329. this.matrixWorldInverse = new Matrix4();
  13330. this.projectionMatrix = new Matrix4();
  13331. this.projectionMatrixInverse = new Matrix4();
  13332. }
  13333. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13334. constructor: Camera,
  13335. isCamera: true,
  13336. copy: function ( source, recursive ) {
  13337. Object3D.prototype.copy.call( this, source, recursive );
  13338. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13339. this.projectionMatrix.copy( source.projectionMatrix );
  13340. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  13341. return this;
  13342. },
  13343. getWorldDirection: function ( target ) {
  13344. if ( target === undefined ) {
  13345. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  13346. target = new Vector3();
  13347. }
  13348. this.updateMatrixWorld( true );
  13349. var e = this.matrixWorld.elements;
  13350. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  13351. },
  13352. updateMatrixWorld: function ( force ) {
  13353. Object3D.prototype.updateMatrixWorld.call( this, force );
  13354. this.matrixWorldInverse.getInverse( this.matrixWorld );
  13355. },
  13356. clone: function () {
  13357. return new this.constructor().copy( this );
  13358. }
  13359. } );
  13360. /**
  13361. * @author mrdoob / http://mrdoob.com/
  13362. * @author greggman / http://games.greggman.com/
  13363. * @author zz85 / http://www.lab4games.net/zz85/blog
  13364. * @author tschw
  13365. */
  13366. function PerspectiveCamera( fov, aspect, near, far ) {
  13367. Camera.call( this );
  13368. this.type = 'PerspectiveCamera';
  13369. this.fov = fov !== undefined ? fov : 50;
  13370. this.zoom = 1;
  13371. this.near = near !== undefined ? near : 0.1;
  13372. this.far = far !== undefined ? far : 2000;
  13373. this.focus = 10;
  13374. this.aspect = aspect !== undefined ? aspect : 1;
  13375. this.view = null;
  13376. this.filmGauge = 35; // width of the film (default in millimeters)
  13377. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13378. this.updateProjectionMatrix();
  13379. }
  13380. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13381. constructor: PerspectiveCamera,
  13382. isPerspectiveCamera: true,
  13383. copy: function ( source, recursive ) {
  13384. Camera.prototype.copy.call( this, source, recursive );
  13385. this.fov = source.fov;
  13386. this.zoom = source.zoom;
  13387. this.near = source.near;
  13388. this.far = source.far;
  13389. this.focus = source.focus;
  13390. this.aspect = source.aspect;
  13391. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13392. this.filmGauge = source.filmGauge;
  13393. this.filmOffset = source.filmOffset;
  13394. return this;
  13395. },
  13396. /**
  13397. * Sets the FOV by focal length in respect to the current .filmGauge.
  13398. *
  13399. * The default film gauge is 35, so that the focal length can be specified for
  13400. * a 35mm (full frame) camera.
  13401. *
  13402. * Values for focal length and film gauge must have the same unit.
  13403. */
  13404. setFocalLength: function ( focalLength ) {
  13405. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13406. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13407. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13408. this.updateProjectionMatrix();
  13409. },
  13410. /**
  13411. * Calculates the focal length from the current .fov and .filmGauge.
  13412. */
  13413. getFocalLength: function () {
  13414. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  13415. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13416. },
  13417. getEffectiveFOV: function () {
  13418. return _Math.RAD2DEG * 2 * Math.atan(
  13419. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13420. },
  13421. getFilmWidth: function () {
  13422. // film not completely covered in portrait format (aspect < 1)
  13423. return this.filmGauge * Math.min( this.aspect, 1 );
  13424. },
  13425. getFilmHeight: function () {
  13426. // film not completely covered in landscape format (aspect > 1)
  13427. return this.filmGauge / Math.max( this.aspect, 1 );
  13428. },
  13429. /**
  13430. * Sets an offset in a larger frustum. This is useful for multi-window or
  13431. * multi-monitor/multi-machine setups.
  13432. *
  13433. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13434. * the monitors are in grid like this
  13435. *
  13436. * +---+---+---+
  13437. * | A | B | C |
  13438. * +---+---+---+
  13439. * | D | E | F |
  13440. * +---+---+---+
  13441. *
  13442. * then for each monitor you would call it like this
  13443. *
  13444. * var w = 1920;
  13445. * var h = 1080;
  13446. * var fullWidth = w * 3;
  13447. * var fullHeight = h * 2;
  13448. *
  13449. * --A--
  13450. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13451. * --B--
  13452. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13453. * --C--
  13454. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13455. * --D--
  13456. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13457. * --E--
  13458. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13459. * --F--
  13460. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13461. *
  13462. * Note there is no reason monitors have to be the same size or in a grid.
  13463. */
  13464. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  13465. this.aspect = fullWidth / fullHeight;
  13466. if ( this.view === null ) {
  13467. this.view = {
  13468. enabled: true,
  13469. fullWidth: 1,
  13470. fullHeight: 1,
  13471. offsetX: 0,
  13472. offsetY: 0,
  13473. width: 1,
  13474. height: 1
  13475. };
  13476. }
  13477. this.view.enabled = true;
  13478. this.view.fullWidth = fullWidth;
  13479. this.view.fullHeight = fullHeight;
  13480. this.view.offsetX = x;
  13481. this.view.offsetY = y;
  13482. this.view.width = width;
  13483. this.view.height = height;
  13484. this.updateProjectionMatrix();
  13485. },
  13486. clearViewOffset: function () {
  13487. if ( this.view !== null ) {
  13488. this.view.enabled = false;
  13489. }
  13490. this.updateProjectionMatrix();
  13491. },
  13492. updateProjectionMatrix: function () {
  13493. var near = this.near,
  13494. top = near * Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  13495. height = 2 * top,
  13496. width = this.aspect * height,
  13497. left = - 0.5 * width,
  13498. view = this.view;
  13499. if ( this.view !== null && this.view.enabled ) {
  13500. var fullWidth = view.fullWidth,
  13501. fullHeight = view.fullHeight;
  13502. left += view.offsetX * width / fullWidth;
  13503. top -= view.offsetY * height / fullHeight;
  13504. width *= view.width / fullWidth;
  13505. height *= view.height / fullHeight;
  13506. }
  13507. var skew = this.filmOffset;
  13508. if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); }
  13509. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  13510. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  13511. },
  13512. toJSON: function ( meta ) {
  13513. var data = Object3D.prototype.toJSON.call( this, meta );
  13514. data.object.fov = this.fov;
  13515. data.object.zoom = this.zoom;
  13516. data.object.near = this.near;
  13517. data.object.far = this.far;
  13518. data.object.focus = this.focus;
  13519. data.object.aspect = this.aspect;
  13520. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  13521. data.object.filmGauge = this.filmGauge;
  13522. data.object.filmOffset = this.filmOffset;
  13523. return data;
  13524. }
  13525. } );
  13526. /**
  13527. * Camera for rendering cube maps
  13528. * - renders scene into axis-aligned cube
  13529. *
  13530. * @author alteredq / http://alteredqualia.com/
  13531. */
  13532. var fov = 90, aspect = 1;
  13533. function CubeCamera( near, far, cubeResolution, options ) {
  13534. Object3D.call( this );
  13535. this.type = 'CubeCamera';
  13536. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  13537. cameraPX.up.set( 0, - 1, 0 );
  13538. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  13539. this.add( cameraPX );
  13540. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  13541. cameraNX.up.set( 0, - 1, 0 );
  13542. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  13543. this.add( cameraNX );
  13544. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  13545. cameraPY.up.set( 0, 0, 1 );
  13546. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  13547. this.add( cameraPY );
  13548. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  13549. cameraNY.up.set( 0, 0, - 1 );
  13550. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  13551. this.add( cameraNY );
  13552. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  13553. cameraPZ.up.set( 0, - 1, 0 );
  13554. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  13555. this.add( cameraPZ );
  13556. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  13557. cameraNZ.up.set( 0, - 1, 0 );
  13558. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  13559. this.add( cameraNZ );
  13560. options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  13561. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  13562. this.renderTarget.texture.name = "CubeCamera";
  13563. this.update = function ( renderer, scene ) {
  13564. if ( this.parent === null ) { this.updateMatrixWorld(); }
  13565. var currentRenderTarget = renderer.getRenderTarget();
  13566. var renderTarget = this.renderTarget;
  13567. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13568. renderTarget.texture.generateMipmaps = false;
  13569. renderer.setRenderTarget( renderTarget, 0 );
  13570. renderer.render( scene, cameraPX );
  13571. renderer.setRenderTarget( renderTarget, 1 );
  13572. renderer.render( scene, cameraNX );
  13573. renderer.setRenderTarget( renderTarget, 2 );
  13574. renderer.render( scene, cameraPY );
  13575. renderer.setRenderTarget( renderTarget, 3 );
  13576. renderer.render( scene, cameraNY );
  13577. renderer.setRenderTarget( renderTarget, 4 );
  13578. renderer.render( scene, cameraPZ );
  13579. renderTarget.texture.generateMipmaps = generateMipmaps;
  13580. renderer.setRenderTarget( renderTarget, 5 );
  13581. renderer.render( scene, cameraNZ );
  13582. renderer.setRenderTarget( currentRenderTarget );
  13583. };
  13584. this.clear = function ( renderer, color, depth, stencil ) {
  13585. var currentRenderTarget = renderer.getRenderTarget();
  13586. var renderTarget = this.renderTarget;
  13587. for ( var i = 0; i < 6; i ++ ) {
  13588. renderer.setRenderTarget( renderTarget, i );
  13589. renderer.clear( color, depth, stencil );
  13590. }
  13591. renderer.setRenderTarget( currentRenderTarget );
  13592. };
  13593. }
  13594. CubeCamera.prototype = Object.create( Object3D.prototype );
  13595. CubeCamera.prototype.constructor = CubeCamera;
  13596. /**
  13597. * @author alteredq / http://alteredqualia.com
  13598. * @author WestLangley / http://github.com/WestLangley
  13599. */
  13600. function WebGLRenderTargetCube( width, height, options ) {
  13601. WebGLRenderTarget.call( this, width, height, options );
  13602. }
  13603. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  13604. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  13605. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  13606. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  13607. this.texture.type = texture.type;
  13608. this.texture.format = texture.format;
  13609. this.texture.encoding = texture.encoding;
  13610. var scene = new Scene();
  13611. var shader = {
  13612. uniforms: {
  13613. tEquirect: { value: null },
  13614. },
  13615. vertexShader: [
  13616. "varying vec3 vWorldDirection;",
  13617. "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {",
  13618. " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );",
  13619. "}",
  13620. "void main() {",
  13621. " vWorldDirection = transformDirection( position, modelMatrix );",
  13622. " #include <begin_vertex>",
  13623. " #include <project_vertex>",
  13624. "}"
  13625. ].join( '\n' ),
  13626. fragmentShader: [
  13627. "uniform sampler2D tEquirect;",
  13628. "varying vec3 vWorldDirection;",
  13629. "#define RECIPROCAL_PI 0.31830988618",
  13630. "#define RECIPROCAL_PI2 0.15915494",
  13631. "void main() {",
  13632. " vec3 direction = normalize( vWorldDirection );",
  13633. " vec2 sampleUV;",
  13634. " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;",
  13635. " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  13636. " gl_FragColor = texture2D( tEquirect, sampleUV );",
  13637. "}"
  13638. ].join( '\n' ),
  13639. };
  13640. var material = new ShaderMaterial( {
  13641. type: 'CubemapFromEquirect',
  13642. uniforms: cloneUniforms( shader.uniforms ),
  13643. vertexShader: shader.vertexShader,
  13644. fragmentShader: shader.fragmentShader,
  13645. side: BackSide,
  13646. blending: NoBlending
  13647. } );
  13648. material.uniforms.tEquirect.value = texture;
  13649. var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );
  13650. scene.add( mesh );
  13651. var camera = new CubeCamera( 1, 10, 1 );
  13652. camera.renderTarget = this;
  13653. camera.renderTarget.texture.name = 'CubeCameraTexture';
  13654. camera.update( renderer, scene );
  13655. mesh.geometry.dispose();
  13656. mesh.material.dispose();
  13657. return this;
  13658. };
  13659. /**
  13660. * @author alteredq / http://alteredqualia.com/
  13661. */
  13662. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13663. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13664. this.image = { data: data || null, width: width || 1, height: height || 1 };
  13665. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13666. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13667. this.generateMipmaps = false;
  13668. this.flipY = false;
  13669. this.unpackAlignment = 1;
  13670. this.needsUpdate = true;
  13671. }
  13672. DataTexture.prototype = Object.create( Texture.prototype );
  13673. DataTexture.prototype.constructor = DataTexture;
  13674. DataTexture.prototype.isDataTexture = true;
  13675. /**
  13676. * @author bhouston / http://clara.io
  13677. */
  13678. var _vector1 = new Vector3();
  13679. var _vector2 = new Vector3();
  13680. var _normalMatrix = new Matrix3();
  13681. function Plane( normal, constant ) {
  13682. // normal is assumed to be normalized
  13683. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  13684. this.constant = ( constant !== undefined ) ? constant : 0;
  13685. }
  13686. Object.assign( Plane.prototype, {
  13687. isPlane: true,
  13688. set: function ( normal, constant ) {
  13689. this.normal.copy( normal );
  13690. this.constant = constant;
  13691. return this;
  13692. },
  13693. setComponents: function ( x, y, z, w ) {
  13694. this.normal.set( x, y, z );
  13695. this.constant = w;
  13696. return this;
  13697. },
  13698. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  13699. this.normal.copy( normal );
  13700. this.constant = - point.dot( this.normal );
  13701. return this;
  13702. },
  13703. setFromCoplanarPoints: function ( a, b, c ) {
  13704. var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  13705. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  13706. this.setFromNormalAndCoplanarPoint( normal, a );
  13707. return this;
  13708. },
  13709. clone: function () {
  13710. return new this.constructor().copy( this );
  13711. },
  13712. copy: function ( plane ) {
  13713. this.normal.copy( plane.normal );
  13714. this.constant = plane.constant;
  13715. return this;
  13716. },
  13717. normalize: function () {
  13718. // Note: will lead to a divide by zero if the plane is invalid.
  13719. var inverseNormalLength = 1.0 / this.normal.length();
  13720. this.normal.multiplyScalar( inverseNormalLength );
  13721. this.constant *= inverseNormalLength;
  13722. return this;
  13723. },
  13724. negate: function () {
  13725. this.constant *= - 1;
  13726. this.normal.negate();
  13727. return this;
  13728. },
  13729. distanceToPoint: function ( point ) {
  13730. return this.normal.dot( point ) + this.constant;
  13731. },
  13732. distanceToSphere: function ( sphere ) {
  13733. return this.distanceToPoint( sphere.center ) - sphere.radius;
  13734. },
  13735. projectPoint: function ( point, target ) {
  13736. if ( target === undefined ) {
  13737. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  13738. target = new Vector3();
  13739. }
  13740. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  13741. },
  13742. intersectLine: function ( line, target ) {
  13743. if ( target === undefined ) {
  13744. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  13745. target = new Vector3();
  13746. }
  13747. var direction = line.delta( _vector1 );
  13748. var denominator = this.normal.dot( direction );
  13749. if ( denominator === 0 ) {
  13750. // line is coplanar, return origin
  13751. if ( this.distanceToPoint( line.start ) === 0 ) {
  13752. return target.copy( line.start );
  13753. }
  13754. // Unsure if this is the correct method to handle this case.
  13755. return undefined;
  13756. }
  13757. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  13758. if ( t < 0 || t > 1 ) {
  13759. return undefined;
  13760. }
  13761. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  13762. },
  13763. intersectsLine: function ( line ) {
  13764. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  13765. var startSign = this.distanceToPoint( line.start );
  13766. var endSign = this.distanceToPoint( line.end );
  13767. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  13768. },
  13769. intersectsBox: function ( box ) {
  13770. return box.intersectsPlane( this );
  13771. },
  13772. intersectsSphere: function ( sphere ) {
  13773. return sphere.intersectsPlane( this );
  13774. },
  13775. coplanarPoint: function ( target ) {
  13776. if ( target === undefined ) {
  13777. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  13778. target = new Vector3();
  13779. }
  13780. return target.copy( this.normal ).multiplyScalar( - this.constant );
  13781. },
  13782. applyMatrix4: function ( matrix, optionalNormalMatrix ) {
  13783. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  13784. var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  13785. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  13786. this.constant = - referencePoint.dot( normal );
  13787. return this;
  13788. },
  13789. translate: function ( offset ) {
  13790. this.constant -= offset.dot( this.normal );
  13791. return this;
  13792. },
  13793. equals: function ( plane ) {
  13794. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  13795. }
  13796. } );
  13797. /**
  13798. * @author mrdoob / http://mrdoob.com/
  13799. * @author alteredq / http://alteredqualia.com/
  13800. * @author bhouston / http://clara.io
  13801. */
  13802. var _sphere$1 = new Sphere();
  13803. var _vector$5 = new Vector3();
  13804. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  13805. this.planes = [
  13806. ( p0 !== undefined ) ? p0 : new Plane(),
  13807. ( p1 !== undefined ) ? p1 : new Plane(),
  13808. ( p2 !== undefined ) ? p2 : new Plane(),
  13809. ( p3 !== undefined ) ? p3 : new Plane(),
  13810. ( p4 !== undefined ) ? p4 : new Plane(),
  13811. ( p5 !== undefined ) ? p5 : new Plane()
  13812. ];
  13813. }
  13814. Object.assign( Frustum.prototype, {
  13815. set: function ( p0, p1, p2, p3, p4, p5 ) {
  13816. var planes = this.planes;
  13817. planes[ 0 ].copy( p0 );
  13818. planes[ 1 ].copy( p1 );
  13819. planes[ 2 ].copy( p2 );
  13820. planes[ 3 ].copy( p3 );
  13821. planes[ 4 ].copy( p4 );
  13822. planes[ 5 ].copy( p5 );
  13823. return this;
  13824. },
  13825. clone: function () {
  13826. return new this.constructor().copy( this );
  13827. },
  13828. copy: function ( frustum ) {
  13829. var planes = this.planes;
  13830. for ( var i = 0; i < 6; i ++ ) {
  13831. planes[ i ].copy( frustum.planes[ i ] );
  13832. }
  13833. return this;
  13834. },
  13835. setFromMatrix: function ( m ) {
  13836. var planes = this.planes;
  13837. var me = m.elements;
  13838. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  13839. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  13840. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  13841. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  13842. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  13843. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  13844. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  13845. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  13846. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  13847. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  13848. return this;
  13849. },
  13850. intersectsObject: function ( object ) {
  13851. var geometry = object.geometry;
  13852. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  13853. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  13854. return this.intersectsSphere( _sphere$1 );
  13855. },
  13856. intersectsSprite: function ( sprite ) {
  13857. _sphere$1.center.set( 0, 0, 0 );
  13858. _sphere$1.radius = 0.7071067811865476;
  13859. _sphere$1.applyMatrix4( sprite.matrixWorld );
  13860. return this.intersectsSphere( _sphere$1 );
  13861. },
  13862. intersectsSphere: function ( sphere ) {
  13863. var planes = this.planes;
  13864. var center = sphere.center;
  13865. var negRadius = - sphere.radius;
  13866. for ( var i = 0; i < 6; i ++ ) {
  13867. var distance = planes[ i ].distanceToPoint( center );
  13868. if ( distance < negRadius ) {
  13869. return false;
  13870. }
  13871. }
  13872. return true;
  13873. },
  13874. intersectsBox: function ( box ) {
  13875. var planes = this.planes;
  13876. for ( var i = 0; i < 6; i ++ ) {
  13877. var plane = planes[ i ];
  13878. // corner at max distance
  13879. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  13880. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  13881. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  13882. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  13883. return false;
  13884. }
  13885. }
  13886. return true;
  13887. },
  13888. containsPoint: function ( point ) {
  13889. var planes = this.planes;
  13890. for ( var i = 0; i < 6; i ++ ) {
  13891. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  13892. return false;
  13893. }
  13894. }
  13895. return true;
  13896. }
  13897. } );
  13898. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  13899. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  13900. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  13901. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  13902. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  13903. var begin_vertex = "vec3 transformed = vec3( position );";
  13904. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  13905. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  13906. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  13907. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  13908. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  13909. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  13910. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  13911. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  13912. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  13913. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  13914. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  13915. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 projectionMatrix ) {\n return projectionMatrix[ 2 ][ 3 ] == - 1.0;\n}";
  13916. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";
  13917. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  13918. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  13919. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  13920. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  13921. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  13922. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  13923. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  13924. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  13925. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  13926. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  13927. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  13928. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  13929. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  13930. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  13931. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  13932. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  13933. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif";
  13934. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  13935. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  13936. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif";
  13937. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  13938. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  13939. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  13940. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  13941. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  13942. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  13943. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  13944. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  13945. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  13946. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 1.0 ? log2( vFragDepth ) * logDepthBufFC * 0.5 : gl_FragCoord.z;\n#endif";
  13947. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  13948. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  13949. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  13950. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  13951. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  13952. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";
  13953. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  13954. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  13955. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  13956. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif";
  13957. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  13958. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  13959. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  13960. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  13961. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 normalScale, in sampler2D normalMap ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvec3 NfromST = cross( S, T );\n\t\t\tif( dot( NfromST, N ) > 0.0 ) {\n\t\t\t\tS *= -1.0;\n\t\t\t\tT *= -1.0;\n\t\t\t}\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  13962. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  13963. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif";
  13964. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  13965. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  13966. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  13967. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;";
  13968. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  13969. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  13970. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  13971. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  13972. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn decodeHalfRGBA( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat 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\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  13973. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  13974. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  13975. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  13976. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  13977. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  13978. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  13979. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  13980. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  13981. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  13982. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  13983. var tonemapping_pars_fragment = "#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
  13984. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  13985. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  13986. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  13987. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  13988. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  13989. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  13990. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif";
  13991. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  13992. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  13993. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  13994. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  13995. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";
  13996. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}";
  13997. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  13998. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  13999. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14000. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  14001. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14002. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14003. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\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 <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14004. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  14005. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14006. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14007. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14008. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  14009. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14010. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14011. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <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_normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14012. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14013. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  14014. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  14015. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14016. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  14017. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}";
  14018. var shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14019. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14020. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14021. var ShaderChunk = {
  14022. alphamap_fragment: alphamap_fragment,
  14023. alphamap_pars_fragment: alphamap_pars_fragment,
  14024. alphatest_fragment: alphatest_fragment,
  14025. aomap_fragment: aomap_fragment,
  14026. aomap_pars_fragment: aomap_pars_fragment,
  14027. begin_vertex: begin_vertex,
  14028. beginnormal_vertex: beginnormal_vertex,
  14029. bsdfs: bsdfs,
  14030. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14031. clipping_planes_fragment: clipping_planes_fragment,
  14032. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14033. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14034. clipping_planes_vertex: clipping_planes_vertex,
  14035. color_fragment: color_fragment,
  14036. color_pars_fragment: color_pars_fragment,
  14037. color_pars_vertex: color_pars_vertex,
  14038. color_vertex: color_vertex,
  14039. common: common,
  14040. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14041. defaultnormal_vertex: defaultnormal_vertex,
  14042. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14043. displacementmap_vertex: displacementmap_vertex,
  14044. emissivemap_fragment: emissivemap_fragment,
  14045. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14046. encodings_fragment: encodings_fragment,
  14047. encodings_pars_fragment: encodings_pars_fragment,
  14048. envmap_fragment: envmap_fragment,
  14049. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14050. envmap_pars_fragment: envmap_pars_fragment,
  14051. envmap_pars_vertex: envmap_pars_vertex,
  14052. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14053. envmap_vertex: envmap_vertex,
  14054. fog_vertex: fog_vertex,
  14055. fog_pars_vertex: fog_pars_vertex,
  14056. fog_fragment: fog_fragment,
  14057. fog_pars_fragment: fog_pars_fragment,
  14058. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14059. lightmap_fragment: lightmap_fragment,
  14060. lightmap_pars_fragment: lightmap_pars_fragment,
  14061. lights_lambert_vertex: lights_lambert_vertex,
  14062. lights_pars_begin: lights_pars_begin,
  14063. lights_phong_fragment: lights_phong_fragment,
  14064. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14065. lights_physical_fragment: lights_physical_fragment,
  14066. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14067. lights_fragment_begin: lights_fragment_begin,
  14068. lights_fragment_maps: lights_fragment_maps,
  14069. lights_fragment_end: lights_fragment_end,
  14070. logdepthbuf_fragment: logdepthbuf_fragment,
  14071. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14072. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14073. logdepthbuf_vertex: logdepthbuf_vertex,
  14074. map_fragment: map_fragment,
  14075. map_pars_fragment: map_pars_fragment,
  14076. map_particle_fragment: map_particle_fragment,
  14077. map_particle_pars_fragment: map_particle_pars_fragment,
  14078. metalnessmap_fragment: metalnessmap_fragment,
  14079. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14080. morphnormal_vertex: morphnormal_vertex,
  14081. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14082. morphtarget_vertex: morphtarget_vertex,
  14083. normal_fragment_begin: normal_fragment_begin,
  14084. normal_fragment_maps: normal_fragment_maps,
  14085. normalmap_pars_fragment: normalmap_pars_fragment,
  14086. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14087. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14088. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  14089. packing: packing,
  14090. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14091. project_vertex: project_vertex,
  14092. dithering_fragment: dithering_fragment,
  14093. dithering_pars_fragment: dithering_pars_fragment,
  14094. roughnessmap_fragment: roughnessmap_fragment,
  14095. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14096. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14097. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14098. shadowmap_vertex: shadowmap_vertex,
  14099. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14100. skinbase_vertex: skinbase_vertex,
  14101. skinning_pars_vertex: skinning_pars_vertex,
  14102. skinning_vertex: skinning_vertex,
  14103. skinnormal_vertex: skinnormal_vertex,
  14104. specularmap_fragment: specularmap_fragment,
  14105. specularmap_pars_fragment: specularmap_pars_fragment,
  14106. tonemapping_fragment: tonemapping_fragment,
  14107. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14108. uv_pars_fragment: uv_pars_fragment,
  14109. uv_pars_vertex: uv_pars_vertex,
  14110. uv_vertex: uv_vertex,
  14111. uv2_pars_fragment: uv2_pars_fragment,
  14112. uv2_pars_vertex: uv2_pars_vertex,
  14113. uv2_vertex: uv2_vertex,
  14114. worldpos_vertex: worldpos_vertex,
  14115. background_frag: background_frag,
  14116. background_vert: background_vert,
  14117. cube_frag: cube_frag,
  14118. cube_vert: cube_vert,
  14119. depth_frag: depth_frag,
  14120. depth_vert: depth_vert,
  14121. distanceRGBA_frag: distanceRGBA_frag,
  14122. distanceRGBA_vert: distanceRGBA_vert,
  14123. equirect_frag: equirect_frag,
  14124. equirect_vert: equirect_vert,
  14125. linedashed_frag: linedashed_frag,
  14126. linedashed_vert: linedashed_vert,
  14127. meshbasic_frag: meshbasic_frag,
  14128. meshbasic_vert: meshbasic_vert,
  14129. meshlambert_frag: meshlambert_frag,
  14130. meshlambert_vert: meshlambert_vert,
  14131. meshmatcap_frag: meshmatcap_frag,
  14132. meshmatcap_vert: meshmatcap_vert,
  14133. meshphong_frag: meshphong_frag,
  14134. meshphong_vert: meshphong_vert,
  14135. meshphysical_frag: meshphysical_frag,
  14136. meshphysical_vert: meshphysical_vert,
  14137. normal_frag: normal_frag,
  14138. normal_vert: normal_vert,
  14139. points_frag: points_frag,
  14140. points_vert: points_vert,
  14141. shadow_frag: shadow_frag,
  14142. shadow_vert: shadow_vert,
  14143. sprite_frag: sprite_frag,
  14144. sprite_vert: sprite_vert
  14145. };
  14146. /**
  14147. * Uniforms library for shared webgl shaders
  14148. */
  14149. var UniformsLib = {
  14150. common: {
  14151. diffuse: { value: new Color( 0xeeeeee ) },
  14152. opacity: { value: 1.0 },
  14153. map: { value: null },
  14154. uvTransform: { value: new Matrix3() },
  14155. alphaMap: { value: null },
  14156. },
  14157. specularmap: {
  14158. specularMap: { value: null },
  14159. },
  14160. envmap: {
  14161. envMap: { value: null },
  14162. flipEnvMap: { value: - 1 },
  14163. reflectivity: { value: 1.0 },
  14164. refractionRatio: { value: 0.98 },
  14165. maxMipLevel: { value: 0 }
  14166. },
  14167. aomap: {
  14168. aoMap: { value: null },
  14169. aoMapIntensity: { value: 1 }
  14170. },
  14171. lightmap: {
  14172. lightMap: { value: null },
  14173. lightMapIntensity: { value: 1 }
  14174. },
  14175. emissivemap: {
  14176. emissiveMap: { value: null }
  14177. },
  14178. bumpmap: {
  14179. bumpMap: { value: null },
  14180. bumpScale: { value: 1 }
  14181. },
  14182. normalmap: {
  14183. normalMap: { value: null },
  14184. normalScale: { value: new Vector2( 1, 1 ) }
  14185. },
  14186. displacementmap: {
  14187. displacementMap: { value: null },
  14188. displacementScale: { value: 1 },
  14189. displacementBias: { value: 0 }
  14190. },
  14191. roughnessmap: {
  14192. roughnessMap: { value: null }
  14193. },
  14194. metalnessmap: {
  14195. metalnessMap: { value: null }
  14196. },
  14197. gradientmap: {
  14198. gradientMap: { value: null }
  14199. },
  14200. fog: {
  14201. fogDensity: { value: 0.00025 },
  14202. fogNear: { value: 1 },
  14203. fogFar: { value: 2000 },
  14204. fogColor: { value: new Color( 0xffffff ) }
  14205. },
  14206. lights: {
  14207. ambientLightColor: { value: [] },
  14208. lightProbe: { value: [] },
  14209. directionalLights: { value: [], properties: {
  14210. direction: {},
  14211. color: {},
  14212. shadow: {},
  14213. shadowBias: {},
  14214. shadowRadius: {},
  14215. shadowMapSize: {}
  14216. } },
  14217. directionalShadowMap: { value: [] },
  14218. directionalShadowMatrix: { value: [] },
  14219. spotLights: { value: [], properties: {
  14220. color: {},
  14221. position: {},
  14222. direction: {},
  14223. distance: {},
  14224. coneCos: {},
  14225. penumbraCos: {},
  14226. decay: {},
  14227. shadow: {},
  14228. shadowBias: {},
  14229. shadowRadius: {},
  14230. shadowMapSize: {}
  14231. } },
  14232. spotShadowMap: { value: [] },
  14233. spotShadowMatrix: { value: [] },
  14234. pointLights: { value: [], properties: {
  14235. color: {},
  14236. position: {},
  14237. decay: {},
  14238. distance: {},
  14239. shadow: {},
  14240. shadowBias: {},
  14241. shadowRadius: {},
  14242. shadowMapSize: {},
  14243. shadowCameraNear: {},
  14244. shadowCameraFar: {}
  14245. } },
  14246. pointShadowMap: { value: [] },
  14247. pointShadowMatrix: { value: [] },
  14248. hemisphereLights: { value: [], properties: {
  14249. direction: {},
  14250. skyColor: {},
  14251. groundColor: {}
  14252. } },
  14253. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14254. rectAreaLights: { value: [], properties: {
  14255. color: {},
  14256. position: {},
  14257. width: {},
  14258. height: {}
  14259. } }
  14260. },
  14261. points: {
  14262. diffuse: { value: new Color( 0xeeeeee ) },
  14263. opacity: { value: 1.0 },
  14264. size: { value: 1.0 },
  14265. scale: { value: 1.0 },
  14266. map: { value: null },
  14267. uvTransform: { value: new Matrix3() }
  14268. },
  14269. sprite: {
  14270. diffuse: { value: new Color( 0xeeeeee ) },
  14271. opacity: { value: 1.0 },
  14272. center: { value: new Vector2( 0.5, 0.5 ) },
  14273. rotation: { value: 0.0 },
  14274. map: { value: null },
  14275. uvTransform: { value: new Matrix3() }
  14276. }
  14277. };
  14278. /**
  14279. * @author alteredq / http://alteredqualia.com/
  14280. * @author mrdoob / http://mrdoob.com/
  14281. * @author mikael emtinger / http://gomo.se/
  14282. */
  14283. var ShaderLib = {
  14284. basic: {
  14285. uniforms: mergeUniforms( [
  14286. UniformsLib.common,
  14287. UniformsLib.specularmap,
  14288. UniformsLib.envmap,
  14289. UniformsLib.aomap,
  14290. UniformsLib.lightmap,
  14291. UniformsLib.fog
  14292. ] ),
  14293. vertexShader: ShaderChunk.meshbasic_vert,
  14294. fragmentShader: ShaderChunk.meshbasic_frag
  14295. },
  14296. lambert: {
  14297. uniforms: mergeUniforms( [
  14298. UniformsLib.common,
  14299. UniformsLib.specularmap,
  14300. UniformsLib.envmap,
  14301. UniformsLib.aomap,
  14302. UniformsLib.lightmap,
  14303. UniformsLib.emissivemap,
  14304. UniformsLib.fog,
  14305. UniformsLib.lights,
  14306. {
  14307. emissive: { value: new Color( 0x000000 ) }
  14308. }
  14309. ] ),
  14310. vertexShader: ShaderChunk.meshlambert_vert,
  14311. fragmentShader: ShaderChunk.meshlambert_frag
  14312. },
  14313. phong: {
  14314. uniforms: mergeUniforms( [
  14315. UniformsLib.common,
  14316. UniformsLib.specularmap,
  14317. UniformsLib.envmap,
  14318. UniformsLib.aomap,
  14319. UniformsLib.lightmap,
  14320. UniformsLib.emissivemap,
  14321. UniformsLib.bumpmap,
  14322. UniformsLib.normalmap,
  14323. UniformsLib.displacementmap,
  14324. UniformsLib.gradientmap,
  14325. UniformsLib.fog,
  14326. UniformsLib.lights,
  14327. {
  14328. emissive: { value: new Color( 0x000000 ) },
  14329. specular: { value: new Color( 0x111111 ) },
  14330. shininess: { value: 30 }
  14331. }
  14332. ] ),
  14333. vertexShader: ShaderChunk.meshphong_vert,
  14334. fragmentShader: ShaderChunk.meshphong_frag
  14335. },
  14336. standard: {
  14337. uniforms: mergeUniforms( [
  14338. UniformsLib.common,
  14339. UniformsLib.envmap,
  14340. UniformsLib.aomap,
  14341. UniformsLib.lightmap,
  14342. UniformsLib.emissivemap,
  14343. UniformsLib.bumpmap,
  14344. UniformsLib.normalmap,
  14345. UniformsLib.displacementmap,
  14346. UniformsLib.roughnessmap,
  14347. UniformsLib.metalnessmap,
  14348. UniformsLib.fog,
  14349. UniformsLib.lights,
  14350. {
  14351. emissive: { value: new Color( 0x000000 ) },
  14352. roughness: { value: 0.5 },
  14353. metalness: { value: 0.5 },
  14354. envMapIntensity: { value: 1 } // temporary
  14355. }
  14356. ] ),
  14357. vertexShader: ShaderChunk.meshphysical_vert,
  14358. fragmentShader: ShaderChunk.meshphysical_frag
  14359. },
  14360. matcap: {
  14361. uniforms: mergeUniforms( [
  14362. UniformsLib.common,
  14363. UniformsLib.bumpmap,
  14364. UniformsLib.normalmap,
  14365. UniformsLib.displacementmap,
  14366. UniformsLib.fog,
  14367. {
  14368. matcap: { value: null }
  14369. }
  14370. ] ),
  14371. vertexShader: ShaderChunk.meshmatcap_vert,
  14372. fragmentShader: ShaderChunk.meshmatcap_frag
  14373. },
  14374. points: {
  14375. uniforms: mergeUniforms( [
  14376. UniformsLib.points,
  14377. UniformsLib.fog
  14378. ] ),
  14379. vertexShader: ShaderChunk.points_vert,
  14380. fragmentShader: ShaderChunk.points_frag
  14381. },
  14382. dashed: {
  14383. uniforms: mergeUniforms( [
  14384. UniformsLib.common,
  14385. UniformsLib.fog,
  14386. {
  14387. scale: { value: 1 },
  14388. dashSize: { value: 1 },
  14389. totalSize: { value: 2 }
  14390. }
  14391. ] ),
  14392. vertexShader: ShaderChunk.linedashed_vert,
  14393. fragmentShader: ShaderChunk.linedashed_frag
  14394. },
  14395. depth: {
  14396. uniforms: mergeUniforms( [
  14397. UniformsLib.common,
  14398. UniformsLib.displacementmap
  14399. ] ),
  14400. vertexShader: ShaderChunk.depth_vert,
  14401. fragmentShader: ShaderChunk.depth_frag
  14402. },
  14403. normal: {
  14404. uniforms: mergeUniforms( [
  14405. UniformsLib.common,
  14406. UniformsLib.bumpmap,
  14407. UniformsLib.normalmap,
  14408. UniformsLib.displacementmap,
  14409. {
  14410. opacity: { value: 1.0 }
  14411. }
  14412. ] ),
  14413. vertexShader: ShaderChunk.normal_vert,
  14414. fragmentShader: ShaderChunk.normal_frag
  14415. },
  14416. sprite: {
  14417. uniforms: mergeUniforms( [
  14418. UniformsLib.sprite,
  14419. UniformsLib.fog
  14420. ] ),
  14421. vertexShader: ShaderChunk.sprite_vert,
  14422. fragmentShader: ShaderChunk.sprite_frag
  14423. },
  14424. background: {
  14425. uniforms: {
  14426. uvTransform: { value: new Matrix3() },
  14427. t2D: { value: null },
  14428. },
  14429. vertexShader: ShaderChunk.background_vert,
  14430. fragmentShader: ShaderChunk.background_frag
  14431. },
  14432. /* -------------------------------------------------------------------------
  14433. // Cube map shader
  14434. ------------------------------------------------------------------------- */
  14435. cube: {
  14436. uniforms: {
  14437. tCube: { value: null },
  14438. tFlip: { value: - 1 },
  14439. opacity: { value: 1.0 }
  14440. },
  14441. vertexShader: ShaderChunk.cube_vert,
  14442. fragmentShader: ShaderChunk.cube_frag
  14443. },
  14444. equirect: {
  14445. uniforms: {
  14446. tEquirect: { value: null },
  14447. },
  14448. vertexShader: ShaderChunk.equirect_vert,
  14449. fragmentShader: ShaderChunk.equirect_frag
  14450. },
  14451. distanceRGBA: {
  14452. uniforms: mergeUniforms( [
  14453. UniformsLib.common,
  14454. UniformsLib.displacementmap,
  14455. {
  14456. referencePosition: { value: new Vector3() },
  14457. nearDistance: { value: 1 },
  14458. farDistance: { value: 1000 }
  14459. }
  14460. ] ),
  14461. vertexShader: ShaderChunk.distanceRGBA_vert,
  14462. fragmentShader: ShaderChunk.distanceRGBA_frag
  14463. },
  14464. shadow: {
  14465. uniforms: mergeUniforms( [
  14466. UniformsLib.lights,
  14467. UniformsLib.fog,
  14468. {
  14469. color: { value: new Color( 0x00000 ) },
  14470. opacity: { value: 1.0 }
  14471. } ] ),
  14472. vertexShader: ShaderChunk.shadow_vert,
  14473. fragmentShader: ShaderChunk.shadow_frag
  14474. }
  14475. };
  14476. ShaderLib.physical = {
  14477. uniforms: mergeUniforms( [
  14478. ShaderLib.standard.uniforms,
  14479. {
  14480. transparency: { value: 0 },
  14481. clearcoat: { value: 0 },
  14482. clearcoatRoughness: { value: 0 },
  14483. sheen: { value: new Color( 0x000000 ) },
  14484. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  14485. clearcoatNormalMap: { value: null },
  14486. }
  14487. ] ),
  14488. vertexShader: ShaderChunk.meshphysical_vert,
  14489. fragmentShader: ShaderChunk.meshphysical_frag
  14490. };
  14491. /**
  14492. * @author mrdoob / http://mrdoob.com/
  14493. */
  14494. function WebGLAnimation() {
  14495. var context = null;
  14496. var isAnimating = false;
  14497. var animationLoop = null;
  14498. function onAnimationFrame( time, frame ) {
  14499. if ( isAnimating === false ) { return; }
  14500. animationLoop( time, frame );
  14501. context.requestAnimationFrame( onAnimationFrame );
  14502. }
  14503. return {
  14504. start: function () {
  14505. if ( isAnimating === true ) { return; }
  14506. if ( animationLoop === null ) { return; }
  14507. context.requestAnimationFrame( onAnimationFrame );
  14508. isAnimating = true;
  14509. },
  14510. stop: function () {
  14511. isAnimating = false;
  14512. },
  14513. setAnimationLoop: function ( callback ) {
  14514. animationLoop = callback;
  14515. },
  14516. setContext: function ( value ) {
  14517. context = value;
  14518. }
  14519. };
  14520. }
  14521. /**
  14522. * @author mrdoob / http://mrdoob.com/
  14523. */
  14524. function WebGLAttributes( gl ) {
  14525. var buffers = new WeakMap();
  14526. function createBuffer( attribute, bufferType ) {
  14527. var array = attribute.array;
  14528. var usage = attribute.dynamic ? 35048 : 35044;
  14529. var buffer = gl.createBuffer();
  14530. gl.bindBuffer( bufferType, buffer );
  14531. gl.bufferData( bufferType, array, usage );
  14532. attribute.onUploadCallback();
  14533. var type = 5126;
  14534. if ( array instanceof Float32Array ) {
  14535. type = 5126;
  14536. } else if ( array instanceof Float64Array ) {
  14537. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  14538. } else if ( array instanceof Uint16Array ) {
  14539. type = 5123;
  14540. } else if ( array instanceof Int16Array ) {
  14541. type = 5122;
  14542. } else if ( array instanceof Uint32Array ) {
  14543. type = 5125;
  14544. } else if ( array instanceof Int32Array ) {
  14545. type = 5124;
  14546. } else if ( array instanceof Int8Array ) {
  14547. type = 5120;
  14548. } else if ( array instanceof Uint8Array ) {
  14549. type = 5121;
  14550. }
  14551. return {
  14552. buffer: buffer,
  14553. type: type,
  14554. bytesPerElement: array.BYTES_PER_ELEMENT,
  14555. version: attribute.version
  14556. };
  14557. }
  14558. function updateBuffer( buffer, attribute, bufferType ) {
  14559. var array = attribute.array;
  14560. var updateRange = attribute.updateRange;
  14561. gl.bindBuffer( bufferType, buffer );
  14562. if ( attribute.dynamic === false ) {
  14563. gl.bufferData( bufferType, array, 35044 );
  14564. } else if ( updateRange.count === - 1 ) {
  14565. // Not using update ranges
  14566. gl.bufferSubData( bufferType, 0, array );
  14567. } else if ( updateRange.count === 0 ) {
  14568. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  14569. } else {
  14570. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  14571. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  14572. updateRange.count = - 1; // reset range
  14573. }
  14574. }
  14575. //
  14576. function get( attribute ) {
  14577. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14578. return buffers.get( attribute );
  14579. }
  14580. function remove( attribute ) {
  14581. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14582. var data = buffers.get( attribute );
  14583. if ( data ) {
  14584. gl.deleteBuffer( data.buffer );
  14585. buffers.delete( attribute );
  14586. }
  14587. }
  14588. function update( attribute, bufferType ) {
  14589. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14590. var data = buffers.get( attribute );
  14591. if ( data === undefined ) {
  14592. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  14593. } else if ( data.version < attribute.version ) {
  14594. updateBuffer( data.buffer, attribute, bufferType );
  14595. data.version = attribute.version;
  14596. }
  14597. }
  14598. return {
  14599. get: get,
  14600. remove: remove,
  14601. update: update
  14602. };
  14603. }
  14604. /**
  14605. * @author mrdoob / http://mrdoob.com/
  14606. * @author Mugen87 / https://github.com/Mugen87
  14607. */
  14608. // PlaneGeometry
  14609. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  14610. Geometry.call( this );
  14611. this.type = 'PlaneGeometry';
  14612. this.parameters = {
  14613. width: width,
  14614. height: height,
  14615. widthSegments: widthSegments,
  14616. heightSegments: heightSegments
  14617. };
  14618. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  14619. this.mergeVertices();
  14620. }
  14621. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  14622. PlaneGeometry.prototype.constructor = PlaneGeometry;
  14623. // PlaneBufferGeometry
  14624. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  14625. BufferGeometry.call( this );
  14626. this.type = 'PlaneBufferGeometry';
  14627. this.parameters = {
  14628. width: width,
  14629. height: height,
  14630. widthSegments: widthSegments,
  14631. heightSegments: heightSegments
  14632. };
  14633. width = width || 1;
  14634. height = height || 1;
  14635. var width_half = width / 2;
  14636. var height_half = height / 2;
  14637. var gridX = Math.floor( widthSegments ) || 1;
  14638. var gridY = Math.floor( heightSegments ) || 1;
  14639. var gridX1 = gridX + 1;
  14640. var gridY1 = gridY + 1;
  14641. var segment_width = width / gridX;
  14642. var segment_height = height / gridY;
  14643. var ix, iy;
  14644. // buffers
  14645. var indices = [];
  14646. var vertices = [];
  14647. var normals = [];
  14648. var uvs = [];
  14649. // generate vertices, normals and uvs
  14650. for ( iy = 0; iy < gridY1; iy ++ ) {
  14651. var y = iy * segment_height - height_half;
  14652. for ( ix = 0; ix < gridX1; ix ++ ) {
  14653. var x = ix * segment_width - width_half;
  14654. vertices.push( x, - y, 0 );
  14655. normals.push( 0, 0, 1 );
  14656. uvs.push( ix / gridX );
  14657. uvs.push( 1 - ( iy / gridY ) );
  14658. }
  14659. }
  14660. // indices
  14661. for ( iy = 0; iy < gridY; iy ++ ) {
  14662. for ( ix = 0; ix < gridX; ix ++ ) {
  14663. var a = ix + gridX1 * iy;
  14664. var b = ix + gridX1 * ( iy + 1 );
  14665. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14666. var d = ( ix + 1 ) + gridX1 * iy;
  14667. // faces
  14668. indices.push( a, b, d );
  14669. indices.push( b, c, d );
  14670. }
  14671. }
  14672. // build geometry
  14673. this.setIndex( indices );
  14674. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14675. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14676. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14677. }
  14678. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14679. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  14680. /**
  14681. * @author mrdoob / http://mrdoob.com/
  14682. */
  14683. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  14684. var clearColor = new Color( 0x000000 );
  14685. var clearAlpha = 0;
  14686. var planeMesh;
  14687. var boxMesh;
  14688. // Store the current background texture and its `version`
  14689. // so we can recompile the material accordingly.
  14690. var currentBackground = null;
  14691. var currentBackgroundVersion = 0;
  14692. function render( renderList, scene, camera, forceClear ) {
  14693. var background = scene.background;
  14694. // Ignore background in AR
  14695. // TODO: Reconsider this.
  14696. var vr = renderer.vr;
  14697. var session = vr.getSession && vr.getSession();
  14698. if ( session && session.environmentBlendMode === 'additive' ) {
  14699. background = null;
  14700. }
  14701. if ( background === null ) {
  14702. setClear( clearColor, clearAlpha );
  14703. currentBackground = null;
  14704. currentBackgroundVersion = 0;
  14705. } else if ( background && background.isColor ) {
  14706. setClear( background, 1 );
  14707. forceClear = true;
  14708. currentBackground = null;
  14709. currentBackgroundVersion = 0;
  14710. }
  14711. if ( renderer.autoClear || forceClear ) {
  14712. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  14713. }
  14714. if ( background && ( background.isCubeTexture || background.isWebGLRenderTargetCube ) ) {
  14715. if ( boxMesh === undefined ) {
  14716. boxMesh = new Mesh(
  14717. new BoxBufferGeometry( 1, 1, 1 ),
  14718. new ShaderMaterial( {
  14719. type: 'BackgroundCubeMaterial',
  14720. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  14721. vertexShader: ShaderLib.cube.vertexShader,
  14722. fragmentShader: ShaderLib.cube.fragmentShader,
  14723. side: BackSide,
  14724. depthTest: false,
  14725. depthWrite: false,
  14726. fog: false
  14727. } )
  14728. );
  14729. boxMesh.geometry.removeAttribute( 'normal' );
  14730. boxMesh.geometry.removeAttribute( 'uv' );
  14731. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14732. this.matrixWorld.copyPosition( camera.matrixWorld );
  14733. };
  14734. // enable code injection for non-built-in material
  14735. Object.defineProperty( boxMesh.material, 'map', {
  14736. get: function () {
  14737. return this.uniforms.tCube.value;
  14738. }
  14739. } );
  14740. objects.update( boxMesh );
  14741. }
  14742. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  14743. boxMesh.material.uniforms.tCube.value = texture;
  14744. boxMesh.material.uniforms.tFlip.value = ( background.isWebGLRenderTargetCube ) ? 1 : - 1;
  14745. if ( currentBackground !== background ||
  14746. currentBackgroundVersion !== texture.version ) {
  14747. boxMesh.material.needsUpdate = true;
  14748. currentBackground = background;
  14749. currentBackgroundVersion = texture.version;
  14750. }
  14751. // push to the pre-sorted opaque render list
  14752. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  14753. } else if ( background && background.isTexture ) {
  14754. if ( planeMesh === undefined ) {
  14755. planeMesh = new Mesh(
  14756. new PlaneBufferGeometry( 2, 2 ),
  14757. new ShaderMaterial( {
  14758. type: 'BackgroundMaterial',
  14759. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  14760. vertexShader: ShaderLib.background.vertexShader,
  14761. fragmentShader: ShaderLib.background.fragmentShader,
  14762. side: FrontSide,
  14763. depthTest: false,
  14764. depthWrite: false,
  14765. fog: false
  14766. } )
  14767. );
  14768. planeMesh.geometry.removeAttribute( 'normal' );
  14769. // enable code injection for non-built-in material
  14770. Object.defineProperty( planeMesh.material, 'map', {
  14771. get: function () {
  14772. return this.uniforms.t2D.value;
  14773. }
  14774. } );
  14775. objects.update( planeMesh );
  14776. }
  14777. planeMesh.material.uniforms.t2D.value = background;
  14778. if ( background.matrixAutoUpdate === true ) {
  14779. background.updateMatrix();
  14780. }
  14781. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  14782. if ( currentBackground !== background ||
  14783. currentBackgroundVersion !== background.version ) {
  14784. planeMesh.material.needsUpdate = true;
  14785. currentBackground = background;
  14786. currentBackgroundVersion = background.version;
  14787. }
  14788. // push to the pre-sorted opaque render list
  14789. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  14790. }
  14791. }
  14792. function setClear( color, alpha ) {
  14793. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  14794. }
  14795. return {
  14796. getClearColor: function () {
  14797. return clearColor;
  14798. },
  14799. setClearColor: function ( color, alpha ) {
  14800. clearColor.set( color );
  14801. clearAlpha = alpha !== undefined ? alpha : 1;
  14802. setClear( clearColor, clearAlpha );
  14803. },
  14804. getClearAlpha: function () {
  14805. return clearAlpha;
  14806. },
  14807. setClearAlpha: function ( alpha ) {
  14808. clearAlpha = alpha;
  14809. setClear( clearColor, clearAlpha );
  14810. },
  14811. render: render
  14812. };
  14813. }
  14814. /**
  14815. * @author mrdoob / http://mrdoob.com/
  14816. */
  14817. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  14818. var mode;
  14819. function setMode( value ) {
  14820. mode = value;
  14821. }
  14822. function render( start, count ) {
  14823. gl.drawArrays( mode, start, count );
  14824. info.update( count, mode );
  14825. }
  14826. function renderInstances( geometry, start, count ) {
  14827. var extension, methodName;
  14828. if ( capabilities.isWebGL2 ) {
  14829. extension = gl;
  14830. methodName = 'drawArraysInstanced';
  14831. } else {
  14832. extension = extensions.get( 'ANGLE_instanced_arrays' );
  14833. methodName = 'drawArraysInstancedANGLE';
  14834. if ( extension === null ) {
  14835. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14836. return;
  14837. }
  14838. }
  14839. extension[ methodName ]( mode, start, count, geometry.maxInstancedCount );
  14840. info.update( count, mode, geometry.maxInstancedCount );
  14841. }
  14842. //
  14843. this.setMode = setMode;
  14844. this.render = render;
  14845. this.renderInstances = renderInstances;
  14846. }
  14847. /**
  14848. * @author mrdoob / http://mrdoob.com/
  14849. */
  14850. function WebGLCapabilities( gl, extensions, parameters ) {
  14851. var maxAnisotropy;
  14852. function getMaxAnisotropy() {
  14853. if ( maxAnisotropy !== undefined ) { return maxAnisotropy; }
  14854. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14855. if ( extension !== null ) {
  14856. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14857. } else {
  14858. maxAnisotropy = 0;
  14859. }
  14860. return maxAnisotropy;
  14861. }
  14862. function getMaxPrecision( precision ) {
  14863. if ( precision === 'highp' ) {
  14864. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  14865. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  14866. return 'highp';
  14867. }
  14868. precision = 'mediump';
  14869. }
  14870. if ( precision === 'mediump' ) {
  14871. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  14872. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  14873. return 'mediump';
  14874. }
  14875. }
  14876. return 'lowp';
  14877. }
  14878. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  14879. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  14880. var maxPrecision = getMaxPrecision( precision );
  14881. if ( maxPrecision !== precision ) {
  14882. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  14883. precision = maxPrecision;
  14884. }
  14885. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  14886. var maxTextures = gl.getParameter( 34930 );
  14887. var maxVertexTextures = gl.getParameter( 35660 );
  14888. var maxTextureSize = gl.getParameter( 3379 );
  14889. var maxCubemapSize = gl.getParameter( 34076 );
  14890. var maxAttributes = gl.getParameter( 34921 );
  14891. var maxVertexUniforms = gl.getParameter( 36347 );
  14892. var maxVaryings = gl.getParameter( 36348 );
  14893. var maxFragmentUniforms = gl.getParameter( 36349 );
  14894. var vertexTextures = maxVertexTextures > 0;
  14895. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  14896. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  14897. var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  14898. var multiviewExt = extensions.get( 'OVR_multiview2' );
  14899. var multiview = isWebGL2 && !! multiviewExt && ! gl.getContextAttributes().antialias;
  14900. var maxMultiviewViews = multiview ? gl.getParameter( multiviewExt.MAX_VIEWS_OVR ) : 0;
  14901. return {
  14902. isWebGL2: isWebGL2,
  14903. getMaxAnisotropy: getMaxAnisotropy,
  14904. getMaxPrecision: getMaxPrecision,
  14905. precision: precision,
  14906. logarithmicDepthBuffer: logarithmicDepthBuffer,
  14907. maxTextures: maxTextures,
  14908. maxVertexTextures: maxVertexTextures,
  14909. maxTextureSize: maxTextureSize,
  14910. maxCubemapSize: maxCubemapSize,
  14911. maxAttributes: maxAttributes,
  14912. maxVertexUniforms: maxVertexUniforms,
  14913. maxVaryings: maxVaryings,
  14914. maxFragmentUniforms: maxFragmentUniforms,
  14915. vertexTextures: vertexTextures,
  14916. floatFragmentTextures: floatFragmentTextures,
  14917. floatVertexTextures: floatVertexTextures,
  14918. maxSamples: maxSamples,
  14919. multiview: multiview,
  14920. maxMultiviewViews: maxMultiviewViews
  14921. };
  14922. }
  14923. /**
  14924. * @author tschw
  14925. */
  14926. function WebGLClipping() {
  14927. var scope = this,
  14928. globalState = null,
  14929. numGlobalPlanes = 0,
  14930. localClippingEnabled = false,
  14931. renderingShadows = false,
  14932. plane = new Plane(),
  14933. viewNormalMatrix = new Matrix3(),
  14934. uniform = { value: null, needsUpdate: false };
  14935. this.uniform = uniform;
  14936. this.numPlanes = 0;
  14937. this.numIntersection = 0;
  14938. this.init = function ( planes, enableLocalClipping, camera ) {
  14939. var enabled =
  14940. planes.length !== 0 ||
  14941. enableLocalClipping ||
  14942. // enable state of previous frame - the clipping code has to
  14943. // run another frame in order to reset the state:
  14944. numGlobalPlanes !== 0 ||
  14945. localClippingEnabled;
  14946. localClippingEnabled = enableLocalClipping;
  14947. globalState = projectPlanes( planes, camera, 0 );
  14948. numGlobalPlanes = planes.length;
  14949. return enabled;
  14950. };
  14951. this.beginShadows = function () {
  14952. renderingShadows = true;
  14953. projectPlanes( null );
  14954. };
  14955. this.endShadows = function () {
  14956. renderingShadows = false;
  14957. resetGlobalState();
  14958. };
  14959. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  14960. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  14961. // there's no local clipping
  14962. if ( renderingShadows ) {
  14963. // there's no global clipping
  14964. projectPlanes( null );
  14965. } else {
  14966. resetGlobalState();
  14967. }
  14968. } else {
  14969. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  14970. lGlobal = nGlobal * 4,
  14971. dstArray = cache.clippingState || null;
  14972. uniform.value = dstArray; // ensure unique state
  14973. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  14974. for ( var i = 0; i !== lGlobal; ++ i ) {
  14975. dstArray[ i ] = globalState[ i ];
  14976. }
  14977. cache.clippingState = dstArray;
  14978. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  14979. this.numPlanes += nGlobal;
  14980. }
  14981. };
  14982. function resetGlobalState() {
  14983. if ( uniform.value !== globalState ) {
  14984. uniform.value = globalState;
  14985. uniform.needsUpdate = numGlobalPlanes > 0;
  14986. }
  14987. scope.numPlanes = numGlobalPlanes;
  14988. scope.numIntersection = 0;
  14989. }
  14990. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  14991. var nPlanes = planes !== null ? planes.length : 0,
  14992. dstArray = null;
  14993. if ( nPlanes !== 0 ) {
  14994. dstArray = uniform.value;
  14995. if ( skipTransform !== true || dstArray === null ) {
  14996. var flatSize = dstOffset + nPlanes * 4,
  14997. viewMatrix = camera.matrixWorldInverse;
  14998. viewNormalMatrix.getNormalMatrix( viewMatrix );
  14999. if ( dstArray === null || dstArray.length < flatSize ) {
  15000. dstArray = new Float32Array( flatSize );
  15001. }
  15002. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  15003. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  15004. plane.normal.toArray( dstArray, i4 );
  15005. dstArray[ i4 + 3 ] = plane.constant;
  15006. }
  15007. }
  15008. uniform.value = dstArray;
  15009. uniform.needsUpdate = true;
  15010. }
  15011. scope.numPlanes = nPlanes;
  15012. return dstArray;
  15013. }
  15014. }
  15015. /**
  15016. * @author mrdoob / http://mrdoob.com/
  15017. */
  15018. function WebGLExtensions( gl ) {
  15019. var extensions = {};
  15020. return {
  15021. get: function ( name ) {
  15022. if ( extensions[ name ] !== undefined ) {
  15023. return extensions[ name ];
  15024. }
  15025. var extension;
  15026. switch ( name ) {
  15027. case 'WEBGL_depth_texture':
  15028. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  15029. break;
  15030. case 'EXT_texture_filter_anisotropic':
  15031. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15032. break;
  15033. case 'WEBGL_compressed_texture_s3tc':
  15034. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15035. break;
  15036. case 'WEBGL_compressed_texture_pvrtc':
  15037. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15038. break;
  15039. default:
  15040. extension = gl.getExtension( name );
  15041. }
  15042. if ( extension === null ) {
  15043. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15044. }
  15045. extensions[ name ] = extension;
  15046. return extension;
  15047. }
  15048. };
  15049. }
  15050. /**
  15051. * @author mrdoob / http://mrdoob.com/
  15052. */
  15053. function WebGLGeometries( gl, attributes, info ) {
  15054. var geometries = new WeakMap();
  15055. var wireframeAttributes = new WeakMap();
  15056. function onGeometryDispose( event ) {
  15057. var geometry = event.target;
  15058. var buffergeometry = geometries.get( geometry );
  15059. if ( buffergeometry.index !== null ) {
  15060. attributes.remove( buffergeometry.index );
  15061. }
  15062. for ( var name in buffergeometry.attributes ) {
  15063. attributes.remove( buffergeometry.attributes[ name ] );
  15064. }
  15065. geometry.removeEventListener( 'dispose', onGeometryDispose );
  15066. geometries.delete( geometry );
  15067. var attribute = wireframeAttributes.get( buffergeometry );
  15068. if ( attribute ) {
  15069. attributes.remove( attribute );
  15070. wireframeAttributes.delete( buffergeometry );
  15071. }
  15072. //
  15073. info.memory.geometries --;
  15074. }
  15075. function get( object, geometry ) {
  15076. var buffergeometry = geometries.get( geometry );
  15077. if ( buffergeometry ) { return buffergeometry; }
  15078. geometry.addEventListener( 'dispose', onGeometryDispose );
  15079. if ( geometry.isBufferGeometry ) {
  15080. buffergeometry = geometry;
  15081. } else if ( geometry.isGeometry ) {
  15082. if ( geometry._bufferGeometry === undefined ) {
  15083. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  15084. }
  15085. buffergeometry = geometry._bufferGeometry;
  15086. }
  15087. geometries.set( geometry, buffergeometry );
  15088. info.memory.geometries ++;
  15089. return buffergeometry;
  15090. }
  15091. function update( geometry ) {
  15092. var index = geometry.index;
  15093. var geometryAttributes = geometry.attributes;
  15094. if ( index !== null ) {
  15095. attributes.update( index, 34963 );
  15096. }
  15097. for ( var name in geometryAttributes ) {
  15098. attributes.update( geometryAttributes[ name ], 34962 );
  15099. }
  15100. // morph targets
  15101. var morphAttributes = geometry.morphAttributes;
  15102. for ( var name in morphAttributes ) {
  15103. var array = morphAttributes[ name ];
  15104. for ( var i = 0, l = array.length; i < l; i ++ ) {
  15105. attributes.update( array[ i ], 34962 );
  15106. }
  15107. }
  15108. }
  15109. function updateWireframeAttribute( geometry ) {
  15110. var indices = [];
  15111. var geometryIndex = geometry.index;
  15112. var geometryPosition = geometry.attributes.position;
  15113. var version = 0;
  15114. if ( geometryIndex !== null ) {
  15115. var array = geometryIndex.array;
  15116. version = geometryIndex.version;
  15117. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  15118. var a = array[ i + 0 ];
  15119. var b = array[ i + 1 ];
  15120. var c = array[ i + 2 ];
  15121. indices.push( a, b, b, c, c, a );
  15122. }
  15123. } else {
  15124. var array = geometryPosition.array;
  15125. version = geometryPosition.version;
  15126. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  15127. var a = i + 0;
  15128. var b = i + 1;
  15129. var c = i + 2;
  15130. indices.push( a, b, b, c, c, a );
  15131. }
  15132. }
  15133. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  15134. attribute.version = version;
  15135. attributes.update( attribute, 34963 );
  15136. //
  15137. var previousAttribute = wireframeAttributes.get( geometry );
  15138. if ( previousAttribute ) { attributes.remove( previousAttribute ); }
  15139. //
  15140. wireframeAttributes.set( geometry, attribute );
  15141. }
  15142. function getWireframeAttribute( geometry ) {
  15143. var currentAttribute = wireframeAttributes.get( geometry );
  15144. if ( currentAttribute ) {
  15145. var geometryIndex = geometry.index;
  15146. if ( geometryIndex !== null ) {
  15147. // if the attribute is obsolete, create a new one
  15148. if ( currentAttribute.version < geometryIndex.version ) {
  15149. updateWireframeAttribute( geometry );
  15150. }
  15151. }
  15152. } else {
  15153. updateWireframeAttribute( geometry );
  15154. }
  15155. return wireframeAttributes.get( geometry );
  15156. }
  15157. return {
  15158. get: get,
  15159. update: update,
  15160. getWireframeAttribute: getWireframeAttribute
  15161. };
  15162. }
  15163. /**
  15164. * @author mrdoob / http://mrdoob.com/
  15165. */
  15166. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  15167. var mode;
  15168. function setMode( value ) {
  15169. mode = value;
  15170. }
  15171. var type, bytesPerElement;
  15172. function setIndex( value ) {
  15173. type = value.type;
  15174. bytesPerElement = value.bytesPerElement;
  15175. }
  15176. function render( start, count ) {
  15177. gl.drawElements( mode, count, type, start * bytesPerElement );
  15178. info.update( count, mode );
  15179. }
  15180. function renderInstances( geometry, start, count ) {
  15181. var extension, methodName;
  15182. if ( capabilities.isWebGL2 ) {
  15183. extension = gl;
  15184. methodName = 'drawElementsInstanced';
  15185. } else {
  15186. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15187. methodName = 'drawElementsInstancedANGLE';
  15188. if ( extension === null ) {
  15189. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15190. return;
  15191. }
  15192. }
  15193. extension[ methodName ]( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  15194. info.update( count, mode, geometry.maxInstancedCount );
  15195. }
  15196. //
  15197. this.setMode = setMode;
  15198. this.setIndex = setIndex;
  15199. this.render = render;
  15200. this.renderInstances = renderInstances;
  15201. }
  15202. /**
  15203. * @author Mugen87 / https://github.com/Mugen87
  15204. */
  15205. function WebGLInfo( gl ) {
  15206. var memory = {
  15207. geometries: 0,
  15208. textures: 0
  15209. };
  15210. var render = {
  15211. frame: 0,
  15212. calls: 0,
  15213. triangles: 0,
  15214. points: 0,
  15215. lines: 0
  15216. };
  15217. function update( count, mode, instanceCount ) {
  15218. instanceCount = instanceCount || 1;
  15219. render.calls ++;
  15220. switch ( mode ) {
  15221. case 4:
  15222. render.triangles += instanceCount * ( count / 3 );
  15223. break;
  15224. case 5:
  15225. case 6:
  15226. render.triangles += instanceCount * ( count - 2 );
  15227. break;
  15228. case 1:
  15229. render.lines += instanceCount * ( count / 2 );
  15230. break;
  15231. case 3:
  15232. render.lines += instanceCount * ( count - 1 );
  15233. break;
  15234. case 2:
  15235. render.lines += instanceCount * count;
  15236. break;
  15237. case 0:
  15238. render.points += instanceCount * count;
  15239. break;
  15240. default:
  15241. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  15242. break;
  15243. }
  15244. }
  15245. function reset() {
  15246. render.frame ++;
  15247. render.calls = 0;
  15248. render.triangles = 0;
  15249. render.points = 0;
  15250. render.lines = 0;
  15251. }
  15252. return {
  15253. memory: memory,
  15254. render: render,
  15255. programs: null,
  15256. autoReset: true,
  15257. reset: reset,
  15258. update: update
  15259. };
  15260. }
  15261. /**
  15262. * @author mrdoob / http://mrdoob.com/
  15263. */
  15264. function absNumericalSort( a, b ) {
  15265. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  15266. }
  15267. function WebGLMorphtargets( gl ) {
  15268. var influencesList = {};
  15269. var morphInfluences = new Float32Array( 8 );
  15270. function update( object, geometry, material, program ) {
  15271. var objectInfluences = object.morphTargetInfluences;
  15272. var length = objectInfluences.length;
  15273. var influences = influencesList[ geometry.id ];
  15274. if ( influences === undefined ) {
  15275. // initialise list
  15276. influences = [];
  15277. for ( var i = 0; i < length; i ++ ) {
  15278. influences[ i ] = [ i, 0 ];
  15279. }
  15280. influencesList[ geometry.id ] = influences;
  15281. }
  15282. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  15283. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  15284. // Remove current morphAttributes
  15285. for ( var i = 0; i < length; i ++ ) {
  15286. var influence = influences[ i ];
  15287. if ( influence[ 1 ] !== 0 ) {
  15288. if ( morphTargets ) { geometry.removeAttribute( 'morphTarget' + i ); }
  15289. if ( morphNormals ) { geometry.removeAttribute( 'morphNormal' + i ); }
  15290. }
  15291. }
  15292. // Collect influences
  15293. for ( var i = 0; i < length; i ++ ) {
  15294. var influence = influences[ i ];
  15295. influence[ 0 ] = i;
  15296. influence[ 1 ] = objectInfluences[ i ];
  15297. }
  15298. influences.sort( absNumericalSort );
  15299. // Add morphAttributes
  15300. for ( var i = 0; i < 8; i ++ ) {
  15301. var influence = influences[ i ];
  15302. if ( influence ) {
  15303. var index = influence[ 0 ];
  15304. var value = influence[ 1 ];
  15305. if ( value ) {
  15306. if ( morphTargets ) { geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] ); }
  15307. if ( morphNormals ) { geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] ); }
  15308. morphInfluences[ i ] = value;
  15309. continue;
  15310. }
  15311. }
  15312. morphInfluences[ i ] = 0;
  15313. }
  15314. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  15315. }
  15316. return {
  15317. update: update
  15318. };
  15319. }
  15320. /**
  15321. * @author mrdoob / http://mrdoob.com/
  15322. */
  15323. function WebGLObjects( geometries, info ) {
  15324. var updateList = {};
  15325. function update( object ) {
  15326. var frame = info.render.frame;
  15327. var geometry = object.geometry;
  15328. var buffergeometry = geometries.get( object, geometry );
  15329. // Update once per frame
  15330. if ( updateList[ buffergeometry.id ] !== frame ) {
  15331. if ( geometry.isGeometry ) {
  15332. buffergeometry.updateFromObject( object );
  15333. }
  15334. geometries.update( buffergeometry );
  15335. updateList[ buffergeometry.id ] = frame;
  15336. }
  15337. return buffergeometry;
  15338. }
  15339. function dispose() {
  15340. updateList = {};
  15341. }
  15342. return {
  15343. update: update,
  15344. dispose: dispose
  15345. };
  15346. }
  15347. /**
  15348. * @author mrdoob / http://mrdoob.com/
  15349. */
  15350. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  15351. images = images !== undefined ? images : [];
  15352. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  15353. format = format !== undefined ? format : RGBFormat;
  15354. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  15355. this.flipY = false;
  15356. }
  15357. CubeTexture.prototype = Object.create( Texture.prototype );
  15358. CubeTexture.prototype.constructor = CubeTexture;
  15359. CubeTexture.prototype.isCubeTexture = true;
  15360. Object.defineProperty( CubeTexture.prototype, 'images', {
  15361. get: function () {
  15362. return this.image;
  15363. },
  15364. set: function ( value ) {
  15365. this.image = value;
  15366. }
  15367. } );
  15368. /**
  15369. * @author Takahiro https://github.com/takahirox
  15370. */
  15371. function DataTexture2DArray( data, width, height, depth ) {
  15372. Texture.call( this, null );
  15373. this.image = { data: data, width: width, height: height, depth: depth };
  15374. this.magFilter = NearestFilter;
  15375. this.minFilter = NearestFilter;
  15376. this.wrapR = ClampToEdgeWrapping;
  15377. this.generateMipmaps = false;
  15378. this.flipY = false;
  15379. }
  15380. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  15381. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  15382. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  15383. /**
  15384. * @author Artur Trzesiok
  15385. */
  15386. function DataTexture3D( data, width, height, depth ) {
  15387. // We're going to add .setXXX() methods for setting properties later.
  15388. // Users can still set in DataTexture3D directly.
  15389. //
  15390. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  15391. // texture.anisotropy = 16;
  15392. //
  15393. // See #14839
  15394. Texture.call( this, null );
  15395. this.image = { data: data, width: width, height: height, depth: depth };
  15396. this.magFilter = NearestFilter;
  15397. this.minFilter = NearestFilter;
  15398. this.wrapR = ClampToEdgeWrapping;
  15399. this.generateMipmaps = false;
  15400. this.flipY = false;
  15401. }
  15402. DataTexture3D.prototype = Object.create( Texture.prototype );
  15403. DataTexture3D.prototype.constructor = DataTexture3D;
  15404. DataTexture3D.prototype.isDataTexture3D = true;
  15405. /**
  15406. * @author tschw
  15407. * @author Mugen87 / https://github.com/Mugen87
  15408. * @author mrdoob / http://mrdoob.com/
  15409. *
  15410. * Uniforms of a program.
  15411. * Those form a tree structure with a special top-level container for the root,
  15412. * which you get by calling 'new WebGLUniforms( gl, program )'.
  15413. *
  15414. *
  15415. * Properties of inner nodes including the top-level container:
  15416. *
  15417. * .seq - array of nested uniforms
  15418. * .map - nested uniforms by name
  15419. *
  15420. *
  15421. * Methods of all nodes except the top-level container:
  15422. *
  15423. * .setValue( gl, value, [textures] )
  15424. *
  15425. * uploads a uniform value(s)
  15426. * the 'textures' parameter is needed for sampler uniforms
  15427. *
  15428. *
  15429. * Static methods of the top-level container (textures factorizations):
  15430. *
  15431. * .upload( gl, seq, values, textures )
  15432. *
  15433. * sets uniforms in 'seq' to 'values[id].value'
  15434. *
  15435. * .seqWithValue( seq, values ) : filteredSeq
  15436. *
  15437. * filters 'seq' entries with corresponding entry in values
  15438. *
  15439. *
  15440. * Methods of the top-level container (textures factorizations):
  15441. *
  15442. * .setValue( gl, name, value, textures )
  15443. *
  15444. * sets uniform with name 'name' to 'value'
  15445. *
  15446. * .setOptional( gl, obj, prop )
  15447. *
  15448. * like .set for an optional property of the object
  15449. *
  15450. */
  15451. var emptyTexture = new Texture();
  15452. var emptyTexture2dArray = new DataTexture2DArray();
  15453. var emptyTexture3d = new DataTexture3D();
  15454. var emptyCubeTexture = new CubeTexture();
  15455. // --- Utilities ---
  15456. // Array Caches (provide typed arrays for temporary by size)
  15457. var arrayCacheF32 = [];
  15458. var arrayCacheI32 = [];
  15459. // Float32Array caches used for uploading Matrix uniforms
  15460. var mat4array = new Float32Array( 16 );
  15461. var mat3array = new Float32Array( 9 );
  15462. var mat2array = new Float32Array( 4 );
  15463. // Flattening for arrays of vectors and matrices
  15464. function flatten( array, nBlocks, blockSize ) {
  15465. var firstElem = array[ 0 ];
  15466. if ( firstElem <= 0 || firstElem > 0 ) { return array; }
  15467. // unoptimized: ! isNaN( firstElem )
  15468. // see http://jacksondunstan.com/articles/983
  15469. var n = nBlocks * blockSize,
  15470. r = arrayCacheF32[ n ];
  15471. if ( r === undefined ) {
  15472. r = new Float32Array( n );
  15473. arrayCacheF32[ n ] = r;
  15474. }
  15475. if ( nBlocks !== 0 ) {
  15476. firstElem.toArray( r, 0 );
  15477. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  15478. offset += blockSize;
  15479. array[ i ].toArray( r, offset );
  15480. }
  15481. }
  15482. return r;
  15483. }
  15484. function arraysEqual( a, b ) {
  15485. if ( a.length !== b.length ) { return false; }
  15486. for ( var i = 0, l = a.length; i < l; i ++ ) {
  15487. if ( a[ i ] !== b[ i ] ) { return false; }
  15488. }
  15489. return true;
  15490. }
  15491. function copyArray( a, b ) {
  15492. for ( var i = 0, l = b.length; i < l; i ++ ) {
  15493. a[ i ] = b[ i ];
  15494. }
  15495. }
  15496. // Texture unit allocation
  15497. function allocTexUnits( textures, n ) {
  15498. var r = arrayCacheI32[ n ];
  15499. if ( r === undefined ) {
  15500. r = new Int32Array( n );
  15501. arrayCacheI32[ n ] = r;
  15502. }
  15503. for ( var i = 0; i !== n; ++ i )
  15504. { r[ i ] = textures.allocateTextureUnit(); }
  15505. return r;
  15506. }
  15507. // --- Setters ---
  15508. // Note: Defining these methods externally, because they come in a bunch
  15509. // and this way their names minify.
  15510. // Single scalar
  15511. function setValueV1f( gl, v ) {
  15512. var cache = this.cache;
  15513. if ( cache[ 0 ] === v ) { return; }
  15514. gl.uniform1f( this.addr, v );
  15515. cache[ 0 ] = v;
  15516. }
  15517. // Single float vector (from flat array or THREE.VectorN)
  15518. function setValueV2f( gl, v ) {
  15519. var cache = this.cache;
  15520. if ( v.x !== undefined ) {
  15521. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  15522. gl.uniform2f( this.addr, v.x, v.y );
  15523. cache[ 0 ] = v.x;
  15524. cache[ 1 ] = v.y;
  15525. }
  15526. } else {
  15527. if ( arraysEqual( cache, v ) ) { return; }
  15528. gl.uniform2fv( this.addr, v );
  15529. copyArray( cache, v );
  15530. }
  15531. }
  15532. function setValueV3f( gl, v ) {
  15533. var cache = this.cache;
  15534. if ( v.x !== undefined ) {
  15535. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  15536. gl.uniform3f( this.addr, v.x, v.y, v.z );
  15537. cache[ 0 ] = v.x;
  15538. cache[ 1 ] = v.y;
  15539. cache[ 2 ] = v.z;
  15540. }
  15541. } else if ( v.r !== undefined ) {
  15542. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  15543. gl.uniform3f( this.addr, v.r, v.g, v.b );
  15544. cache[ 0 ] = v.r;
  15545. cache[ 1 ] = v.g;
  15546. cache[ 2 ] = v.b;
  15547. }
  15548. } else {
  15549. if ( arraysEqual( cache, v ) ) { return; }
  15550. gl.uniform3fv( this.addr, v );
  15551. copyArray( cache, v );
  15552. }
  15553. }
  15554. function setValueV4f( gl, v ) {
  15555. var cache = this.cache;
  15556. if ( v.x !== undefined ) {
  15557. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  15558. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  15559. cache[ 0 ] = v.x;
  15560. cache[ 1 ] = v.y;
  15561. cache[ 2 ] = v.z;
  15562. cache[ 3 ] = v.w;
  15563. }
  15564. } else {
  15565. if ( arraysEqual( cache, v ) ) { return; }
  15566. gl.uniform4fv( this.addr, v );
  15567. copyArray( cache, v );
  15568. }
  15569. }
  15570. // Single matrix (from flat array or MatrixN)
  15571. function setValueM2( gl, v ) {
  15572. var cache = this.cache;
  15573. var elements = v.elements;
  15574. if ( elements === undefined ) {
  15575. if ( arraysEqual( cache, v ) ) { return; }
  15576. gl.uniformMatrix2fv( this.addr, false, v );
  15577. copyArray( cache, v );
  15578. } else {
  15579. if ( arraysEqual( cache, elements ) ) { return; }
  15580. mat2array.set( elements );
  15581. gl.uniformMatrix2fv( this.addr, false, mat2array );
  15582. copyArray( cache, elements );
  15583. }
  15584. }
  15585. function setValueM3( gl, v ) {
  15586. var cache = this.cache;
  15587. var elements = v.elements;
  15588. if ( elements === undefined ) {
  15589. if ( arraysEqual( cache, v ) ) { return; }
  15590. gl.uniformMatrix3fv( this.addr, false, v );
  15591. copyArray( cache, v );
  15592. } else {
  15593. if ( arraysEqual( cache, elements ) ) { return; }
  15594. mat3array.set( elements );
  15595. gl.uniformMatrix3fv( this.addr, false, mat3array );
  15596. copyArray( cache, elements );
  15597. }
  15598. }
  15599. function setValueM4( gl, v ) {
  15600. var cache = this.cache;
  15601. var elements = v.elements;
  15602. if ( elements === undefined ) {
  15603. if ( arraysEqual( cache, v ) ) { return; }
  15604. gl.uniformMatrix4fv( this.addr, false, v );
  15605. copyArray( cache, v );
  15606. } else {
  15607. if ( arraysEqual( cache, elements ) ) { return; }
  15608. mat4array.set( elements );
  15609. gl.uniformMatrix4fv( this.addr, false, mat4array );
  15610. copyArray( cache, elements );
  15611. }
  15612. }
  15613. // Single texture (2D / Cube)
  15614. function setValueT1( gl, v, textures ) {
  15615. var cache = this.cache;
  15616. var unit = textures.allocateTextureUnit();
  15617. if ( cache[ 0 ] !== unit ) {
  15618. gl.uniform1i( this.addr, unit );
  15619. cache[ 0 ] = unit;
  15620. }
  15621. textures.safeSetTexture2D( v || emptyTexture, unit );
  15622. }
  15623. function setValueT2DArray1( gl, v, textures ) {
  15624. var cache = this.cache;
  15625. var unit = textures.allocateTextureUnit();
  15626. if ( cache[ 0 ] !== unit ) {
  15627. gl.uniform1i( this.addr, unit );
  15628. cache[ 0 ] = unit;
  15629. }
  15630. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  15631. }
  15632. function setValueT3D1( gl, v, textures ) {
  15633. var cache = this.cache;
  15634. var unit = textures.allocateTextureUnit();
  15635. if ( cache[ 0 ] !== unit ) {
  15636. gl.uniform1i( this.addr, unit );
  15637. cache[ 0 ] = unit;
  15638. }
  15639. textures.setTexture3D( v || emptyTexture3d, unit );
  15640. }
  15641. function setValueT6( gl, v, textures ) {
  15642. var cache = this.cache;
  15643. var unit = textures.allocateTextureUnit();
  15644. if ( cache[ 0 ] !== unit ) {
  15645. gl.uniform1i( this.addr, unit );
  15646. cache[ 0 ] = unit;
  15647. }
  15648. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  15649. }
  15650. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  15651. function setValueV1i( gl, v ) {
  15652. var cache = this.cache;
  15653. if ( cache[ 0 ] === v ) { return; }
  15654. gl.uniform1i( this.addr, v );
  15655. cache[ 0 ] = v;
  15656. }
  15657. function setValueV2i( gl, v ) {
  15658. var cache = this.cache;
  15659. if ( arraysEqual( cache, v ) ) { return; }
  15660. gl.uniform2iv( this.addr, v );
  15661. copyArray( cache, v );
  15662. }
  15663. function setValueV3i( gl, v ) {
  15664. var cache = this.cache;
  15665. if ( arraysEqual( cache, v ) ) { return; }
  15666. gl.uniform3iv( this.addr, v );
  15667. copyArray( cache, v );
  15668. }
  15669. function setValueV4i( gl, v ) {
  15670. var cache = this.cache;
  15671. if ( arraysEqual( cache, v ) ) { return; }
  15672. gl.uniform4iv( this.addr, v );
  15673. copyArray( cache, v );
  15674. }
  15675. // Helper to pick the right setter for the singular case
  15676. function getSingularSetter( type ) {
  15677. switch ( type ) {
  15678. case 0x1406: return setValueV1f; // FLOAT
  15679. case 0x8b50: return setValueV2f; // _VEC2
  15680. case 0x8b51: return setValueV3f; // _VEC3
  15681. case 0x8b52: return setValueV4f; // _VEC4
  15682. case 0x8b5a: return setValueM2; // _MAT2
  15683. case 0x8b5b: return setValueM3; // _MAT3
  15684. case 0x8b5c: return setValueM4; // _MAT4
  15685. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  15686. case 0x8b5f: return setValueT3D1; // SAMPLER_3D
  15687. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  15688. case 0x8DC1: return setValueT2DArray1; // SAMPLER_2D_ARRAY
  15689. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  15690. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  15691. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  15692. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  15693. }
  15694. }
  15695. // Array of scalars
  15696. function setValueV1fArray( gl, v ) {
  15697. gl.uniform1fv( this.addr, v );
  15698. }
  15699. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  15700. function setValueV1iArray( gl, v ) {
  15701. gl.uniform1iv( this.addr, v );
  15702. }
  15703. function setValueV2iArray( gl, v ) {
  15704. gl.uniform2iv( this.addr, v );
  15705. }
  15706. function setValueV3iArray( gl, v ) {
  15707. gl.uniform3iv( this.addr, v );
  15708. }
  15709. function setValueV4iArray( gl, v ) {
  15710. gl.uniform4iv( this.addr, v );
  15711. }
  15712. // Array of vectors (flat or from THREE classes)
  15713. function setValueV2fArray( gl, v ) {
  15714. var data = flatten( v, this.size, 2 );
  15715. gl.uniform2fv( this.addr, data );
  15716. }
  15717. function setValueV3fArray( gl, v ) {
  15718. var data = flatten( v, this.size, 3 );
  15719. gl.uniform3fv( this.addr, data );
  15720. }
  15721. function setValueV4fArray( gl, v ) {
  15722. var data = flatten( v, this.size, 4 );
  15723. gl.uniform4fv( this.addr, data );
  15724. }
  15725. // Array of matrices (flat or from THREE clases)
  15726. function setValueM2Array( gl, v ) {
  15727. var data = flatten( v, this.size, 4 );
  15728. gl.uniformMatrix2fv( this.addr, false, data );
  15729. }
  15730. function setValueM3Array( gl, v ) {
  15731. var data = flatten( v, this.size, 9 );
  15732. gl.uniformMatrix3fv( this.addr, false, data );
  15733. }
  15734. function setValueM4Array( gl, v ) {
  15735. var data = flatten( v, this.size, 16 );
  15736. gl.uniformMatrix4fv( this.addr, false, data );
  15737. }
  15738. // Array of textures (2D / Cube)
  15739. function setValueT1Array( gl, v, textures ) {
  15740. var n = v.length;
  15741. var units = allocTexUnits( textures, n );
  15742. gl.uniform1iv( this.addr, units );
  15743. for ( var i = 0; i !== n; ++ i ) {
  15744. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  15745. }
  15746. }
  15747. function setValueT6Array( gl, v, textures ) {
  15748. var n = v.length;
  15749. var units = allocTexUnits( textures, n );
  15750. gl.uniform1iv( this.addr, units );
  15751. for ( var i = 0; i !== n; ++ i ) {
  15752. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  15753. }
  15754. }
  15755. // Helper to pick the right setter for a pure (bottom-level) array
  15756. function getPureArraySetter( type ) {
  15757. switch ( type ) {
  15758. case 0x1406: return setValueV1fArray; // FLOAT
  15759. case 0x8b50: return setValueV2fArray; // _VEC2
  15760. case 0x8b51: return setValueV3fArray; // _VEC3
  15761. case 0x8b52: return setValueV4fArray; // _VEC4
  15762. case 0x8b5a: return setValueM2Array; // _MAT2
  15763. case 0x8b5b: return setValueM3Array; // _MAT3
  15764. case 0x8b5c: return setValueM4Array; // _MAT4
  15765. case 0x8b5e: return setValueT1Array; // SAMPLER_2D
  15766. case 0x8b60: return setValueT6Array; // SAMPLER_CUBE
  15767. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  15768. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  15769. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  15770. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  15771. }
  15772. }
  15773. // --- Uniform Classes ---
  15774. function SingleUniform( id, activeInfo, addr ) {
  15775. this.id = id;
  15776. this.addr = addr;
  15777. this.cache = [];
  15778. this.setValue = getSingularSetter( activeInfo.type );
  15779. // this.path = activeInfo.name; // DEBUG
  15780. }
  15781. function PureArrayUniform( id, activeInfo, addr ) {
  15782. this.id = id;
  15783. this.addr = addr;
  15784. this.cache = [];
  15785. this.size = activeInfo.size;
  15786. this.setValue = getPureArraySetter( activeInfo.type );
  15787. // this.path = activeInfo.name; // DEBUG
  15788. }
  15789. PureArrayUniform.prototype.updateCache = function ( data ) {
  15790. var cache = this.cache;
  15791. if ( data instanceof Float32Array && cache.length !== data.length ) {
  15792. this.cache = new Float32Array( data.length );
  15793. }
  15794. copyArray( cache, data );
  15795. };
  15796. function StructuredUniform( id ) {
  15797. this.id = id;
  15798. this.seq = [];
  15799. this.map = {};
  15800. }
  15801. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  15802. var seq = this.seq;
  15803. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  15804. var u = seq[ i ];
  15805. u.setValue( gl, value[ u.id ], textures );
  15806. }
  15807. };
  15808. // --- Top-level ---
  15809. // Parser - builds up the property tree from the path strings
  15810. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  15811. // extracts
  15812. // - the identifier (member name or array index)
  15813. // - followed by an optional right bracket (found when array index)
  15814. // - followed by an optional left bracket or dot (type of subscript)
  15815. //
  15816. // Note: These portions can be read in a non-overlapping fashion and
  15817. // allow straightforward parsing of the hierarchy that WebGL encodes
  15818. // in the uniform names.
  15819. function addUniform( container, uniformObject ) {
  15820. container.seq.push( uniformObject );
  15821. container.map[ uniformObject.id ] = uniformObject;
  15822. }
  15823. function parseUniform( activeInfo, addr, container ) {
  15824. var path = activeInfo.name,
  15825. pathLength = path.length;
  15826. // reset RegExp object, because of the early exit of a previous run
  15827. RePathPart.lastIndex = 0;
  15828. while ( true ) {
  15829. var match = RePathPart.exec( path ),
  15830. matchEnd = RePathPart.lastIndex,
  15831. id = match[ 1 ],
  15832. idIsIndex = match[ 2 ] === ']',
  15833. subscript = match[ 3 ];
  15834. if ( idIsIndex ) { id = id | 0; } // convert to integer
  15835. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  15836. // bare name or "pure" bottom-level array "[0]" suffix
  15837. addUniform( container, subscript === undefined ?
  15838. new SingleUniform( id, activeInfo, addr ) :
  15839. new PureArrayUniform( id, activeInfo, addr ) );
  15840. break;
  15841. } else {
  15842. // step into inner node / create it in case it doesn't exist
  15843. var map = container.map, next = map[ id ];
  15844. if ( next === undefined ) {
  15845. next = new StructuredUniform( id );
  15846. addUniform( container, next );
  15847. }
  15848. container = next;
  15849. }
  15850. }
  15851. }
  15852. // Root Container
  15853. function WebGLUniforms( gl, program ) {
  15854. this.seq = [];
  15855. this.map = {};
  15856. var n = gl.getProgramParameter( program, 35718 );
  15857. for ( var i = 0; i < n; ++ i ) {
  15858. var info = gl.getActiveUniform( program, i ),
  15859. addr = gl.getUniformLocation( program, info.name );
  15860. parseUniform( info, addr, this );
  15861. }
  15862. }
  15863. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  15864. var u = this.map[ name ];
  15865. if ( u !== undefined ) { u.setValue( gl, value, textures ); }
  15866. };
  15867. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  15868. var v = object[ name ];
  15869. if ( v !== undefined ) { this.setValue( gl, name, v ); }
  15870. };
  15871. // Static interface
  15872. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  15873. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  15874. var u = seq[ i ],
  15875. v = values[ u.id ];
  15876. if ( v.needsUpdate !== false ) {
  15877. // note: always updating when .needsUpdate is undefined
  15878. u.setValue( gl, v.value, textures );
  15879. }
  15880. }
  15881. };
  15882. WebGLUniforms.seqWithValue = function ( seq, values ) {
  15883. var r = [];
  15884. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  15885. var u = seq[ i ];
  15886. if ( u.id in values ) { r.push( u ); }
  15887. }
  15888. return r;
  15889. };
  15890. /**
  15891. * @author mrdoob / http://mrdoob.com/
  15892. */
  15893. function WebGLShader( gl, type, string ) {
  15894. var shader = gl.createShader( type );
  15895. gl.shaderSource( shader, string );
  15896. gl.compileShader( shader );
  15897. return shader;
  15898. }
  15899. /**
  15900. * @author mrdoob / http://mrdoob.com/
  15901. */
  15902. var programIdCount = 0;
  15903. function addLineNumbers( string ) {
  15904. var lines = string.split( '\n' );
  15905. for ( var i = 0; i < lines.length; i ++ ) {
  15906. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15907. }
  15908. return lines.join( '\n' );
  15909. }
  15910. function getEncodingComponents( encoding ) {
  15911. switch ( encoding ) {
  15912. case LinearEncoding:
  15913. return [ 'Linear', '( value )' ];
  15914. case sRGBEncoding:
  15915. return [ 'sRGB', '( value )' ];
  15916. case RGBEEncoding:
  15917. return [ 'RGBE', '( value )' ];
  15918. case RGBM7Encoding:
  15919. return [ 'RGBM', '( value, 7.0 )' ];
  15920. case RGBM16Encoding:
  15921. return [ 'RGBM', '( value, 16.0 )' ];
  15922. case RGBDEncoding:
  15923. return [ 'RGBD', '( value, 256.0 )' ];
  15924. case GammaEncoding:
  15925. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  15926. case LogLuvEncoding:
  15927. return [ 'LogLuv', '( value )' ];
  15928. default:
  15929. throw new Error( 'unsupported encoding: ' + encoding );
  15930. }
  15931. }
  15932. function getShaderErrors( gl, shader, type ) {
  15933. var status = gl.getShaderParameter( shader, 35713 );
  15934. var log = gl.getShaderInfoLog( shader ).trim();
  15935. if ( status && log === '' ) { return ''; }
  15936. // --enable-privileged-webgl-extension
  15937. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15938. var source = gl.getShaderSource( shader );
  15939. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  15940. }
  15941. function getTexelDecodingFunction( functionName, encoding ) {
  15942. var components = getEncodingComponents( encoding );
  15943. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  15944. }
  15945. function getTexelEncodingFunction( functionName, encoding ) {
  15946. var components = getEncodingComponents( encoding );
  15947. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  15948. }
  15949. function getToneMappingFunction( functionName, toneMapping ) {
  15950. var toneMappingName;
  15951. switch ( toneMapping ) {
  15952. case LinearToneMapping:
  15953. toneMappingName = 'Linear';
  15954. break;
  15955. case ReinhardToneMapping:
  15956. toneMappingName = 'Reinhard';
  15957. break;
  15958. case Uncharted2ToneMapping:
  15959. toneMappingName = 'Uncharted2';
  15960. break;
  15961. case CineonToneMapping:
  15962. toneMappingName = 'OptimizedCineon';
  15963. break;
  15964. case ACESFilmicToneMapping:
  15965. toneMappingName = 'ACESFilmic';
  15966. break;
  15967. default:
  15968. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  15969. }
  15970. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  15971. }
  15972. function generateExtensions( extensions, parameters, rendererExtensions ) {
  15973. extensions = extensions || {};
  15974. var chunks = [
  15975. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  15976. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  15977. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  15978. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  15979. ];
  15980. return chunks.filter( filterEmptyLine ).join( '\n' );
  15981. }
  15982. function generateDefines( defines ) {
  15983. var chunks = [];
  15984. for ( var name in defines ) {
  15985. var value = defines[ name ];
  15986. if ( value === false ) { continue; }
  15987. chunks.push( '#define ' + name + ' ' + value );
  15988. }
  15989. return chunks.join( '\n' );
  15990. }
  15991. function fetchAttributeLocations( gl, program ) {
  15992. var attributes = {};
  15993. var n = gl.getProgramParameter( program, 35721 );
  15994. for ( var i = 0; i < n; i ++ ) {
  15995. var info = gl.getActiveAttrib( program, i );
  15996. var name = info.name;
  15997. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  15998. attributes[ name ] = gl.getAttribLocation( program, name );
  15999. }
  16000. return attributes;
  16001. }
  16002. function filterEmptyLine( string ) {
  16003. return string !== '';
  16004. }
  16005. function replaceLightNums( string, parameters ) {
  16006. return string
  16007. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  16008. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  16009. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  16010. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  16011. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  16012. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  16013. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  16014. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  16015. }
  16016. function replaceClippingPlaneNums( string, parameters ) {
  16017. return string
  16018. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  16019. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  16020. }
  16021. function parseIncludes( string ) {
  16022. var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16023. function replace( match, include ) {
  16024. var replace = ShaderChunk[ include ];
  16025. if ( replace === undefined ) {
  16026. throw new Error( 'Can not resolve #include <' + include + '>' );
  16027. }
  16028. return parseIncludes( replace );
  16029. }
  16030. return string.replace( pattern, replace );
  16031. }
  16032. function unrollLoops( string ) {
  16033. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16034. function replace( match, start, end, snippet ) {
  16035. var unroll = '';
  16036. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  16037. unroll += snippet
  16038. .replace( /\[ i \]/g, '[ ' + i + ' ]' )
  16039. .replace( /UNROLLED_LOOP_INDEX/g, i );
  16040. }
  16041. return unroll;
  16042. }
  16043. return string.replace( pattern, replace );
  16044. }
  16045. function generatePrecision( parameters ) {
  16046. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  16047. if ( parameters.precision === "highp" ) {
  16048. precisionstring += "\n#define HIGH_PRECISION;";
  16049. } else if ( parameters.precision === "mediump" ) {
  16050. precisionstring += "\n#define MEDIUM_PRECISION;";
  16051. } else if ( parameters.precision === "lowp" ) {
  16052. precisionstring += "\n#define LOW_PRECISION;";
  16053. }
  16054. return precisionstring;
  16055. }
  16056. function generateShadowMapTypeDefine( parameters ) {
  16057. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16058. if ( parameters.shadowMapType === PCFShadowMap ) {
  16059. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16060. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  16061. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16062. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  16063. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16064. }
  16065. return shadowMapTypeDefine;
  16066. }
  16067. function generateEnvMapTypeDefine( parameters, material ) {
  16068. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16069. if ( parameters.envMap ) {
  16070. switch ( material.envMap.mapping ) {
  16071. case CubeReflectionMapping:
  16072. case CubeRefractionMapping:
  16073. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16074. break;
  16075. case CubeUVReflectionMapping:
  16076. case CubeUVRefractionMapping:
  16077. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16078. break;
  16079. case EquirectangularReflectionMapping:
  16080. case EquirectangularRefractionMapping:
  16081. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  16082. break;
  16083. case SphericalReflectionMapping:
  16084. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  16085. break;
  16086. }
  16087. }
  16088. return envMapTypeDefine;
  16089. }
  16090. function generateEnvMapModeDefine( parameters, material ) {
  16091. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16092. if ( parameters.envMap ) {
  16093. switch ( material.envMap.mapping ) {
  16094. case CubeRefractionMapping:
  16095. case EquirectangularRefractionMapping:
  16096. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16097. break;
  16098. }
  16099. }
  16100. return envMapModeDefine;
  16101. }
  16102. function generateEnvMapBlendingDefine( parameters, material ) {
  16103. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16104. if ( parameters.envMap ) {
  16105. switch ( material.combine ) {
  16106. case MultiplyOperation:
  16107. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16108. break;
  16109. case MixOperation:
  16110. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16111. break;
  16112. case AddOperation:
  16113. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16114. break;
  16115. }
  16116. }
  16117. return envMapBlendingDefine;
  16118. }
  16119. function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
  16120. var gl = renderer.getContext();
  16121. var defines = material.defines;
  16122. var vertexShader = shader.vertexShader;
  16123. var fragmentShader = shader.fragmentShader;
  16124. var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  16125. var envMapTypeDefine = generateEnvMapTypeDefine( parameters, material );
  16126. var envMapModeDefine = generateEnvMapModeDefine( parameters, material );
  16127. var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters, material );
  16128. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  16129. var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
  16130. var customDefines = generateDefines( defines );
  16131. var program = gl.createProgram();
  16132. var prefixVertex, prefixFragment;
  16133. var renderTarget = renderer.getRenderTarget();
  16134. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  16135. if ( material.isRawShaderMaterial ) {
  16136. prefixVertex = [
  16137. customDefines
  16138. ].filter( filterEmptyLine ).join( '\n' );
  16139. if ( prefixVertex.length > 0 ) {
  16140. prefixVertex += '\n';
  16141. }
  16142. prefixFragment = [
  16143. customExtensions,
  16144. customDefines
  16145. ].filter( filterEmptyLine ).join( '\n' );
  16146. if ( prefixFragment.length > 0 ) {
  16147. prefixFragment += '\n';
  16148. }
  16149. } else {
  16150. prefixVertex = [
  16151. generatePrecision( parameters ),
  16152. '#define SHADER_NAME ' + shader.name,
  16153. customDefines,
  16154. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  16155. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16156. '#define MAX_BONES ' + parameters.maxBones,
  16157. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16158. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16159. parameters.map ? '#define USE_MAP' : '',
  16160. parameters.envMap ? '#define USE_ENVMAP' : '',
  16161. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16162. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16163. parameters.aoMap ? '#define USE_AOMAP' : '',
  16164. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16165. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16166. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16167. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16168. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16169. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16170. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  16171. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16172. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16173. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16174. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16175. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16176. parameters.vertexColors ? '#define USE_COLOR' : '',
  16177. parameters.vertexUvs ? '#define USE_UV' : '',
  16178. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16179. parameters.skinning ? '#define USE_SKINNING' : '',
  16180. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  16181. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  16182. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  16183. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16184. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16185. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16186. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16187. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  16188. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16189. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16190. 'uniform mat4 modelMatrix;',
  16191. 'uniform vec3 cameraPosition;',
  16192. numMultiviewViews > 0 ? [
  16193. 'uniform mat4 modelViewMatrices[' + numMultiviewViews + '];',
  16194. 'uniform mat3 normalMatrices[' + numMultiviewViews + '];',
  16195. 'uniform mat4 viewMatrices[' + numMultiviewViews + '];',
  16196. 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];',
  16197. '#define modelViewMatrix modelViewMatrices[VIEW_ID]',
  16198. '#define normalMatrix normalMatrices[VIEW_ID]',
  16199. '#define viewMatrix viewMatrices[VIEW_ID]',
  16200. '#define projectionMatrix projectionMatrices[VIEW_ID]'
  16201. ].join( '\n' ) : [
  16202. 'uniform mat4 modelViewMatrix;',
  16203. 'uniform mat4 projectionMatrix;',
  16204. 'uniform mat4 viewMatrix;',
  16205. 'uniform mat3 normalMatrix;' ].join( '\n' ),
  16206. 'attribute vec3 position;',
  16207. 'attribute vec3 normal;',
  16208. 'attribute vec2 uv;',
  16209. '#ifdef USE_TANGENT',
  16210. ' attribute vec4 tangent;',
  16211. '#endif',
  16212. '#ifdef USE_COLOR',
  16213. ' attribute vec3 color;',
  16214. '#endif',
  16215. '#ifdef USE_MORPHTARGETS',
  16216. ' attribute vec3 morphTarget0;',
  16217. ' attribute vec3 morphTarget1;',
  16218. ' attribute vec3 morphTarget2;',
  16219. ' attribute vec3 morphTarget3;',
  16220. ' #ifdef USE_MORPHNORMALS',
  16221. ' attribute vec3 morphNormal0;',
  16222. ' attribute vec3 morphNormal1;',
  16223. ' attribute vec3 morphNormal2;',
  16224. ' attribute vec3 morphNormal3;',
  16225. ' #else',
  16226. ' attribute vec3 morphTarget4;',
  16227. ' attribute vec3 morphTarget5;',
  16228. ' attribute vec3 morphTarget6;',
  16229. ' attribute vec3 morphTarget7;',
  16230. ' #endif',
  16231. '#endif',
  16232. '#ifdef USE_SKINNING',
  16233. ' attribute vec4 skinIndex;',
  16234. ' attribute vec4 skinWeight;',
  16235. '#endif',
  16236. '\n'
  16237. ].filter( filterEmptyLine ).join( '\n' );
  16238. prefixFragment = [
  16239. customExtensions,
  16240. generatePrecision( parameters ),
  16241. '#define SHADER_NAME ' + shader.name,
  16242. customDefines,
  16243. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  16244. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16245. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16246. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16247. parameters.map ? '#define USE_MAP' : '',
  16248. parameters.matcap ? '#define USE_MATCAP' : '',
  16249. parameters.envMap ? '#define USE_ENVMAP' : '',
  16250. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  16251. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16252. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  16253. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16254. parameters.aoMap ? '#define USE_AOMAP' : '',
  16255. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16256. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16257. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16258. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16259. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16260. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16261. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16262. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16263. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16264. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16265. parameters.sheen ? '#define USE_SHEEN' : '',
  16266. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16267. parameters.vertexColors ? '#define USE_COLOR' : '',
  16268. parameters.vertexUvs ? '#define USE_UV' : '',
  16269. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  16270. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16271. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16272. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16273. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16274. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16275. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  16276. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  16277. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16278. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16279. ( ( material.extensions ? material.extensions.shaderTextureLOD : false ) || parameters.envMap ) && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
  16280. 'uniform vec3 cameraPosition;',
  16281. numMultiviewViews > 0 ? [
  16282. 'uniform mat4 viewMatrices[' + numMultiviewViews + '];',
  16283. '#define viewMatrix viewMatrices[VIEW_ID]'
  16284. ].join( '\n' ) : 'uniform mat4 viewMatrix;',
  16285. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  16286. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  16287. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  16288. parameters.dithering ? '#define DITHERING' : '',
  16289. ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ?
  16290. ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  16291. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  16292. parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  16293. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  16294. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  16295. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  16296. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  16297. '\n'
  16298. ].filter( filterEmptyLine ).join( '\n' );
  16299. }
  16300. vertexShader = parseIncludes( vertexShader );
  16301. vertexShader = replaceLightNums( vertexShader, parameters );
  16302. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  16303. fragmentShader = parseIncludes( fragmentShader );
  16304. fragmentShader = replaceLightNums( fragmentShader, parameters );
  16305. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  16306. vertexShader = unrollLoops( vertexShader );
  16307. fragmentShader = unrollLoops( fragmentShader );
  16308. if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
  16309. var isGLSL3ShaderMaterial = false;
  16310. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  16311. if ( material.isShaderMaterial &&
  16312. vertexShader.match( versionRegex ) !== null &&
  16313. fragmentShader.match( versionRegex ) !== null ) {
  16314. isGLSL3ShaderMaterial = true;
  16315. vertexShader = vertexShader.replace( versionRegex, '' );
  16316. fragmentShader = fragmentShader.replace( versionRegex, '' );
  16317. }
  16318. // GLSL 3.0 conversion
  16319. prefixVertex = [
  16320. '#version 300 es\n',
  16321. numMultiviewViews > 0 ? [
  16322. '#extension GL_OVR_multiview2 : require',
  16323. 'layout(num_views = ' + numMultiviewViews + ') in;',
  16324. '#define VIEW_ID gl_ViewID_OVR'
  16325. ].join( '\n' ) : '',
  16326. '#define attribute in',
  16327. '#define varying out',
  16328. '#define texture2D texture'
  16329. ].join( '\n' ) + '\n' + prefixVertex;
  16330. prefixFragment = [
  16331. '#version 300 es\n',
  16332. numMultiviewViews > 0 ? [
  16333. '#extension GL_OVR_multiview2 : require',
  16334. '#define VIEW_ID gl_ViewID_OVR'
  16335. ].join( '\n' ) : '',
  16336. '#define varying in',
  16337. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  16338. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  16339. '#define gl_FragDepthEXT gl_FragDepth',
  16340. '#define texture2D texture',
  16341. '#define textureCube texture',
  16342. '#define texture2DProj textureProj',
  16343. '#define texture2DLodEXT textureLod',
  16344. '#define texture2DProjLodEXT textureProjLod',
  16345. '#define textureCubeLodEXT textureLod',
  16346. '#define texture2DGradEXT textureGrad',
  16347. '#define texture2DProjGradEXT textureProjGrad',
  16348. '#define textureCubeGradEXT textureGrad'
  16349. ].join( '\n' ) + '\n' + prefixFragment;
  16350. }
  16351. var vertexGlsl = prefixVertex + vertexShader;
  16352. var fragmentGlsl = prefixFragment + fragmentShader;
  16353. // console.log( '*VERTEX*', vertexGlsl );
  16354. // console.log( '*FRAGMENT*', fragmentGlsl );
  16355. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  16356. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  16357. gl.attachShader( program, glVertexShader );
  16358. gl.attachShader( program, glFragmentShader );
  16359. // Force a particular attribute to index 0.
  16360. if ( material.index0AttributeName !== undefined ) {
  16361. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  16362. } else if ( parameters.morphTargets === true ) {
  16363. // programs with morphTargets displace position out of attribute 0
  16364. gl.bindAttribLocation( program, 0, 'position' );
  16365. }
  16366. gl.linkProgram( program );
  16367. // check for link errors
  16368. if ( renderer.debug.checkShaderErrors ) {
  16369. var programLog = gl.getProgramInfoLog( program ).trim();
  16370. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  16371. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  16372. var runnable = true;
  16373. var haveDiagnostics = true;
  16374. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  16375. runnable = false;
  16376. var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  16377. var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  16378. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  16379. } else if ( programLog !== '' ) {
  16380. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  16381. } else if ( vertexLog === '' || fragmentLog === '' ) {
  16382. haveDiagnostics = false;
  16383. }
  16384. if ( haveDiagnostics ) {
  16385. this.diagnostics = {
  16386. runnable: runnable,
  16387. material: material,
  16388. programLog: programLog,
  16389. vertexShader: {
  16390. log: vertexLog,
  16391. prefix: prefixVertex
  16392. },
  16393. fragmentShader: {
  16394. log: fragmentLog,
  16395. prefix: prefixFragment
  16396. }
  16397. };
  16398. }
  16399. }
  16400. // clean up
  16401. gl.deleteShader( glVertexShader );
  16402. gl.deleteShader( glFragmentShader );
  16403. // set up caching for uniform locations
  16404. var cachedUniforms;
  16405. this.getUniforms = function () {
  16406. if ( cachedUniforms === undefined ) {
  16407. cachedUniforms = new WebGLUniforms( gl, program );
  16408. }
  16409. return cachedUniforms;
  16410. };
  16411. // set up caching for attribute locations
  16412. var cachedAttributes;
  16413. this.getAttributes = function () {
  16414. if ( cachedAttributes === undefined ) {
  16415. cachedAttributes = fetchAttributeLocations( gl, program );
  16416. }
  16417. return cachedAttributes;
  16418. };
  16419. // free resource
  16420. this.destroy = function () {
  16421. gl.deleteProgram( program );
  16422. this.program = undefined;
  16423. };
  16424. //
  16425. this.name = shader.name;
  16426. this.id = programIdCount ++;
  16427. this.code = code;
  16428. this.usedTimes = 1;
  16429. this.program = program;
  16430. this.vertexShader = glVertexShader;
  16431. this.fragmentShader = glFragmentShader;
  16432. this.numMultiviewViews = numMultiviewViews;
  16433. return this;
  16434. }
  16435. /**
  16436. * @author mrdoob / http://mrdoob.com/
  16437. */
  16438. function WebGLPrograms( renderer, extensions, capabilities ) {
  16439. var programs = [];
  16440. var shaderIDs = {
  16441. MeshDepthMaterial: 'depth',
  16442. MeshDistanceMaterial: 'distanceRGBA',
  16443. MeshNormalMaterial: 'normal',
  16444. MeshBasicMaterial: 'basic',
  16445. MeshLambertMaterial: 'lambert',
  16446. MeshPhongMaterial: 'phong',
  16447. MeshToonMaterial: 'phong',
  16448. MeshStandardMaterial: 'physical',
  16449. MeshPhysicalMaterial: 'physical',
  16450. MeshMatcapMaterial: 'matcap',
  16451. LineBasicMaterial: 'basic',
  16452. LineDashedMaterial: 'dashed',
  16453. PointsMaterial: 'points',
  16454. ShadowMaterial: 'shadow',
  16455. SpriteMaterial: 'sprite'
  16456. };
  16457. var parameterNames = [
  16458. "precision", "supportsVertexTextures", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding",
  16459. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap",
  16460. "roughnessMap", "metalnessMap", "gradientMap",
  16461. "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2",
  16462. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  16463. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  16464. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  16465. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  16466. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  16467. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
  16468. "sheen"
  16469. ];
  16470. function allocateBones( object ) {
  16471. var skeleton = object.skeleton;
  16472. var bones = skeleton.bones;
  16473. if ( capabilities.floatVertexTextures ) {
  16474. return 1024;
  16475. } else {
  16476. // default for when object is not specified
  16477. // ( for example when prebuilding shader to be used with multiple objects )
  16478. //
  16479. // - leave some extra space for other uniforms
  16480. // - limit here is ANGLE's 254 max uniform vectors
  16481. // (up to 54 should be safe)
  16482. var nVertexUniforms = capabilities.maxVertexUniforms;
  16483. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  16484. var maxBones = Math.min( nVertexMatrices, bones.length );
  16485. if ( maxBones < bones.length ) {
  16486. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  16487. return 0;
  16488. }
  16489. return maxBones;
  16490. }
  16491. }
  16492. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  16493. var encoding;
  16494. if ( ! map ) {
  16495. encoding = LinearEncoding;
  16496. } else if ( map.isTexture ) {
  16497. encoding = map.encoding;
  16498. } else if ( map.isWebGLRenderTarget ) {
  16499. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  16500. encoding = map.texture.encoding;
  16501. }
  16502. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  16503. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  16504. encoding = GammaEncoding;
  16505. }
  16506. return encoding;
  16507. }
  16508. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  16509. var shaderID = shaderIDs[ material.type ];
  16510. // heuristics to create shader parameters according to lights in the scene
  16511. // (not to blow over maxLights budget)
  16512. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  16513. var precision = capabilities.precision;
  16514. if ( material.precision !== null ) {
  16515. precision = capabilities.getMaxPrecision( material.precision );
  16516. if ( precision !== material.precision ) {
  16517. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  16518. }
  16519. }
  16520. var currentRenderTarget = renderer.getRenderTarget();
  16521. var parameters = {
  16522. shaderID: shaderID,
  16523. precision: precision,
  16524. supportsVertexTextures: capabilities.vertexTextures,
  16525. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  16526. map: !! material.map,
  16527. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  16528. matcap: !! material.matcap,
  16529. matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
  16530. envMap: !! material.envMap,
  16531. envMapMode: material.envMap && material.envMap.mapping,
  16532. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  16533. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  16534. lightMap: !! material.lightMap,
  16535. aoMap: !! material.aoMap,
  16536. emissiveMap: !! material.emissiveMap,
  16537. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  16538. bumpMap: !! material.bumpMap,
  16539. normalMap: !! material.normalMap,
  16540. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  16541. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  16542. clearcoatNormalMap: !! material.clearcoatNormalMap,
  16543. displacementMap: !! material.displacementMap,
  16544. roughnessMap: !! material.roughnessMap,
  16545. metalnessMap: !! material.metalnessMap,
  16546. specularMap: !! material.specularMap,
  16547. alphaMap: !! material.alphaMap,
  16548. gradientMap: !! material.gradientMap,
  16549. sheen: !! material.sheen,
  16550. combine: material.combine,
  16551. vertexTangents: ( material.normalMap && material.vertexTangents ),
  16552. vertexColors: material.vertexColors,
  16553. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap,
  16554. fog: !! fog,
  16555. useFog: material.fog,
  16556. fogExp2: ( fog && fog.isFogExp2 ),
  16557. flatShading: material.flatShading,
  16558. sizeAttenuation: material.sizeAttenuation,
  16559. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  16560. skinning: material.skinning && maxBones > 0,
  16561. maxBones: maxBones,
  16562. useVertexTexture: capabilities.floatVertexTextures,
  16563. morphTargets: material.morphTargets,
  16564. morphNormals: material.morphNormals,
  16565. maxMorphTargets: renderer.maxMorphTargets,
  16566. maxMorphNormals: renderer.maxMorphNormals,
  16567. numDirLights: lights.directional.length,
  16568. numPointLights: lights.point.length,
  16569. numSpotLights: lights.spot.length,
  16570. numRectAreaLights: lights.rectArea.length,
  16571. numHemiLights: lights.hemi.length,
  16572. numDirLightShadows: lights.directionalShadowMap.length,
  16573. numPointLightShadows: lights.pointShadowMap.length,
  16574. numSpotLightShadows: lights.spotShadowMap.length,
  16575. numClippingPlanes: nClipPlanes,
  16576. numClipIntersection: nClipIntersection,
  16577. dithering: material.dithering,
  16578. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  16579. shadowMapType: renderer.shadowMap.type,
  16580. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  16581. physicallyCorrectLights: renderer.physicallyCorrectLights,
  16582. premultipliedAlpha: material.premultipliedAlpha,
  16583. alphaTest: material.alphaTest,
  16584. doubleSided: material.side === DoubleSide,
  16585. flipSided: material.side === BackSide,
  16586. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  16587. };
  16588. return parameters;
  16589. };
  16590. this.getProgramCode = function ( material, parameters ) {
  16591. var array = [];
  16592. if ( parameters.shaderID ) {
  16593. array.push( parameters.shaderID );
  16594. } else {
  16595. array.push( material.fragmentShader );
  16596. array.push( material.vertexShader );
  16597. }
  16598. if ( material.defines !== undefined ) {
  16599. for ( var name in material.defines ) {
  16600. array.push( name );
  16601. array.push( material.defines[ name ] );
  16602. }
  16603. }
  16604. for ( var i = 0; i < parameterNames.length; i ++ ) {
  16605. array.push( parameters[ parameterNames[ i ] ] );
  16606. }
  16607. array.push( material.onBeforeCompile.toString() );
  16608. array.push( renderer.gammaOutput );
  16609. array.push( renderer.gammaFactor );
  16610. return array.join();
  16611. };
  16612. this.acquireProgram = function ( material, shader, parameters, code ) {
  16613. var program;
  16614. // Check if code has been already compiled
  16615. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  16616. var programInfo = programs[ p ];
  16617. if ( programInfo.code === code ) {
  16618. program = programInfo;
  16619. ++ program.usedTimes;
  16620. break;
  16621. }
  16622. }
  16623. if ( program === undefined ) {
  16624. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
  16625. programs.push( program );
  16626. }
  16627. return program;
  16628. };
  16629. this.releaseProgram = function ( program ) {
  16630. if ( -- program.usedTimes === 0 ) {
  16631. // Remove from unordered set
  16632. var i = programs.indexOf( program );
  16633. programs[ i ] = programs[ programs.length - 1 ];
  16634. programs.pop();
  16635. // Free WebGL resources
  16636. program.destroy();
  16637. }
  16638. };
  16639. // Exposed for resource monitoring & error feedback via renderer.info:
  16640. this.programs = programs;
  16641. }
  16642. /**
  16643. * @author fordacious / fordacious.github.io
  16644. */
  16645. function WebGLProperties() {
  16646. var properties = new WeakMap();
  16647. function get( object ) {
  16648. var map = properties.get( object );
  16649. if ( map === undefined ) {
  16650. map = {};
  16651. properties.set( object, map );
  16652. }
  16653. return map;
  16654. }
  16655. function remove( object ) {
  16656. properties.delete( object );
  16657. }
  16658. function update( object, key, value ) {
  16659. properties.get( object )[ key ] = value;
  16660. }
  16661. function dispose() {
  16662. properties = new WeakMap();
  16663. }
  16664. return {
  16665. get: get,
  16666. remove: remove,
  16667. update: update,
  16668. dispose: dispose
  16669. };
  16670. }
  16671. /**
  16672. * @author mrdoob / http://mrdoob.com/
  16673. */
  16674. function painterSortStable( a, b ) {
  16675. if ( a.groupOrder !== b.groupOrder ) {
  16676. return a.groupOrder - b.groupOrder;
  16677. } else if ( a.renderOrder !== b.renderOrder ) {
  16678. return a.renderOrder - b.renderOrder;
  16679. } else if ( a.program !== b.program ) {
  16680. return a.program.id - b.program.id;
  16681. } else if ( a.material.id !== b.material.id ) {
  16682. return a.material.id - b.material.id;
  16683. } else if ( a.z !== b.z ) {
  16684. return a.z - b.z;
  16685. } else {
  16686. return a.id - b.id;
  16687. }
  16688. }
  16689. function reversePainterSortStable( a, b ) {
  16690. if ( a.groupOrder !== b.groupOrder ) {
  16691. return a.groupOrder - b.groupOrder;
  16692. } else if ( a.renderOrder !== b.renderOrder ) {
  16693. return a.renderOrder - b.renderOrder;
  16694. } else if ( a.z !== b.z ) {
  16695. return b.z - a.z;
  16696. } else {
  16697. return a.id - b.id;
  16698. }
  16699. }
  16700. function WebGLRenderList() {
  16701. var renderItems = [];
  16702. var renderItemsIndex = 0;
  16703. var opaque = [];
  16704. var transparent = [];
  16705. var defaultProgram = { id: - 1 };
  16706. function init() {
  16707. renderItemsIndex = 0;
  16708. opaque.length = 0;
  16709. transparent.length = 0;
  16710. }
  16711. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  16712. var renderItem = renderItems[ renderItemsIndex ];
  16713. if ( renderItem === undefined ) {
  16714. renderItem = {
  16715. id: object.id,
  16716. object: object,
  16717. geometry: geometry,
  16718. material: material,
  16719. program: material.program || defaultProgram,
  16720. groupOrder: groupOrder,
  16721. renderOrder: object.renderOrder,
  16722. z: z,
  16723. group: group
  16724. };
  16725. renderItems[ renderItemsIndex ] = renderItem;
  16726. } else {
  16727. renderItem.id = object.id;
  16728. renderItem.object = object;
  16729. renderItem.geometry = geometry;
  16730. renderItem.material = material;
  16731. renderItem.program = material.program || defaultProgram;
  16732. renderItem.groupOrder = groupOrder;
  16733. renderItem.renderOrder = object.renderOrder;
  16734. renderItem.z = z;
  16735. renderItem.group = group;
  16736. }
  16737. renderItemsIndex ++;
  16738. return renderItem;
  16739. }
  16740. function push( object, geometry, material, groupOrder, z, group ) {
  16741. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  16742. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  16743. }
  16744. function unshift( object, geometry, material, groupOrder, z, group ) {
  16745. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  16746. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  16747. }
  16748. function sort() {
  16749. if ( opaque.length > 1 ) { opaque.sort( painterSortStable ); }
  16750. if ( transparent.length > 1 ) { transparent.sort( reversePainterSortStable ); }
  16751. }
  16752. return {
  16753. opaque: opaque,
  16754. transparent: transparent,
  16755. init: init,
  16756. push: push,
  16757. unshift: unshift,
  16758. sort: sort
  16759. };
  16760. }
  16761. function WebGLRenderLists() {
  16762. var lists = new WeakMap();
  16763. function onSceneDispose( event ) {
  16764. var scene = event.target;
  16765. scene.removeEventListener( 'dispose', onSceneDispose );
  16766. lists.delete( scene );
  16767. }
  16768. function get( scene, camera ) {
  16769. var cameras = lists.get( scene );
  16770. var list;
  16771. if ( cameras === undefined ) {
  16772. list = new WebGLRenderList();
  16773. lists.set( scene, new WeakMap() );
  16774. lists.get( scene ).set( camera, list );
  16775. scene.addEventListener( 'dispose', onSceneDispose );
  16776. } else {
  16777. list = cameras.get( camera );
  16778. if ( list === undefined ) {
  16779. list = new WebGLRenderList();
  16780. cameras.set( camera, list );
  16781. }
  16782. }
  16783. return list;
  16784. }
  16785. function dispose() {
  16786. lists = new WeakMap();
  16787. }
  16788. return {
  16789. get: get,
  16790. dispose: dispose
  16791. };
  16792. }
  16793. /**
  16794. * @author mrdoob / http://mrdoob.com/
  16795. */
  16796. function UniformsCache() {
  16797. var lights = {};
  16798. return {
  16799. get: function ( light ) {
  16800. if ( lights[ light.id ] !== undefined ) {
  16801. return lights[ light.id ];
  16802. }
  16803. var uniforms;
  16804. switch ( light.type ) {
  16805. case 'DirectionalLight':
  16806. uniforms = {
  16807. direction: new Vector3(),
  16808. color: new Color(),
  16809. shadow: false,
  16810. shadowBias: 0,
  16811. shadowRadius: 1,
  16812. shadowMapSize: new Vector2()
  16813. };
  16814. break;
  16815. case 'SpotLight':
  16816. uniforms = {
  16817. position: new Vector3(),
  16818. direction: new Vector3(),
  16819. color: new Color(),
  16820. distance: 0,
  16821. coneCos: 0,
  16822. penumbraCos: 0,
  16823. decay: 0,
  16824. shadow: false,
  16825. shadowBias: 0,
  16826. shadowRadius: 1,
  16827. shadowMapSize: new Vector2()
  16828. };
  16829. break;
  16830. case 'PointLight':
  16831. uniforms = {
  16832. position: new Vector3(),
  16833. color: new Color(),
  16834. distance: 0,
  16835. decay: 0,
  16836. shadow: false,
  16837. shadowBias: 0,
  16838. shadowRadius: 1,
  16839. shadowMapSize: new Vector2(),
  16840. shadowCameraNear: 1,
  16841. shadowCameraFar: 1000
  16842. };
  16843. break;
  16844. case 'HemisphereLight':
  16845. uniforms = {
  16846. direction: new Vector3(),
  16847. skyColor: new Color(),
  16848. groundColor: new Color()
  16849. };
  16850. break;
  16851. case 'RectAreaLight':
  16852. uniforms = {
  16853. color: new Color(),
  16854. position: new Vector3(),
  16855. halfWidth: new Vector3(),
  16856. halfHeight: new Vector3()
  16857. // TODO (abelnation): set RectAreaLight shadow uniforms
  16858. };
  16859. break;
  16860. }
  16861. lights[ light.id ] = uniforms;
  16862. return uniforms;
  16863. }
  16864. };
  16865. }
  16866. var nextVersion = 0;
  16867. function shadowCastingLightsFirst( lightA, lightB ) {
  16868. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  16869. }
  16870. function WebGLLights() {
  16871. var cache = new UniformsCache();
  16872. var state = {
  16873. version: 0,
  16874. hash: {
  16875. directionalLength: - 1,
  16876. pointLength: - 1,
  16877. spotLength: - 1,
  16878. rectAreaLength: - 1,
  16879. hemiLength: - 1,
  16880. numDirectionalShadows: - 1,
  16881. numPointShadows: - 1,
  16882. numSpotShadows: - 1,
  16883. },
  16884. ambient: [ 0, 0, 0 ],
  16885. probe: [],
  16886. directional: [],
  16887. directionalShadowMap: [],
  16888. directionalShadowMatrix: [],
  16889. spot: [],
  16890. spotShadowMap: [],
  16891. spotShadowMatrix: [],
  16892. rectArea: [],
  16893. point: [],
  16894. pointShadowMap: [],
  16895. pointShadowMatrix: [],
  16896. hemi: [],
  16897. numDirectionalShadows: - 1,
  16898. numPointShadows: - 1,
  16899. numSpotShadows: - 1
  16900. };
  16901. for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); }
  16902. var vector3 = new Vector3();
  16903. var matrix4 = new Matrix4();
  16904. var matrix42 = new Matrix4();
  16905. function setup( lights, shadows, camera ) {
  16906. var r = 0, g = 0, b = 0;
  16907. for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); }
  16908. var directionalLength = 0;
  16909. var pointLength = 0;
  16910. var spotLength = 0;
  16911. var rectAreaLength = 0;
  16912. var hemiLength = 0;
  16913. var numDirectionalShadows = 0;
  16914. var numPointShadows = 0;
  16915. var numSpotShadows = 0;
  16916. var viewMatrix = camera.matrixWorldInverse;
  16917. lights.sort( shadowCastingLightsFirst );
  16918. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  16919. var light = lights[ i ];
  16920. var color = light.color;
  16921. var intensity = light.intensity;
  16922. var distance = light.distance;
  16923. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  16924. if ( light.isAmbientLight ) {
  16925. r += color.r * intensity;
  16926. g += color.g * intensity;
  16927. b += color.b * intensity;
  16928. } else if ( light.isLightProbe ) {
  16929. for ( var j = 0; j < 9; j ++ ) {
  16930. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  16931. }
  16932. } else if ( light.isDirectionalLight ) {
  16933. var uniforms = cache.get( light );
  16934. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16935. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16936. vector3.setFromMatrixPosition( light.target.matrixWorld );
  16937. uniforms.direction.sub( vector3 );
  16938. uniforms.direction.transformDirection( viewMatrix );
  16939. uniforms.shadow = light.castShadow;
  16940. if ( light.castShadow ) {
  16941. var shadow = light.shadow;
  16942. uniforms.shadowBias = shadow.bias;
  16943. uniforms.shadowRadius = shadow.radius;
  16944. uniforms.shadowMapSize = shadow.mapSize;
  16945. state.directionalShadowMap[ directionalLength ] = shadowMap;
  16946. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  16947. numDirectionalShadows ++;
  16948. }
  16949. state.directional[ directionalLength ] = uniforms;
  16950. directionalLength ++;
  16951. } else if ( light.isSpotLight ) {
  16952. var uniforms = cache.get( light );
  16953. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16954. uniforms.position.applyMatrix4( viewMatrix );
  16955. uniforms.color.copy( color ).multiplyScalar( intensity );
  16956. uniforms.distance = distance;
  16957. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16958. vector3.setFromMatrixPosition( light.target.matrixWorld );
  16959. uniforms.direction.sub( vector3 );
  16960. uniforms.direction.transformDirection( viewMatrix );
  16961. uniforms.coneCos = Math.cos( light.angle );
  16962. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  16963. uniforms.decay = light.decay;
  16964. uniforms.shadow = light.castShadow;
  16965. if ( light.castShadow ) {
  16966. var shadow = light.shadow;
  16967. uniforms.shadowBias = shadow.bias;
  16968. uniforms.shadowRadius = shadow.radius;
  16969. uniforms.shadowMapSize = shadow.mapSize;
  16970. state.spotShadowMap[ spotLength ] = shadowMap;
  16971. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  16972. numSpotShadows ++;
  16973. }
  16974. state.spot[ spotLength ] = uniforms;
  16975. spotLength ++;
  16976. } else if ( light.isRectAreaLight ) {
  16977. var uniforms = cache.get( light );
  16978. // (a) intensity is the total visible light emitted
  16979. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  16980. // (b) intensity is the brightness of the light
  16981. uniforms.color.copy( color ).multiplyScalar( intensity );
  16982. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16983. uniforms.position.applyMatrix4( viewMatrix );
  16984. // extract local rotation of light to derive width/height half vectors
  16985. matrix42.identity();
  16986. matrix4.copy( light.matrixWorld );
  16987. matrix4.premultiply( viewMatrix );
  16988. matrix42.extractRotation( matrix4 );
  16989. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  16990. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  16991. uniforms.halfWidth.applyMatrix4( matrix42 );
  16992. uniforms.halfHeight.applyMatrix4( matrix42 );
  16993. // TODO (abelnation): RectAreaLight distance?
  16994. // uniforms.distance = distance;
  16995. state.rectArea[ rectAreaLength ] = uniforms;
  16996. rectAreaLength ++;
  16997. } else if ( light.isPointLight ) {
  16998. var uniforms = cache.get( light );
  16999. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17000. uniforms.position.applyMatrix4( viewMatrix );
  17001. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17002. uniforms.distance = light.distance;
  17003. uniforms.decay = light.decay;
  17004. uniforms.shadow = light.castShadow;
  17005. if ( light.castShadow ) {
  17006. var shadow = light.shadow;
  17007. uniforms.shadowBias = shadow.bias;
  17008. uniforms.shadowRadius = shadow.radius;
  17009. uniforms.shadowMapSize = shadow.mapSize;
  17010. uniforms.shadowCameraNear = shadow.camera.near;
  17011. uniforms.shadowCameraFar = shadow.camera.far;
  17012. state.pointShadowMap[ pointLength ] = shadowMap;
  17013. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  17014. numPointShadows ++;
  17015. }
  17016. state.point[ pointLength ] = uniforms;
  17017. pointLength ++;
  17018. } else if ( light.isHemisphereLight ) {
  17019. var uniforms = cache.get( light );
  17020. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17021. uniforms.direction.transformDirection( viewMatrix );
  17022. uniforms.direction.normalize();
  17023. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  17024. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17025. state.hemi[ hemiLength ] = uniforms;
  17026. hemiLength ++;
  17027. }
  17028. }
  17029. state.ambient[ 0 ] = r;
  17030. state.ambient[ 1 ] = g;
  17031. state.ambient[ 2 ] = b;
  17032. var hash = state.hash;
  17033. if ( hash.directionalLength !== directionalLength ||
  17034. hash.pointLength !== pointLength ||
  17035. hash.spotLength !== spotLength ||
  17036. hash.rectAreaLength !== rectAreaLength ||
  17037. hash.hemiLength !== hemiLength ||
  17038. hash.numDirectionalShadows !== numDirectionalShadows ||
  17039. hash.numPointShadows !== numPointShadows ||
  17040. hash.numSpotShadows !== numSpotShadows ) {
  17041. state.directional.length = directionalLength;
  17042. state.spot.length = spotLength;
  17043. state.rectArea.length = rectAreaLength;
  17044. state.point.length = pointLength;
  17045. state.hemi.length = hemiLength;
  17046. state.directionalShadowMap.length = numDirectionalShadows;
  17047. state.pointShadowMap.length = numPointShadows;
  17048. state.spotShadowMap.length = numSpotShadows;
  17049. state.directionalShadowMatrix.length = numDirectionalShadows;
  17050. state.pointShadowMatrix.length = numPointShadows;
  17051. state.spotShadowMatrix.length = numSpotShadows;
  17052. hash.directionalLength = directionalLength;
  17053. hash.pointLength = pointLength;
  17054. hash.spotLength = spotLength;
  17055. hash.rectAreaLength = rectAreaLength;
  17056. hash.hemiLength = hemiLength;
  17057. hash.numDirectionalShadows = numDirectionalShadows;
  17058. hash.numPointShadows = numPointShadows;
  17059. hash.numSpotShadows = numSpotShadows;
  17060. state.version = nextVersion ++;
  17061. }
  17062. }
  17063. return {
  17064. setup: setup,
  17065. state: state
  17066. };
  17067. }
  17068. /**
  17069. * @author Mugen87 / https://github.com/Mugen87
  17070. */
  17071. function WebGLRenderState() {
  17072. var lights = new WebGLLights();
  17073. var lightsArray = [];
  17074. var shadowsArray = [];
  17075. function init() {
  17076. lightsArray.length = 0;
  17077. shadowsArray.length = 0;
  17078. }
  17079. function pushLight( light ) {
  17080. lightsArray.push( light );
  17081. }
  17082. function pushShadow( shadowLight ) {
  17083. shadowsArray.push( shadowLight );
  17084. }
  17085. function setupLights( camera ) {
  17086. lights.setup( lightsArray, shadowsArray, camera );
  17087. }
  17088. var state = {
  17089. lightsArray: lightsArray,
  17090. shadowsArray: shadowsArray,
  17091. lights: lights
  17092. };
  17093. return {
  17094. init: init,
  17095. state: state,
  17096. setupLights: setupLights,
  17097. pushLight: pushLight,
  17098. pushShadow: pushShadow
  17099. };
  17100. }
  17101. function WebGLRenderStates() {
  17102. var renderStates = new WeakMap();
  17103. function onSceneDispose( event ) {
  17104. var scene = event.target;
  17105. scene.removeEventListener( 'dispose', onSceneDispose );
  17106. renderStates.delete( scene );
  17107. }
  17108. function get( scene, camera ) {
  17109. var renderState;
  17110. if ( renderStates.has( scene ) === false ) {
  17111. renderState = new WebGLRenderState();
  17112. renderStates.set( scene, new WeakMap() );
  17113. renderStates.get( scene ).set( camera, renderState );
  17114. scene.addEventListener( 'dispose', onSceneDispose );
  17115. } else {
  17116. if ( renderStates.get( scene ).has( camera ) === false ) {
  17117. renderState = new WebGLRenderState();
  17118. renderStates.get( scene ).set( camera, renderState );
  17119. } else {
  17120. renderState = renderStates.get( scene ).get( camera );
  17121. }
  17122. }
  17123. return renderState;
  17124. }
  17125. function dispose() {
  17126. renderStates = new WeakMap();
  17127. }
  17128. return {
  17129. get: get,
  17130. dispose: dispose
  17131. };
  17132. }
  17133. /**
  17134. * @author mrdoob / http://mrdoob.com/
  17135. * @author alteredq / http://alteredqualia.com/
  17136. * @author bhouston / https://clara.io
  17137. * @author WestLangley / http://github.com/WestLangley
  17138. *
  17139. * parameters = {
  17140. *
  17141. * opacity: <float>,
  17142. *
  17143. * map: new THREE.Texture( <Image> ),
  17144. *
  17145. * alphaMap: new THREE.Texture( <Image> ),
  17146. *
  17147. * displacementMap: new THREE.Texture( <Image> ),
  17148. * displacementScale: <float>,
  17149. * displacementBias: <float>,
  17150. *
  17151. * wireframe: <boolean>,
  17152. * wireframeLinewidth: <float>
  17153. * }
  17154. */
  17155. function MeshDepthMaterial( parameters ) {
  17156. Material.call( this );
  17157. this.type = 'MeshDepthMaterial';
  17158. this.depthPacking = BasicDepthPacking;
  17159. this.skinning = false;
  17160. this.morphTargets = false;
  17161. this.map = null;
  17162. this.alphaMap = null;
  17163. this.displacementMap = null;
  17164. this.displacementScale = 1;
  17165. this.displacementBias = 0;
  17166. this.wireframe = false;
  17167. this.wireframeLinewidth = 1;
  17168. this.fog = false;
  17169. this.lights = false;
  17170. this.setValues( parameters );
  17171. }
  17172. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  17173. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17174. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17175. MeshDepthMaterial.prototype.copy = function ( source ) {
  17176. Material.prototype.copy.call( this, source );
  17177. this.depthPacking = source.depthPacking;
  17178. this.skinning = source.skinning;
  17179. this.morphTargets = source.morphTargets;
  17180. this.map = source.map;
  17181. this.alphaMap = source.alphaMap;
  17182. this.displacementMap = source.displacementMap;
  17183. this.displacementScale = source.displacementScale;
  17184. this.displacementBias = source.displacementBias;
  17185. this.wireframe = source.wireframe;
  17186. this.wireframeLinewidth = source.wireframeLinewidth;
  17187. return this;
  17188. };
  17189. /**
  17190. * @author WestLangley / http://github.com/WestLangley
  17191. *
  17192. * parameters = {
  17193. *
  17194. * referencePosition: <float>,
  17195. * nearDistance: <float>,
  17196. * farDistance: <float>,
  17197. *
  17198. * skinning: <bool>,
  17199. * morphTargets: <bool>,
  17200. *
  17201. * map: new THREE.Texture( <Image> ),
  17202. *
  17203. * alphaMap: new THREE.Texture( <Image> ),
  17204. *
  17205. * displacementMap: new THREE.Texture( <Image> ),
  17206. * displacementScale: <float>,
  17207. * displacementBias: <float>
  17208. *
  17209. * }
  17210. */
  17211. function MeshDistanceMaterial( parameters ) {
  17212. Material.call( this );
  17213. this.type = 'MeshDistanceMaterial';
  17214. this.referencePosition = new Vector3();
  17215. this.nearDistance = 1;
  17216. this.farDistance = 1000;
  17217. this.skinning = false;
  17218. this.morphTargets = false;
  17219. this.map = null;
  17220. this.alphaMap = null;
  17221. this.displacementMap = null;
  17222. this.displacementScale = 1;
  17223. this.displacementBias = 0;
  17224. this.fog = false;
  17225. this.lights = false;
  17226. this.setValues( parameters );
  17227. }
  17228. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  17229. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  17230. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  17231. MeshDistanceMaterial.prototype.copy = function ( source ) {
  17232. Material.prototype.copy.call( this, source );
  17233. this.referencePosition.copy( source.referencePosition );
  17234. this.nearDistance = source.nearDistance;
  17235. this.farDistance = source.farDistance;
  17236. this.skinning = source.skinning;
  17237. this.morphTargets = source.morphTargets;
  17238. this.map = source.map;
  17239. this.alphaMap = source.alphaMap;
  17240. this.displacementMap = source.displacementMap;
  17241. this.displacementScale = source.displacementScale;
  17242. this.displacementBias = source.displacementBias;
  17243. return this;
  17244. };
  17245. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n \n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = decodeHalfRGBA ( 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 #else\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 #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}";
  17246. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  17247. /**
  17248. * @author alteredq / http://alteredqualia.com/
  17249. * @author mrdoob / http://mrdoob.com/
  17250. */
  17251. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  17252. var _frustum = new Frustum(),
  17253. _shadowMapSize = new Vector2(),
  17254. _viewportSize = new Vector2(),
  17255. _viewport = new Vector4(),
  17256. _MorphingFlag = 1,
  17257. _SkinningFlag = 2,
  17258. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17259. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17260. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  17261. _materialCache = {};
  17262. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  17263. var shadowMaterialVertical = new ShaderMaterial( {
  17264. defines: {
  17265. SAMPLE_RATE: 2.0 / 8.0,
  17266. HALF_SAMPLE_RATE: 1.0 / 8.0
  17267. },
  17268. uniforms: {
  17269. shadow_pass: { value: null },
  17270. resolution: { value: new Vector2() },
  17271. radius: { value: 4.0 }
  17272. },
  17273. vertexShader: vsm_vert,
  17274. fragmentShader: vsm_frag
  17275. } );
  17276. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  17277. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  17278. var fullScreenTri = new BufferGeometry();
  17279. fullScreenTri.addAttribute(
  17280. "position",
  17281. new BufferAttribute(
  17282. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  17283. 3
  17284. )
  17285. );
  17286. var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  17287. // init
  17288. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17289. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17290. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17291. var depthMaterial = new MeshDepthMaterial( {
  17292. depthPacking: RGBADepthPacking,
  17293. morphTargets: useMorphing,
  17294. skinning: useSkinning
  17295. } );
  17296. _depthMaterials[ i ] = depthMaterial;
  17297. var distanceMaterial = new MeshDistanceMaterial( {
  17298. morphTargets: useMorphing,
  17299. skinning: useSkinning
  17300. } );
  17301. _distanceMaterials[ i ] = distanceMaterial;
  17302. }
  17303. var scope = this;
  17304. this.enabled = false;
  17305. this.autoUpdate = true;
  17306. this.needsUpdate = false;
  17307. this.type = PCFShadowMap;
  17308. this.render = function ( lights, scene, camera ) {
  17309. if ( scope.enabled === false ) { return; }
  17310. if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; }
  17311. if ( lights.length === 0 ) { return; }
  17312. var currentRenderTarget = _renderer.getRenderTarget();
  17313. var activeCubeFace = _renderer.getActiveCubeFace();
  17314. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  17315. var _state = _renderer.state;
  17316. // Set GL state for depth map.
  17317. _state.setBlending( NoBlending );
  17318. _state.buffers.color.setClear( 1, 1, 1, 1 );
  17319. _state.buffers.depth.setTest( true );
  17320. _state.setScissorTest( false );
  17321. // render depth map
  17322. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  17323. var light = lights[ i ];
  17324. var shadow = light.shadow;
  17325. if ( shadow === undefined ) {
  17326. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  17327. continue;
  17328. }
  17329. _shadowMapSize.copy( shadow.mapSize );
  17330. var shadowFrameExtents = shadow.getFrameExtents();
  17331. _shadowMapSize.multiply( shadowFrameExtents );
  17332. _viewportSize.copy( shadow.mapSize );
  17333. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  17334. console.warn( 'THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing' );
  17335. if ( _shadowMapSize.x > maxTextureSize ) {
  17336. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  17337. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  17338. shadow.mapSize.x = _viewportSize.x;
  17339. }
  17340. if ( _shadowMapSize.y > maxTextureSize ) {
  17341. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  17342. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  17343. shadow.mapSize.y = _viewportSize.y;
  17344. }
  17345. }
  17346. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17347. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  17348. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17349. shadow.map.texture.name = light.name + ".shadowMap";
  17350. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17351. shadow.camera.updateProjectionMatrix();
  17352. }
  17353. if ( shadow.map === null ) {
  17354. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  17355. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17356. shadow.map.texture.name = light.name + ".shadowMap";
  17357. shadow.camera.updateProjectionMatrix();
  17358. }
  17359. _renderer.setRenderTarget( shadow.map );
  17360. _renderer.clear();
  17361. var viewportCount = shadow.getViewportCount();
  17362. for ( var vp = 0; vp < viewportCount; vp ++ ) {
  17363. var viewport = shadow.getViewport( vp );
  17364. _viewport.set(
  17365. _viewportSize.x * viewport.x,
  17366. _viewportSize.y * viewport.y,
  17367. _viewportSize.x * viewport.z,
  17368. _viewportSize.y * viewport.w
  17369. );
  17370. _state.viewport( _viewport );
  17371. shadow.updateMatrices( light, camera, vp );
  17372. _frustum = shadow.getFrustum();
  17373. renderObject( scene, camera, shadow.camera, light, this.type );
  17374. }
  17375. // do blur pass for VSM
  17376. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17377. VSMPass( shadow, camera );
  17378. }
  17379. }
  17380. scope.needsUpdate = false;
  17381. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  17382. };
  17383. function VSMPass( shadow, camera ) {
  17384. var geometry = _objects.update( fullScreenMesh );
  17385. // vertical pass
  17386. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  17387. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  17388. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  17389. _renderer.setRenderTarget( shadow.mapPass );
  17390. _renderer.clear();
  17391. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  17392. // horizonal pass
  17393. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  17394. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  17395. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  17396. _renderer.setRenderTarget( shadow.map );
  17397. _renderer.clear();
  17398. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );
  17399. }
  17400. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  17401. var geometry = object.geometry;
  17402. var result = null;
  17403. var materialVariants = _depthMaterials;
  17404. var customMaterial = object.customDepthMaterial;
  17405. if ( light.isPointLight ) {
  17406. materialVariants = _distanceMaterials;
  17407. customMaterial = object.customDistanceMaterial;
  17408. }
  17409. if ( ! customMaterial ) {
  17410. var useMorphing = false;
  17411. if ( material.morphTargets ) {
  17412. if ( geometry && geometry.isBufferGeometry ) {
  17413. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  17414. } else if ( geometry && geometry.isGeometry ) {
  17415. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  17416. }
  17417. }
  17418. if ( object.isSkinnedMesh && material.skinning === false ) {
  17419. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  17420. }
  17421. var useSkinning = object.isSkinnedMesh && material.skinning;
  17422. var variantIndex = 0;
  17423. if ( useMorphing ) { variantIndex |= _MorphingFlag; }
  17424. if ( useSkinning ) { variantIndex |= _SkinningFlag; }
  17425. result = materialVariants[ variantIndex ];
  17426. } else {
  17427. result = customMaterial;
  17428. }
  17429. if ( _renderer.localClippingEnabled &&
  17430. material.clipShadows === true &&
  17431. material.clippingPlanes.length !== 0 ) {
  17432. // in this case we need a unique material instance reflecting the
  17433. // appropriate state
  17434. var keyA = result.uuid, keyB = material.uuid;
  17435. var materialsForVariant = _materialCache[ keyA ];
  17436. if ( materialsForVariant === undefined ) {
  17437. materialsForVariant = {};
  17438. _materialCache[ keyA ] = materialsForVariant;
  17439. }
  17440. var cachedMaterial = materialsForVariant[ keyB ];
  17441. if ( cachedMaterial === undefined ) {
  17442. cachedMaterial = result.clone();
  17443. materialsForVariant[ keyB ] = cachedMaterial;
  17444. }
  17445. result = cachedMaterial;
  17446. }
  17447. result.visible = material.visible;
  17448. result.wireframe = material.wireframe;
  17449. if ( type === VSMShadowMap ) {
  17450. result.side = ( material.shadowSide != null ) ? material.shadowSide : material.side;
  17451. } else {
  17452. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  17453. }
  17454. result.clipShadows = material.clipShadows;
  17455. result.clippingPlanes = material.clippingPlanes;
  17456. result.clipIntersection = material.clipIntersection;
  17457. result.wireframeLinewidth = material.wireframeLinewidth;
  17458. result.linewidth = material.linewidth;
  17459. if ( light.isPointLight && result.isMeshDistanceMaterial ) {
  17460. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  17461. result.nearDistance = shadowCameraNear;
  17462. result.farDistance = shadowCameraFar;
  17463. }
  17464. return result;
  17465. }
  17466. function renderObject( object, camera, shadowCamera, light, type ) {
  17467. if ( object.visible === false ) { return; }
  17468. var visible = object.layers.test( camera.layers );
  17469. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  17470. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  17471. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17472. var geometry = _objects.update( object );
  17473. var material = object.material;
  17474. if ( Array.isArray( material ) ) {
  17475. var groups = geometry.groups;
  17476. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17477. var group = groups[ k ];
  17478. var groupMaterial = material[ group.materialIndex ];
  17479. if ( groupMaterial && groupMaterial.visible ) {
  17480. var depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  17481. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17482. }
  17483. }
  17484. } else if ( material.visible ) {
  17485. var depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  17486. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17487. }
  17488. }
  17489. }
  17490. var children = object.children;
  17491. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17492. renderObject( children[ i ], camera, shadowCamera, light, type );
  17493. }
  17494. }
  17495. }
  17496. /**
  17497. * @author mrdoob / http://mrdoob.com/
  17498. */
  17499. function WebGLState( gl, extensions, utils, capabilities ) {
  17500. function ColorBuffer() {
  17501. var locked = false;
  17502. var color = new Vector4();
  17503. var currentColorMask = null;
  17504. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  17505. return {
  17506. setMask: function ( colorMask ) {
  17507. if ( currentColorMask !== colorMask && ! locked ) {
  17508. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  17509. currentColorMask = colorMask;
  17510. }
  17511. },
  17512. setLocked: function ( lock ) {
  17513. locked = lock;
  17514. },
  17515. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  17516. if ( premultipliedAlpha === true ) {
  17517. r *= a; g *= a; b *= a;
  17518. }
  17519. color.set( r, g, b, a );
  17520. if ( currentColorClear.equals( color ) === false ) {
  17521. gl.clearColor( r, g, b, a );
  17522. currentColorClear.copy( color );
  17523. }
  17524. },
  17525. reset: function () {
  17526. locked = false;
  17527. currentColorMask = null;
  17528. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  17529. }
  17530. };
  17531. }
  17532. function DepthBuffer() {
  17533. var locked = false;
  17534. var currentDepthMask = null;
  17535. var currentDepthFunc = null;
  17536. var currentDepthClear = null;
  17537. return {
  17538. setTest: function ( depthTest ) {
  17539. if ( depthTest ) {
  17540. enable( 2929 );
  17541. } else {
  17542. disable( 2929 );
  17543. }
  17544. },
  17545. setMask: function ( depthMask ) {
  17546. if ( currentDepthMask !== depthMask && ! locked ) {
  17547. gl.depthMask( depthMask );
  17548. currentDepthMask = depthMask;
  17549. }
  17550. },
  17551. setFunc: function ( depthFunc ) {
  17552. if ( currentDepthFunc !== depthFunc ) {
  17553. if ( depthFunc ) {
  17554. switch ( depthFunc ) {
  17555. case NeverDepth:
  17556. gl.depthFunc( 512 );
  17557. break;
  17558. case AlwaysDepth:
  17559. gl.depthFunc( 519 );
  17560. break;
  17561. case LessDepth:
  17562. gl.depthFunc( 513 );
  17563. break;
  17564. case LessEqualDepth:
  17565. gl.depthFunc( 515 );
  17566. break;
  17567. case EqualDepth:
  17568. gl.depthFunc( 514 );
  17569. break;
  17570. case GreaterEqualDepth:
  17571. gl.depthFunc( 518 );
  17572. break;
  17573. case GreaterDepth:
  17574. gl.depthFunc( 516 );
  17575. break;
  17576. case NotEqualDepth:
  17577. gl.depthFunc( 517 );
  17578. break;
  17579. default:
  17580. gl.depthFunc( 515 );
  17581. }
  17582. } else {
  17583. gl.depthFunc( 515 );
  17584. }
  17585. currentDepthFunc = depthFunc;
  17586. }
  17587. },
  17588. setLocked: function ( lock ) {
  17589. locked = lock;
  17590. },
  17591. setClear: function ( depth ) {
  17592. if ( currentDepthClear !== depth ) {
  17593. gl.clearDepth( depth );
  17594. currentDepthClear = depth;
  17595. }
  17596. },
  17597. reset: function () {
  17598. locked = false;
  17599. currentDepthMask = null;
  17600. currentDepthFunc = null;
  17601. currentDepthClear = null;
  17602. }
  17603. };
  17604. }
  17605. function StencilBuffer() {
  17606. var locked = false;
  17607. var currentStencilMask = null;
  17608. var currentStencilFunc = null;
  17609. var currentStencilRef = null;
  17610. var currentStencilFuncMask = null;
  17611. var currentStencilFail = null;
  17612. var currentStencilZFail = null;
  17613. var currentStencilZPass = null;
  17614. var currentStencilClear = null;
  17615. return {
  17616. setTest: function ( stencilTest ) {
  17617. if ( ! locked ) {
  17618. if ( stencilTest ) {
  17619. enable( 2960 );
  17620. } else {
  17621. disable( 2960 );
  17622. }
  17623. }
  17624. },
  17625. setMask: function ( stencilMask ) {
  17626. if ( currentStencilMask !== stencilMask && ! locked ) {
  17627. gl.stencilMask( stencilMask );
  17628. currentStencilMask = stencilMask;
  17629. }
  17630. },
  17631. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  17632. if ( currentStencilFunc !== stencilFunc ||
  17633. currentStencilRef !== stencilRef ||
  17634. currentStencilFuncMask !== stencilMask ) {
  17635. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  17636. currentStencilFunc = stencilFunc;
  17637. currentStencilRef = stencilRef;
  17638. currentStencilFuncMask = stencilMask;
  17639. }
  17640. },
  17641. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  17642. if ( currentStencilFail !== stencilFail ||
  17643. currentStencilZFail !== stencilZFail ||
  17644. currentStencilZPass !== stencilZPass ) {
  17645. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  17646. currentStencilFail = stencilFail;
  17647. currentStencilZFail = stencilZFail;
  17648. currentStencilZPass = stencilZPass;
  17649. }
  17650. },
  17651. setLocked: function ( lock ) {
  17652. locked = lock;
  17653. },
  17654. setClear: function ( stencil ) {
  17655. if ( currentStencilClear !== stencil ) {
  17656. gl.clearStencil( stencil );
  17657. currentStencilClear = stencil;
  17658. }
  17659. },
  17660. reset: function () {
  17661. locked = false;
  17662. currentStencilMask = null;
  17663. currentStencilFunc = null;
  17664. currentStencilRef = null;
  17665. currentStencilFuncMask = null;
  17666. currentStencilFail = null;
  17667. currentStencilZFail = null;
  17668. currentStencilZPass = null;
  17669. currentStencilClear = null;
  17670. }
  17671. };
  17672. }
  17673. //
  17674. var colorBuffer = new ColorBuffer();
  17675. var depthBuffer = new DepthBuffer();
  17676. var stencilBuffer = new StencilBuffer();
  17677. var maxVertexAttributes = gl.getParameter( 34921 );
  17678. var newAttributes = new Uint8Array( maxVertexAttributes );
  17679. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  17680. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  17681. var enabledCapabilities = {};
  17682. var compressedTextureFormats = null;
  17683. var currentProgram = null;
  17684. var currentBlendingEnabled = null;
  17685. var currentBlending = null;
  17686. var currentBlendEquation = null;
  17687. var currentBlendSrc = null;
  17688. var currentBlendDst = null;
  17689. var currentBlendEquationAlpha = null;
  17690. var currentBlendSrcAlpha = null;
  17691. var currentBlendDstAlpha = null;
  17692. var currentPremultipledAlpha = false;
  17693. var currentFlipSided = null;
  17694. var currentCullFace = null;
  17695. var currentLineWidth = null;
  17696. var currentPolygonOffsetFactor = null;
  17697. var currentPolygonOffsetUnits = null;
  17698. var maxTextures = gl.getParameter( 35661 );
  17699. var lineWidthAvailable = false;
  17700. var version = 0;
  17701. var glVersion = gl.getParameter( 7938 );
  17702. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  17703. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  17704. lineWidthAvailable = ( version >= 1.0 );
  17705. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  17706. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  17707. lineWidthAvailable = ( version >= 2.0 );
  17708. }
  17709. var currentTextureSlot = null;
  17710. var currentBoundTextures = {};
  17711. var currentScissor = new Vector4();
  17712. var currentViewport = new Vector4();
  17713. function createTexture( type, target, count ) {
  17714. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  17715. var texture = gl.createTexture();
  17716. gl.bindTexture( type, texture );
  17717. gl.texParameteri( type, 10241, 9728 );
  17718. gl.texParameteri( type, 10240, 9728 );
  17719. for ( var i = 0; i < count; i ++ ) {
  17720. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  17721. }
  17722. return texture;
  17723. }
  17724. var emptyTextures = {};
  17725. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  17726. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  17727. // init
  17728. colorBuffer.setClear( 0, 0, 0, 1 );
  17729. depthBuffer.setClear( 1 );
  17730. stencilBuffer.setClear( 0 );
  17731. enable( 2929 );
  17732. depthBuffer.setFunc( LessEqualDepth );
  17733. setFlipSided( false );
  17734. setCullFace( CullFaceBack );
  17735. enable( 2884 );
  17736. setBlending( NoBlending );
  17737. //
  17738. function initAttributes() {
  17739. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  17740. newAttributes[ i ] = 0;
  17741. }
  17742. }
  17743. function enableAttribute( attribute ) {
  17744. enableAttributeAndDivisor( attribute, 0 );
  17745. }
  17746. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  17747. newAttributes[ attribute ] = 1;
  17748. if ( enabledAttributes[ attribute ] === 0 ) {
  17749. gl.enableVertexAttribArray( attribute );
  17750. enabledAttributes[ attribute ] = 1;
  17751. }
  17752. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  17753. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  17754. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  17755. attributeDivisors[ attribute ] = meshPerAttribute;
  17756. }
  17757. }
  17758. function disableUnusedAttributes() {
  17759. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  17760. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  17761. gl.disableVertexAttribArray( i );
  17762. enabledAttributes[ i ] = 0;
  17763. }
  17764. }
  17765. }
  17766. function enable( id ) {
  17767. if ( enabledCapabilities[ id ] !== true ) {
  17768. gl.enable( id );
  17769. enabledCapabilities[ id ] = true;
  17770. }
  17771. }
  17772. function disable( id ) {
  17773. if ( enabledCapabilities[ id ] !== false ) {
  17774. gl.disable( id );
  17775. enabledCapabilities[ id ] = false;
  17776. }
  17777. }
  17778. function getCompressedTextureFormats() {
  17779. if ( compressedTextureFormats === null ) {
  17780. compressedTextureFormats = [];
  17781. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  17782. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  17783. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  17784. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  17785. var formats = gl.getParameter( 34467 );
  17786. for ( var i = 0; i < formats.length; i ++ ) {
  17787. compressedTextureFormats.push( formats[ i ] );
  17788. }
  17789. }
  17790. }
  17791. return compressedTextureFormats;
  17792. }
  17793. function useProgram( program ) {
  17794. if ( currentProgram !== program ) {
  17795. gl.useProgram( program );
  17796. currentProgram = program;
  17797. return true;
  17798. }
  17799. return false;
  17800. }
  17801. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  17802. if ( blending === NoBlending ) {
  17803. if ( currentBlendingEnabled ) {
  17804. disable( 3042 );
  17805. currentBlendingEnabled = false;
  17806. }
  17807. return;
  17808. }
  17809. if ( ! currentBlendingEnabled ) {
  17810. enable( 3042 );
  17811. currentBlendingEnabled = true;
  17812. }
  17813. if ( blending !== CustomBlending ) {
  17814. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  17815. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  17816. gl.blendEquation( 32774 );
  17817. currentBlendEquation = AddEquation;
  17818. currentBlendEquationAlpha = AddEquation;
  17819. }
  17820. if ( premultipliedAlpha ) {
  17821. switch ( blending ) {
  17822. case NormalBlending:
  17823. gl.blendFuncSeparate( 1, 771, 1, 771 );
  17824. break;
  17825. case AdditiveBlending:
  17826. gl.blendFunc( 1, 1 );
  17827. break;
  17828. case SubtractiveBlending:
  17829. gl.blendFuncSeparate( 0, 0, 769, 771 );
  17830. break;
  17831. case MultiplyBlending:
  17832. gl.blendFuncSeparate( 0, 768, 0, 770 );
  17833. break;
  17834. default:
  17835. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  17836. break;
  17837. }
  17838. } else {
  17839. switch ( blending ) {
  17840. case NormalBlending:
  17841. gl.blendFuncSeparate( 770, 771, 1, 771 );
  17842. break;
  17843. case AdditiveBlending:
  17844. gl.blendFunc( 770, 1 );
  17845. break;
  17846. case SubtractiveBlending:
  17847. gl.blendFunc( 0, 769 );
  17848. break;
  17849. case MultiplyBlending:
  17850. gl.blendFunc( 0, 768 );
  17851. break;
  17852. default:
  17853. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  17854. break;
  17855. }
  17856. }
  17857. currentBlendSrc = null;
  17858. currentBlendDst = null;
  17859. currentBlendSrcAlpha = null;
  17860. currentBlendDstAlpha = null;
  17861. currentBlending = blending;
  17862. currentPremultipledAlpha = premultipliedAlpha;
  17863. }
  17864. return;
  17865. }
  17866. // custom blending
  17867. blendEquationAlpha = blendEquationAlpha || blendEquation;
  17868. blendSrcAlpha = blendSrcAlpha || blendSrc;
  17869. blendDstAlpha = blendDstAlpha || blendDst;
  17870. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  17871. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  17872. currentBlendEquation = blendEquation;
  17873. currentBlendEquationAlpha = blendEquationAlpha;
  17874. }
  17875. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  17876. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  17877. currentBlendSrc = blendSrc;
  17878. currentBlendDst = blendDst;
  17879. currentBlendSrcAlpha = blendSrcAlpha;
  17880. currentBlendDstAlpha = blendDstAlpha;
  17881. }
  17882. currentBlending = blending;
  17883. currentPremultipledAlpha = null;
  17884. }
  17885. function setMaterial( material, frontFaceCW ) {
  17886. material.side === DoubleSide
  17887. ? disable( 2884 )
  17888. : enable( 2884 );
  17889. var flipSided = ( material.side === BackSide );
  17890. if ( frontFaceCW ) { flipSided = ! flipSided; }
  17891. setFlipSided( flipSided );
  17892. ( material.blending === NormalBlending && material.transparent === false )
  17893. ? setBlending( NoBlending )
  17894. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  17895. depthBuffer.setFunc( material.depthFunc );
  17896. depthBuffer.setTest( material.depthTest );
  17897. depthBuffer.setMask( material.depthWrite );
  17898. colorBuffer.setMask( material.colorWrite );
  17899. var stencilWrite = material.stencilWrite;
  17900. stencilBuffer.setTest( stencilWrite );
  17901. if ( stencilWrite ) {
  17902. stencilBuffer.setMask( material.stencilWriteMask );
  17903. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  17904. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  17905. }
  17906. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  17907. }
  17908. //
  17909. function setFlipSided( flipSided ) {
  17910. if ( currentFlipSided !== flipSided ) {
  17911. if ( flipSided ) {
  17912. gl.frontFace( 2304 );
  17913. } else {
  17914. gl.frontFace( 2305 );
  17915. }
  17916. currentFlipSided = flipSided;
  17917. }
  17918. }
  17919. function setCullFace( cullFace ) {
  17920. if ( cullFace !== CullFaceNone ) {
  17921. enable( 2884 );
  17922. if ( cullFace !== currentCullFace ) {
  17923. if ( cullFace === CullFaceBack ) {
  17924. gl.cullFace( 1029 );
  17925. } else if ( cullFace === CullFaceFront ) {
  17926. gl.cullFace( 1028 );
  17927. } else {
  17928. gl.cullFace( 1032 );
  17929. }
  17930. }
  17931. } else {
  17932. disable( 2884 );
  17933. }
  17934. currentCullFace = cullFace;
  17935. }
  17936. function setLineWidth( width ) {
  17937. if ( width !== currentLineWidth ) {
  17938. if ( lineWidthAvailable ) { gl.lineWidth( width ); }
  17939. currentLineWidth = width;
  17940. }
  17941. }
  17942. function setPolygonOffset( polygonOffset, factor, units ) {
  17943. if ( polygonOffset ) {
  17944. enable( 32823 );
  17945. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  17946. gl.polygonOffset( factor, units );
  17947. currentPolygonOffsetFactor = factor;
  17948. currentPolygonOffsetUnits = units;
  17949. }
  17950. } else {
  17951. disable( 32823 );
  17952. }
  17953. }
  17954. function setScissorTest( scissorTest ) {
  17955. if ( scissorTest ) {
  17956. enable( 3089 );
  17957. } else {
  17958. disable( 3089 );
  17959. }
  17960. }
  17961. // texture
  17962. function activeTexture( webglSlot ) {
  17963. if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; }
  17964. if ( currentTextureSlot !== webglSlot ) {
  17965. gl.activeTexture( webglSlot );
  17966. currentTextureSlot = webglSlot;
  17967. }
  17968. }
  17969. function bindTexture( webglType, webglTexture ) {
  17970. if ( currentTextureSlot === null ) {
  17971. activeTexture();
  17972. }
  17973. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  17974. if ( boundTexture === undefined ) {
  17975. boundTexture = { type: undefined, texture: undefined };
  17976. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  17977. }
  17978. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  17979. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  17980. boundTexture.type = webglType;
  17981. boundTexture.texture = webglTexture;
  17982. }
  17983. }
  17984. function compressedTexImage2D() {
  17985. try {
  17986. gl.compressedTexImage2D.apply( gl, arguments );
  17987. } catch ( error ) {
  17988. console.error( 'THREE.WebGLState:', error );
  17989. }
  17990. }
  17991. function texImage2D() {
  17992. try {
  17993. gl.texImage2D.apply( gl, arguments );
  17994. } catch ( error ) {
  17995. console.error( 'THREE.WebGLState:', error );
  17996. }
  17997. }
  17998. function texImage3D() {
  17999. try {
  18000. gl.texImage3D.apply( gl, arguments );
  18001. } catch ( error ) {
  18002. console.error( 'THREE.WebGLState:', error );
  18003. }
  18004. }
  18005. //
  18006. function scissor( scissor ) {
  18007. if ( currentScissor.equals( scissor ) === false ) {
  18008. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  18009. currentScissor.copy( scissor );
  18010. }
  18011. }
  18012. function viewport( viewport ) {
  18013. if ( currentViewport.equals( viewport ) === false ) {
  18014. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  18015. currentViewport.copy( viewport );
  18016. }
  18017. }
  18018. //
  18019. function reset() {
  18020. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18021. if ( enabledAttributes[ i ] === 1 ) {
  18022. gl.disableVertexAttribArray( i );
  18023. enabledAttributes[ i ] = 0;
  18024. }
  18025. }
  18026. enabledCapabilities = {};
  18027. compressedTextureFormats = null;
  18028. currentTextureSlot = null;
  18029. currentBoundTextures = {};
  18030. currentProgram = null;
  18031. currentBlending = null;
  18032. currentFlipSided = null;
  18033. currentCullFace = null;
  18034. colorBuffer.reset();
  18035. depthBuffer.reset();
  18036. stencilBuffer.reset();
  18037. }
  18038. return {
  18039. buffers: {
  18040. color: colorBuffer,
  18041. depth: depthBuffer,
  18042. stencil: stencilBuffer
  18043. },
  18044. initAttributes: initAttributes,
  18045. enableAttribute: enableAttribute,
  18046. enableAttributeAndDivisor: enableAttributeAndDivisor,
  18047. disableUnusedAttributes: disableUnusedAttributes,
  18048. enable: enable,
  18049. disable: disable,
  18050. getCompressedTextureFormats: getCompressedTextureFormats,
  18051. useProgram: useProgram,
  18052. setBlending: setBlending,
  18053. setMaterial: setMaterial,
  18054. setFlipSided: setFlipSided,
  18055. setCullFace: setCullFace,
  18056. setLineWidth: setLineWidth,
  18057. setPolygonOffset: setPolygonOffset,
  18058. setScissorTest: setScissorTest,
  18059. activeTexture: activeTexture,
  18060. bindTexture: bindTexture,
  18061. compressedTexImage2D: compressedTexImage2D,
  18062. texImage2D: texImage2D,
  18063. texImage3D: texImage3D,
  18064. scissor: scissor,
  18065. viewport: viewport,
  18066. reset: reset
  18067. };
  18068. }
  18069. /**
  18070. * @author mrdoob / http://mrdoob.com/
  18071. */
  18072. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  18073. var _videoTextures = new WeakMap();
  18074. var _canvas;
  18075. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18076. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18077. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  18078. && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;
  18079. function createCanvas( width, height ) {
  18080. // Use OffscreenCanvas when available. Specially needed in web workers
  18081. return useOffscreenCanvas ?
  18082. new OffscreenCanvas( width, height ) :
  18083. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  18084. }
  18085. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  18086. var scale = 1;
  18087. // handle case if texture exceeds max size
  18088. if ( image.width > maxSize || image.height > maxSize ) {
  18089. scale = maxSize / Math.max( image.width, image.height );
  18090. }
  18091. // only perform resize if necessary
  18092. if ( scale < 1 || needsPowerOfTwo === true ) {
  18093. // only perform resize for certain image types
  18094. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  18095. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  18096. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  18097. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  18098. var width = floor( scale * image.width );
  18099. var height = floor( scale * image.height );
  18100. if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); }
  18101. // cube textures can't reuse the same canvas
  18102. var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  18103. canvas.width = width;
  18104. canvas.height = height;
  18105. var context = canvas.getContext( '2d' );
  18106. context.drawImage( image, 0, 0, width, height );
  18107. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  18108. return canvas;
  18109. } else {
  18110. if ( 'data' in image ) {
  18111. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  18112. }
  18113. return image;
  18114. }
  18115. }
  18116. return image;
  18117. }
  18118. function isPowerOfTwo( image ) {
  18119. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  18120. }
  18121. function textureNeedsPowerOfTwo( texture ) {
  18122. if ( capabilities.isWebGL2 ) { return false; }
  18123. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  18124. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  18125. }
  18126. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  18127. return texture.generateMipmaps && supportsMips &&
  18128. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18129. }
  18130. function generateMipmap( target, texture, width, height ) {
  18131. _gl.generateMipmap( target );
  18132. var textureProperties = properties.get( texture );
  18133. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18134. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  18135. }
  18136. function getInternalFormat( glFormat, glType ) {
  18137. if ( ! capabilities.isWebGL2 ) { return glFormat; }
  18138. var internalFormat = glFormat;
  18139. if ( glFormat === 6403 ) {
  18140. if ( glType === 5126 ) { internalFormat = 33326; }
  18141. if ( glType === 5131 ) { internalFormat = 33325; }
  18142. if ( glType === 5121 ) { internalFormat = 33321; }
  18143. }
  18144. if ( glFormat === 6407 ) {
  18145. if ( glType === 5126 ) { internalFormat = 34837; }
  18146. if ( glType === 5131 ) { internalFormat = 34843; }
  18147. if ( glType === 5121 ) { internalFormat = 32849; }
  18148. }
  18149. if ( glFormat === 6408 ) {
  18150. if ( glType === 5126 ) { internalFormat = 34836; }
  18151. if ( glType === 5131 ) { internalFormat = 34842; }
  18152. if ( glType === 5121 ) { internalFormat = 32856; }
  18153. }
  18154. if ( internalFormat === 33325 || internalFormat === 33326 ||
  18155. internalFormat === 34842 || internalFormat === 34836 ) {
  18156. extensions.get( 'EXT_color_buffer_float' );
  18157. } else if ( internalFormat === 34843 || internalFormat === 34837 ) {
  18158. console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );
  18159. }
  18160. return internalFormat;
  18161. }
  18162. // Fallback filters for non-power-of-2 textures
  18163. function filterFallback( f ) {
  18164. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18165. return 9728;
  18166. }
  18167. return 9729;
  18168. }
  18169. //
  18170. function onTextureDispose( event ) {
  18171. var texture = event.target;
  18172. texture.removeEventListener( 'dispose', onTextureDispose );
  18173. deallocateTexture( texture );
  18174. if ( texture.isVideoTexture ) {
  18175. _videoTextures.delete( texture );
  18176. }
  18177. info.memory.textures --;
  18178. }
  18179. function onRenderTargetDispose( event ) {
  18180. var renderTarget = event.target;
  18181. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  18182. deallocateRenderTarget( renderTarget );
  18183. info.memory.textures --;
  18184. }
  18185. //
  18186. function deallocateTexture( texture ) {
  18187. var textureProperties = properties.get( texture );
  18188. if ( textureProperties.__webglInit === undefined ) { return; }
  18189. _gl.deleteTexture( textureProperties.__webglTexture );
  18190. properties.remove( texture );
  18191. }
  18192. function deallocateRenderTarget( renderTarget ) {
  18193. var renderTargetProperties = properties.get( renderTarget );
  18194. var textureProperties = properties.get( renderTarget.texture );
  18195. if ( ! renderTarget ) { return; }
  18196. if ( textureProperties.__webglTexture !== undefined ) {
  18197. _gl.deleteTexture( textureProperties.__webglTexture );
  18198. }
  18199. if ( renderTarget.depthTexture ) {
  18200. renderTarget.depthTexture.dispose();
  18201. }
  18202. if ( renderTarget.isWebGLRenderTargetCube ) {
  18203. for ( var i = 0; i < 6; i ++ ) {
  18204. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  18205. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); }
  18206. }
  18207. } else {
  18208. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  18209. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); }
  18210. }
  18211. if ( renderTarget.isWebGLMultiviewRenderTarget ) {
  18212. _gl.deleteTexture( renderTargetProperties.__webglColorTexture );
  18213. _gl.deleteTexture( renderTargetProperties.__webglDepthStencilTexture );
  18214. info.memory.textures -= 2;
  18215. for ( var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i ++ ) {
  18216. _gl.deleteFramebuffer( renderTargetProperties.__webglViewFramebuffers[ i ] );
  18217. }
  18218. }
  18219. properties.remove( renderTarget.texture );
  18220. properties.remove( renderTarget );
  18221. }
  18222. //
  18223. var textureUnits = 0;
  18224. function resetTextureUnits() {
  18225. textureUnits = 0;
  18226. }
  18227. function allocateTextureUnit() {
  18228. var textureUnit = textureUnits;
  18229. if ( textureUnit >= capabilities.maxTextures ) {
  18230. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18231. }
  18232. textureUnits += 1;
  18233. return textureUnit;
  18234. }
  18235. //
  18236. function setTexture2D( texture, slot ) {
  18237. var textureProperties = properties.get( texture );
  18238. if ( texture.isVideoTexture ) { updateVideoTexture( texture ); }
  18239. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18240. var image = texture.image;
  18241. if ( image === undefined ) {
  18242. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  18243. } else if ( image.complete === false ) {
  18244. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  18245. } else {
  18246. uploadTexture( textureProperties, texture, slot );
  18247. return;
  18248. }
  18249. }
  18250. state.activeTexture( 33984 + slot );
  18251. state.bindTexture( 3553, textureProperties.__webglTexture );
  18252. }
  18253. function setTexture2DArray( texture, slot ) {
  18254. var textureProperties = properties.get( texture );
  18255. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18256. uploadTexture( textureProperties, texture, slot );
  18257. return;
  18258. }
  18259. state.activeTexture( 33984 + slot );
  18260. state.bindTexture( 35866, textureProperties.__webglTexture );
  18261. }
  18262. function setTexture3D( texture, slot ) {
  18263. var textureProperties = properties.get( texture );
  18264. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18265. uploadTexture( textureProperties, texture, slot );
  18266. return;
  18267. }
  18268. state.activeTexture( 33984 + slot );
  18269. state.bindTexture( 32879, textureProperties.__webglTexture );
  18270. }
  18271. function setTextureCube( texture, slot ) {
  18272. if ( texture.image.length !== 6 ) { return; }
  18273. var textureProperties = properties.get( texture );
  18274. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18275. initTexture( textureProperties, texture );
  18276. state.activeTexture( 33984 + slot );
  18277. state.bindTexture( 34067, textureProperties.__webglTexture );
  18278. _gl.pixelStorei( 37440, texture.flipY );
  18279. var isCompressed = ( texture && texture.isCompressedTexture );
  18280. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  18281. var cubeImage = [];
  18282. for ( var i = 0; i < 6; i ++ ) {
  18283. if ( ! isCompressed && ! isDataTexture ) {
  18284. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );
  18285. } else {
  18286. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  18287. }
  18288. }
  18289. var image = cubeImage[ 0 ],
  18290. supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  18291. glFormat = utils.convert( texture.format ),
  18292. glType = utils.convert( texture.type ),
  18293. glInternalFormat = getInternalFormat( glFormat, glType );
  18294. setTextureParameters( 34067, texture, supportsMips );
  18295. var mipmaps;
  18296. if ( isCompressed ) {
  18297. for ( var i = 0; i < 6; i ++ ) {
  18298. mipmaps = cubeImage[ i ].mipmaps;
  18299. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18300. var mipmap = mipmaps[ j ];
  18301. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18302. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  18303. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18304. } else {
  18305. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  18306. }
  18307. } else {
  18308. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18309. }
  18310. }
  18311. }
  18312. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18313. } else {
  18314. mipmaps = texture.mipmaps;
  18315. for ( var i = 0; i < 6; i ++ ) {
  18316. if ( isDataTexture ) {
  18317. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  18318. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18319. var mipmap = mipmaps[ j ];
  18320. var mipmapImage = mipmap.image[ i ].image;
  18321. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  18322. }
  18323. } else {
  18324. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  18325. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18326. var mipmap = mipmaps[ j ];
  18327. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  18328. }
  18329. }
  18330. }
  18331. textureProperties.__maxMipLevel = mipmaps.length;
  18332. }
  18333. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18334. // We assume images for cube map have the same size.
  18335. generateMipmap( 34067, texture, image.width, image.height );
  18336. }
  18337. textureProperties.__version = texture.version;
  18338. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18339. } else {
  18340. state.activeTexture( 33984 + slot );
  18341. state.bindTexture( 34067, textureProperties.__webglTexture );
  18342. }
  18343. }
  18344. function setTextureCubeDynamic( texture, slot ) {
  18345. state.activeTexture( 33984 + slot );
  18346. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  18347. }
  18348. function setTextureParameters( textureType, texture, supportsMips ) {
  18349. var extension;
  18350. if ( supportsMips ) {
  18351. _gl.texParameteri( textureType, 10242, utils.convert( texture.wrapS ) );
  18352. _gl.texParameteri( textureType, 10243, utils.convert( texture.wrapT ) );
  18353. if ( textureType === 32879 || textureType === 35866 ) {
  18354. _gl.texParameteri( textureType, 32882, utils.convert( texture.wrapR ) );
  18355. }
  18356. _gl.texParameteri( textureType, 10240, utils.convert( texture.magFilter ) );
  18357. _gl.texParameteri( textureType, 10241, utils.convert( texture.minFilter ) );
  18358. } else {
  18359. _gl.texParameteri( textureType, 10242, 33071 );
  18360. _gl.texParameteri( textureType, 10243, 33071 );
  18361. if ( textureType === 32879 || textureType === 35866 ) {
  18362. _gl.texParameteri( textureType, 32882, 33071 );
  18363. }
  18364. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  18365. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  18366. }
  18367. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  18368. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  18369. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  18370. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  18371. }
  18372. }
  18373. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  18374. if ( extension ) {
  18375. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; }
  18376. if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; }
  18377. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  18378. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  18379. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  18380. }
  18381. }
  18382. }
  18383. function initTexture( textureProperties, texture ) {
  18384. if ( textureProperties.__webglInit === undefined ) {
  18385. textureProperties.__webglInit = true;
  18386. texture.addEventListener( 'dispose', onTextureDispose );
  18387. textureProperties.__webglTexture = _gl.createTexture();
  18388. info.memory.textures ++;
  18389. }
  18390. }
  18391. function uploadTexture( textureProperties, texture, slot ) {
  18392. var textureType = 3553;
  18393. if ( texture.isDataTexture2DArray ) { textureType = 35866; }
  18394. if ( texture.isDataTexture3D ) { textureType = 32879; }
  18395. initTexture( textureProperties, texture );
  18396. state.activeTexture( 33984 + slot );
  18397. state.bindTexture( textureType, textureProperties.__webglTexture );
  18398. _gl.pixelStorei( 37440, texture.flipY );
  18399. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  18400. _gl.pixelStorei( 3317, texture.unpackAlignment );
  18401. var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  18402. var image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );
  18403. var supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  18404. glFormat = utils.convert( texture.format ),
  18405. glType = utils.convert( texture.type ),
  18406. glInternalFormat = getInternalFormat( glFormat, glType );
  18407. setTextureParameters( textureType, texture, supportsMips );
  18408. var mipmap, mipmaps = texture.mipmaps;
  18409. if ( texture.isDepthTexture ) {
  18410. // populate depth texture with dummy data
  18411. glInternalFormat = 6402;
  18412. if ( texture.type === FloatType ) {
  18413. if ( ! capabilities.isWebGL2 ) { throw new Error( 'Float Depth Texture only supported in WebGL2.0' ); }
  18414. glInternalFormat = 36012;
  18415. } else if ( capabilities.isWebGL2 ) {
  18416. // WebGL 2.0 requires signed internalformat for glTexImage2D
  18417. glInternalFormat = 33189;
  18418. }
  18419. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  18420. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18421. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  18422. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18423. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  18424. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  18425. texture.type = UnsignedShortType;
  18426. glType = utils.convert( texture.type );
  18427. }
  18428. }
  18429. // Depth stencil textures need the DEPTH_STENCIL internal format
  18430. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18431. if ( texture.format === DepthStencilFormat ) {
  18432. glInternalFormat = 34041;
  18433. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18434. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  18435. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18436. if ( texture.type !== UnsignedInt248Type ) {
  18437. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  18438. texture.type = UnsignedInt248Type;
  18439. glType = utils.convert( texture.type );
  18440. }
  18441. }
  18442. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  18443. } else if ( texture.isDataTexture ) {
  18444. // use manually created mipmaps if available
  18445. // if there are no manual mipmaps
  18446. // set 0 level mipmap and then use GL to generate other mipmap levels
  18447. if ( mipmaps.length > 0 && supportsMips ) {
  18448. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18449. mipmap = mipmaps[ i ];
  18450. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18451. }
  18452. texture.generateMipmaps = false;
  18453. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18454. } else {
  18455. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  18456. textureProperties.__maxMipLevel = 0;
  18457. }
  18458. } else if ( texture.isCompressedTexture ) {
  18459. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18460. mipmap = mipmaps[ i ];
  18461. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18462. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  18463. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18464. } else {
  18465. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  18466. }
  18467. } else {
  18468. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18469. }
  18470. }
  18471. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18472. } else if ( texture.isDataTexture2DArray ) {
  18473. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18474. textureProperties.__maxMipLevel = 0;
  18475. } else if ( texture.isDataTexture3D ) {
  18476. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18477. textureProperties.__maxMipLevel = 0;
  18478. } else {
  18479. // regular Texture (image, video, canvas)
  18480. // use manually created mipmaps if available
  18481. // if there are no manual mipmaps
  18482. // set 0 level mipmap and then use GL to generate other mipmap levels
  18483. if ( mipmaps.length > 0 && supportsMips ) {
  18484. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18485. mipmap = mipmaps[ i ];
  18486. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  18487. }
  18488. texture.generateMipmaps = false;
  18489. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18490. } else {
  18491. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  18492. textureProperties.__maxMipLevel = 0;
  18493. }
  18494. }
  18495. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18496. generateMipmap( 3553, texture, image.width, image.height );
  18497. }
  18498. textureProperties.__version = texture.version;
  18499. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18500. }
  18501. // Render targets
  18502. // Setup storage for target texture and bind it to correct framebuffer
  18503. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  18504. var glFormat = utils.convert( renderTarget.texture.format );
  18505. var glType = utils.convert( renderTarget.texture.type );
  18506. var glInternalFormat = getInternalFormat( glFormat, glType );
  18507. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  18508. _gl.bindFramebuffer( 36160, framebuffer );
  18509. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  18510. _gl.bindFramebuffer( 36160, null );
  18511. }
  18512. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  18513. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  18514. _gl.bindRenderbuffer( 36161, renderbuffer );
  18515. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  18516. if ( isMultisample ) {
  18517. var samples = getRenderTargetSamples( renderTarget );
  18518. _gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height );
  18519. } else {
  18520. _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height );
  18521. }
  18522. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  18523. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  18524. if ( isMultisample ) {
  18525. var samples = getRenderTargetSamples( renderTarget );
  18526. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  18527. } else {
  18528. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  18529. }
  18530. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  18531. } else {
  18532. var glFormat = utils.convert( renderTarget.texture.format );
  18533. var glType = utils.convert( renderTarget.texture.type );
  18534. var glInternalFormat = getInternalFormat( glFormat, glType );
  18535. if ( isMultisample ) {
  18536. var samples = getRenderTargetSamples( renderTarget );
  18537. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18538. } else {
  18539. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  18540. }
  18541. }
  18542. _gl.bindRenderbuffer( 36161, null );
  18543. }
  18544. // Setup resources for a Depth Texture for a FBO (needs an extension)
  18545. function setupDepthTexture( framebuffer, renderTarget ) {
  18546. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  18547. if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); }
  18548. _gl.bindFramebuffer( 36160, framebuffer );
  18549. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  18550. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  18551. }
  18552. // upload an empty depth texture with framebuffer size
  18553. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  18554. renderTarget.depthTexture.image.width !== renderTarget.width ||
  18555. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  18556. renderTarget.depthTexture.image.width = renderTarget.width;
  18557. renderTarget.depthTexture.image.height = renderTarget.height;
  18558. renderTarget.depthTexture.needsUpdate = true;
  18559. }
  18560. setTexture2D( renderTarget.depthTexture, 0 );
  18561. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  18562. if ( renderTarget.depthTexture.format === DepthFormat ) {
  18563. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  18564. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  18565. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  18566. } else {
  18567. throw new Error( 'Unknown depthTexture format' );
  18568. }
  18569. }
  18570. // Setup GL resources for a non-texture depth buffer
  18571. function setupDepthRenderbuffer( renderTarget ) {
  18572. var renderTargetProperties = properties.get( renderTarget );
  18573. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  18574. if ( renderTarget.depthTexture ) {
  18575. if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); }
  18576. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  18577. } else {
  18578. if ( isCube ) {
  18579. renderTargetProperties.__webglDepthbuffer = [];
  18580. for ( var i = 0; i < 6; i ++ ) {
  18581. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  18582. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  18583. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  18584. }
  18585. } else {
  18586. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  18587. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  18588. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  18589. }
  18590. }
  18591. _gl.bindFramebuffer( 36160, null );
  18592. }
  18593. // Set up GL resources for the render target
  18594. function setupRenderTarget( renderTarget ) {
  18595. var renderTargetProperties = properties.get( renderTarget );
  18596. var textureProperties = properties.get( renderTarget.texture );
  18597. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  18598. textureProperties.__webglTexture = _gl.createTexture();
  18599. info.memory.textures ++;
  18600. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  18601. var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  18602. var isMultiview = ( renderTarget.isWebGLMultiviewRenderTarget === true );
  18603. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  18604. // Setup framebuffer
  18605. if ( isCube ) {
  18606. renderTargetProperties.__webglFramebuffer = [];
  18607. for ( var i = 0; i < 6; i ++ ) {
  18608. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  18609. }
  18610. } else {
  18611. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  18612. if ( isMultisample ) {
  18613. if ( capabilities.isWebGL2 ) {
  18614. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  18615. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  18616. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  18617. var glFormat = utils.convert( renderTarget.texture.format );
  18618. var glType = utils.convert( renderTarget.texture.type );
  18619. var glInternalFormat = getInternalFormat( glFormat, glType );
  18620. var samples = getRenderTargetSamples( renderTarget );
  18621. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18622. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  18623. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  18624. _gl.bindRenderbuffer( 36161, null );
  18625. if ( renderTarget.depthBuffer ) {
  18626. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  18627. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  18628. }
  18629. _gl.bindFramebuffer( 36160, null );
  18630. } else {
  18631. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  18632. }
  18633. } else if ( isMultiview ) {
  18634. if ( capabilities.multiview ) {
  18635. var width = renderTarget.width;
  18636. var height = renderTarget.height;
  18637. var numViews = renderTarget.numViews;
  18638. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  18639. var ext = extensions.get( 'OVR_multiview2' );
  18640. info.memory.textures += 2;
  18641. var colorTexture = _gl.createTexture();
  18642. _gl.bindTexture( 35866, colorTexture );
  18643. _gl.texParameteri( 35866, 10240, 9728 );
  18644. _gl.texParameteri( 35866, 10241, 9728 );
  18645. _gl.texImage3D( 35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null );
  18646. ext.framebufferTextureMultiviewOVR( 36160, 36064, colorTexture, 0, 0, numViews );
  18647. var depthStencilTexture = _gl.createTexture();
  18648. _gl.bindTexture( 35866, depthStencilTexture );
  18649. _gl.texParameteri( 35866, 10240, 9728 );
  18650. _gl.texParameteri( 35866, 10241, 9728 );
  18651. _gl.texImage3D( 35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null );
  18652. ext.framebufferTextureMultiviewOVR( 36160, 33306, depthStencilTexture, 0, 0, numViews );
  18653. var viewFramebuffers = new Array( numViews );
  18654. for ( var i = 0; i < numViews; ++ i ) {
  18655. viewFramebuffers[ i ] = _gl.createFramebuffer();
  18656. _gl.bindFramebuffer( 36160, viewFramebuffers[ i ] );
  18657. _gl.framebufferTextureLayer( 36160, 36064, colorTexture, 0, i );
  18658. }
  18659. renderTargetProperties.__webglColorTexture = colorTexture;
  18660. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  18661. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  18662. _gl.bindFramebuffer( 36160, null );
  18663. _gl.bindTexture( 35866, null );
  18664. } else {
  18665. console.warn( 'THREE.WebGLRenderer: WebGLMultiviewRenderTarget can only be used with WebGL2 and Multiview extension support.' );
  18666. }
  18667. }
  18668. }
  18669. // Setup color buffer
  18670. if ( isCube ) {
  18671. state.bindTexture( 34067, textureProperties.__webglTexture );
  18672. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  18673. for ( var i = 0; i < 6; i ++ ) {
  18674. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  18675. }
  18676. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  18677. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  18678. }
  18679. state.bindTexture( 34067, null );
  18680. } else if ( ! isMultiview ) {
  18681. state.bindTexture( 3553, textureProperties.__webglTexture );
  18682. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  18683. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  18684. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  18685. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  18686. }
  18687. state.bindTexture( 3553, null );
  18688. }
  18689. // Setup depth and stencil buffers
  18690. if ( renderTarget.depthBuffer ) {
  18691. setupDepthRenderbuffer( renderTarget );
  18692. }
  18693. }
  18694. function updateRenderTargetMipmap( renderTarget ) {
  18695. var texture = renderTarget.texture;
  18696. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  18697. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18698. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  18699. var webglTexture = properties.get( texture ).__webglTexture;
  18700. state.bindTexture( target, webglTexture );
  18701. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  18702. state.bindTexture( target, null );
  18703. }
  18704. }
  18705. function updateMultisampleRenderTarget( renderTarget ) {
  18706. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  18707. if ( capabilities.isWebGL2 ) {
  18708. var renderTargetProperties = properties.get( renderTarget );
  18709. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  18710. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  18711. var width = renderTarget.width;
  18712. var height = renderTarget.height;
  18713. var mask = 16384;
  18714. if ( renderTarget.depthBuffer ) { mask |= 256; }
  18715. if ( renderTarget.stencilBuffer ) { mask |= 1024; }
  18716. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  18717. } else {
  18718. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  18719. }
  18720. }
  18721. }
  18722. function getRenderTargetSamples( renderTarget ) {
  18723. return ( capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  18724. Math.min( capabilities.maxSamples, renderTarget.samples ) : 0;
  18725. }
  18726. function updateVideoTexture( texture ) {
  18727. var frame = info.render.frame;
  18728. // Check the last frame we updated the VideoTexture
  18729. if ( _videoTextures.get( texture ) !== frame ) {
  18730. _videoTextures.set( texture, frame );
  18731. texture.update();
  18732. }
  18733. }
  18734. // backwards compatibility
  18735. var warnedTexture2D = false;
  18736. var warnedTextureCube = false;
  18737. function safeSetTexture2D( texture, slot ) {
  18738. if ( texture && texture.isWebGLRenderTarget ) {
  18739. if ( warnedTexture2D === false ) {
  18740. console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18741. warnedTexture2D = true;
  18742. }
  18743. texture = texture.texture;
  18744. }
  18745. setTexture2D( texture, slot );
  18746. }
  18747. function safeSetTextureCube( texture, slot ) {
  18748. if ( texture && texture.isWebGLRenderTargetCube ) {
  18749. if ( warnedTextureCube === false ) {
  18750. console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18751. warnedTextureCube = true;
  18752. }
  18753. texture = texture.texture;
  18754. }
  18755. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18756. // TODO: unify these code paths
  18757. if ( ( texture && texture.isCubeTexture ) ||
  18758. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18759. // CompressedTexture can have Array in image :/
  18760. // this function alone should take care of cube textures
  18761. setTextureCube( texture, slot );
  18762. } else {
  18763. // assumed: texture property of THREE.WebGLRenderTargetCube
  18764. setTextureCubeDynamic( texture, slot );
  18765. }
  18766. }
  18767. //
  18768. this.allocateTextureUnit = allocateTextureUnit;
  18769. this.resetTextureUnits = resetTextureUnits;
  18770. this.setTexture2D = setTexture2D;
  18771. this.setTexture2DArray = setTexture2DArray;
  18772. this.setTexture3D = setTexture3D;
  18773. this.setTextureCube = setTextureCube;
  18774. this.setTextureCubeDynamic = setTextureCubeDynamic;
  18775. this.setupRenderTarget = setupRenderTarget;
  18776. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  18777. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  18778. this.safeSetTexture2D = safeSetTexture2D;
  18779. this.safeSetTextureCube = safeSetTextureCube;
  18780. }
  18781. /**
  18782. * @author thespite / http://www.twitter.com/thespite
  18783. */
  18784. function WebGLUtils( gl, extensions, capabilities ) {
  18785. function convert( p ) {
  18786. var extension;
  18787. if ( p === RepeatWrapping ) { return 10497; }
  18788. if ( p === ClampToEdgeWrapping ) { return 33071; }
  18789. if ( p === MirroredRepeatWrapping ) { return 33648; }
  18790. if ( p === NearestFilter ) { return 9728; }
  18791. if ( p === NearestMipmapNearestFilter ) { return 9984; }
  18792. if ( p === NearestMipmapLinearFilter ) { return 9986; }
  18793. if ( p === LinearFilter ) { return 9729; }
  18794. if ( p === LinearMipmapNearestFilter ) { return 9985; }
  18795. if ( p === LinearMipmapLinearFilter ) { return 9987; }
  18796. if ( p === UnsignedByteType ) { return 5121; }
  18797. if ( p === UnsignedShort4444Type ) { return 32819; }
  18798. if ( p === UnsignedShort5551Type ) { return 32820; }
  18799. if ( p === UnsignedShort565Type ) { return 33635; }
  18800. if ( p === ByteType ) { return 5120; }
  18801. if ( p === ShortType ) { return 5122; }
  18802. if ( p === UnsignedShortType ) { return 5123; }
  18803. if ( p === IntType ) { return 5124; }
  18804. if ( p === UnsignedIntType ) { return 5125; }
  18805. if ( p === FloatType ) { return 5126; }
  18806. if ( p === HalfFloatType ) {
  18807. if ( capabilities.isWebGL2 ) { return 5131; }
  18808. extension = extensions.get( 'OES_texture_half_float' );
  18809. if ( extension !== null ) { return extension.HALF_FLOAT_OES; }
  18810. }
  18811. if ( p === AlphaFormat ) { return 6406; }
  18812. if ( p === RGBFormat ) { return 6407; }
  18813. if ( p === RGBAFormat ) { return 6408; }
  18814. if ( p === LuminanceFormat ) { return 6409; }
  18815. if ( p === LuminanceAlphaFormat ) { return 6410; }
  18816. if ( p === DepthFormat ) { return 6402; }
  18817. if ( p === DepthStencilFormat ) { return 34041; }
  18818. if ( p === RedFormat ) { return 6403; }
  18819. if ( p === AddEquation ) { return 32774; }
  18820. if ( p === SubtractEquation ) { return 32778; }
  18821. if ( p === ReverseSubtractEquation ) { return 32779; }
  18822. if ( p === ZeroFactor ) { return 0; }
  18823. if ( p === OneFactor ) { return 1; }
  18824. if ( p === SrcColorFactor ) { return 768; }
  18825. if ( p === OneMinusSrcColorFactor ) { return 769; }
  18826. if ( p === SrcAlphaFactor ) { return 770; }
  18827. if ( p === OneMinusSrcAlphaFactor ) { return 771; }
  18828. if ( p === DstAlphaFactor ) { return 772; }
  18829. if ( p === OneMinusDstAlphaFactor ) { return 773; }
  18830. if ( p === DstColorFactor ) { return 774; }
  18831. if ( p === OneMinusDstColorFactor ) { return 775; }
  18832. if ( p === SrcAlphaSaturateFactor ) { return 776; }
  18833. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  18834. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  18835. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  18836. if ( extension !== null ) {
  18837. if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; }
  18838. if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; }
  18839. if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; }
  18840. if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; }
  18841. }
  18842. }
  18843. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  18844. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  18845. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  18846. if ( extension !== null ) {
  18847. if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; }
  18848. if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; }
  18849. if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; }
  18850. if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; }
  18851. }
  18852. }
  18853. if ( p === RGB_ETC1_Format ) {
  18854. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  18855. if ( extension !== null ) { return extension.COMPRESSED_RGB_ETC1_WEBGL; }
  18856. }
  18857. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  18858. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  18859. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  18860. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  18861. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  18862. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  18863. if ( extension !== null ) {
  18864. return p;
  18865. }
  18866. }
  18867. if ( p === MinEquation || p === MaxEquation ) {
  18868. if ( capabilities.isWebGL2 ) {
  18869. if ( p === MinEquation ) { return 32775; }
  18870. if ( p === MaxEquation ) { return 32776; }
  18871. }
  18872. extension = extensions.get( 'EXT_blend_minmax' );
  18873. if ( extension !== null ) {
  18874. if ( p === MinEquation ) { return extension.MIN_EXT; }
  18875. if ( p === MaxEquation ) { return extension.MAX_EXT; }
  18876. }
  18877. }
  18878. if ( p === UnsignedInt248Type ) {
  18879. if ( capabilities.isWebGL2 ) { return 34042; }
  18880. extension = extensions.get( 'WEBGL_depth_texture' );
  18881. if ( extension !== null ) { return extension.UNSIGNED_INT_24_8_WEBGL; }
  18882. }
  18883. return 0;
  18884. }
  18885. return { convert: convert };
  18886. }
  18887. /**
  18888. * @author fernandojsg / http://fernandojsg.com
  18889. * @author Takahiro https://github.com/takahirox
  18890. */
  18891. function WebGLMultiviewRenderTarget( width, height, numViews, options ) {
  18892. WebGLRenderTarget.call( this, width, height, options );
  18893. this.depthBuffer = false;
  18894. this.stencilBuffer = false;
  18895. this.numViews = numViews;
  18896. }
  18897. WebGLMultiviewRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  18898. constructor: WebGLMultiviewRenderTarget,
  18899. isWebGLMultiviewRenderTarget: true,
  18900. copy: function ( source ) {
  18901. WebGLRenderTarget.prototype.copy.call( this, source );
  18902. this.numViews = source.numViews;
  18903. return this;
  18904. },
  18905. setNumViews: function ( numViews ) {
  18906. if ( this.numViews !== numViews ) {
  18907. this.numViews = numViews;
  18908. this.dispose();
  18909. }
  18910. return this;
  18911. }
  18912. } );
  18913. /**
  18914. * @author fernandojsg / http://fernandojsg.com
  18915. * @author Takahiro https://github.com/takahirox
  18916. */
  18917. function WebGLMultiview( renderer, gl ) {
  18918. var DEFAULT_NUMVIEWS = 2;
  18919. var capabilities = renderer.capabilities;
  18920. var properties = renderer.properties;
  18921. var maxNumViews = capabilities.maxMultiviewViews;
  18922. var renderTarget, currentRenderTarget;
  18923. var mat3, mat4, cameraArray, renderSize;
  18924. function getCameraArray( camera ) {
  18925. if ( camera.isArrayCamera ) { return camera.cameras; }
  18926. cameraArray[ 0 ] = camera;
  18927. return cameraArray;
  18928. }
  18929. //
  18930. function updateCameraProjectionMatricesUniform( camera, uniforms ) {
  18931. var cameras = getCameraArray( camera );
  18932. for ( var i = 0; i < cameras.length; i ++ ) {
  18933. mat4[ i ].copy( cameras[ i ].projectionMatrix );
  18934. }
  18935. uniforms.setValue( gl, 'projectionMatrices', mat4 );
  18936. }
  18937. function updateCameraViewMatricesUniform( camera, uniforms ) {
  18938. var cameras = getCameraArray( camera );
  18939. for ( var i = 0; i < cameras.length; i ++ ) {
  18940. mat4[ i ].copy( cameras[ i ].matrixWorldInverse );
  18941. }
  18942. uniforms.setValue( gl, 'viewMatrices', mat4 );
  18943. }
  18944. function updateObjectMatricesUniforms( object, camera, uniforms ) {
  18945. var cameras = getCameraArray( camera );
  18946. for ( var i = 0; i < cameras.length; i ++ ) {
  18947. mat4[ i ].multiplyMatrices( cameras[ i ].matrixWorldInverse, object.matrixWorld );
  18948. mat3[ i ].getNormalMatrix( mat4[ i ] );
  18949. }
  18950. uniforms.setValue( gl, 'modelViewMatrices', mat4 );
  18951. uniforms.setValue( gl, 'normalMatrices', mat3 );
  18952. }
  18953. function isMultiviewCompatible( camera ) {
  18954. if ( ! camera.isArrayCamera ) { return true; }
  18955. var cameras = camera.cameras;
  18956. if ( cameras.length > maxNumViews ) { return false; }
  18957. for ( var i = 1, il = cameras.length; i < il; i ++ ) {
  18958. if ( cameras[ 0 ].viewport.z !== cameras[ i ].viewport.z ||
  18959. cameras[ 0 ].viewport.w !== cameras[ i ].viewport.w ) { return false; }
  18960. }
  18961. return true;
  18962. }
  18963. function resizeRenderTarget( camera ) {
  18964. if ( currentRenderTarget ) {
  18965. renderSize.set( currentRenderTarget.width, currentRenderTarget.height );
  18966. } else {
  18967. renderer.getDrawingBufferSize( renderSize );
  18968. }
  18969. if ( camera.isArrayCamera ) {
  18970. var viewport = camera.cameras[ 0 ].viewport;
  18971. renderTarget.setSize( viewport.z, viewport.w );
  18972. renderTarget.setNumViews( camera.cameras.length );
  18973. } else {
  18974. renderTarget.setSize( renderSize.x, renderSize.y );
  18975. renderTarget.setNumViews( DEFAULT_NUMVIEWS );
  18976. }
  18977. }
  18978. function attachCamera( camera ) {
  18979. if ( ! isMultiviewCompatible( camera ) ) { return; }
  18980. currentRenderTarget = renderer.getRenderTarget();
  18981. resizeRenderTarget( camera );
  18982. renderer.setRenderTarget( renderTarget );
  18983. }
  18984. function detachCamera( camera ) {
  18985. if ( renderTarget !== renderer.getRenderTarget() ) { return; }
  18986. renderer.setRenderTarget( currentRenderTarget );
  18987. flush( camera );
  18988. }
  18989. function flush( camera ) {
  18990. var srcRenderTarget = renderTarget;
  18991. var numViews = srcRenderTarget.numViews;
  18992. var srcFramebuffers = properties.get( srcRenderTarget ).__webglViewFramebuffers;
  18993. var viewWidth = srcRenderTarget.width;
  18994. var viewHeight = srcRenderTarget.height;
  18995. if ( camera.isArrayCamera ) {
  18996. for ( var i = 0; i < numViews; i ++ ) {
  18997. var viewport = camera.cameras[ i ].viewport;
  18998. var x1 = viewport.x;
  18999. var y1 = viewport.y;
  19000. var x2 = x1 + viewport.z;
  19001. var y2 = y1 + viewport.w;
  19002. gl.bindFramebuffer( 36008, srcFramebuffers[ i ] );
  19003. gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728 );
  19004. }
  19005. } else {
  19006. gl.bindFramebuffer( 36008, srcFramebuffers[ 0 ] );
  19007. gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728 );
  19008. }
  19009. }
  19010. if ( renderer.capabilities.multiview ) {
  19011. renderTarget = new WebGLMultiviewRenderTarget( 0, 0, DEFAULT_NUMVIEWS );
  19012. renderSize = new Vector2();
  19013. mat4 = [];
  19014. mat3 = [];
  19015. cameraArray = [];
  19016. var maxViews = capabilities.maxMultiviewViews;
  19017. for ( var i = 0; i < maxViews; i ++ ) {
  19018. mat4[ i ] = new Matrix4();
  19019. mat3[ i ] = new Matrix3();
  19020. }
  19021. }
  19022. this.attachCamera = attachCamera;
  19023. this.detachCamera = detachCamera;
  19024. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  19025. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  19026. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  19027. }
  19028. /**
  19029. * @author mrdoob / http://mrdoob.com/
  19030. */
  19031. function Group() {
  19032. Object3D.call( this );
  19033. this.type = 'Group';
  19034. }
  19035. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19036. constructor: Group,
  19037. isGroup: true
  19038. } );
  19039. /**
  19040. * @author mrdoob / http://mrdoob.com/
  19041. */
  19042. function ArrayCamera( array ) {
  19043. PerspectiveCamera.call( this );
  19044. this.cameras = array || [];
  19045. }
  19046. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  19047. constructor: ArrayCamera,
  19048. isArrayCamera: true
  19049. } );
  19050. /**
  19051. * @author jsantell / https://www.jsantell.com/
  19052. * @author mrdoob / http://mrdoob.com/
  19053. */
  19054. var cameraLPos = new Vector3();
  19055. var cameraRPos = new Vector3();
  19056. /**
  19057. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19058. * the cameras' projection and world matrices have already been set.
  19059. * And that near and far planes are identical for both cameras.
  19060. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19061. */
  19062. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  19063. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  19064. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  19065. var ipd = cameraLPos.distanceTo( cameraRPos );
  19066. var projL = cameraL.projectionMatrix.elements;
  19067. var projR = cameraR.projectionMatrix.elements;
  19068. // VR systems will have identical far and near planes, and
  19069. // most likely identical top and bottom frustum extents.
  19070. // Use the left camera for these values.
  19071. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  19072. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  19073. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  19074. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  19075. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  19076. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  19077. var left = near * leftFov;
  19078. var right = near * rightFov;
  19079. // Calculate the new camera's position offset from the
  19080. // left camera. xOffset should be roughly half `ipd`.
  19081. var zOffset = ipd / ( - leftFov + rightFov );
  19082. var xOffset = zOffset * - leftFov;
  19083. // TODO: Better way to apply this offset?
  19084. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  19085. camera.translateX( xOffset );
  19086. camera.translateZ( zOffset );
  19087. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  19088. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19089. // Find the union of the frustum values of the cameras and scale
  19090. // the values so that the near plane's position does not change in world space,
  19091. // although must now be relative to the new union camera.
  19092. var near2 = near + zOffset;
  19093. var far2 = far + zOffset;
  19094. var left2 = left - xOffset;
  19095. var right2 = right + ( ipd - xOffset );
  19096. var top2 = topFov * far / far2 * near2;
  19097. var bottom2 = bottomFov * far / far2 * near2;
  19098. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  19099. }
  19100. /**
  19101. * @author mrdoob / http://mrdoob.com/
  19102. */
  19103. function WebVRManager( renderer ) {
  19104. var renderWidth, renderHeight;
  19105. var scope = this;
  19106. var device = null;
  19107. var frameData = null;
  19108. var poseTarget = null;
  19109. var controllers = [];
  19110. var standingMatrix = new Matrix4();
  19111. var standingMatrixInverse = new Matrix4();
  19112. var framebufferScaleFactor = 1.0;
  19113. var referenceSpaceType = 'local-floor';
  19114. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  19115. frameData = new window.VRFrameData();
  19116. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  19117. }
  19118. var matrixWorldInverse = new Matrix4();
  19119. var tempQuaternion = new Quaternion();
  19120. var tempPosition = new Vector3();
  19121. var cameraL = new PerspectiveCamera();
  19122. cameraL.viewport = new Vector4();
  19123. cameraL.layers.enable( 1 );
  19124. var cameraR = new PerspectiveCamera();
  19125. cameraR.viewport = new Vector4();
  19126. cameraR.layers.enable( 2 );
  19127. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  19128. cameraVR.layers.enable( 1 );
  19129. cameraVR.layers.enable( 2 );
  19130. //
  19131. function isPresenting() {
  19132. return device !== null && device.isPresenting === true;
  19133. }
  19134. var currentSize = new Vector2(), currentPixelRatio;
  19135. function onVRDisplayPresentChange() {
  19136. if ( isPresenting() ) {
  19137. var eyeParameters = device.getEyeParameters( 'left' );
  19138. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19139. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19140. currentPixelRatio = renderer.getPixelRatio();
  19141. renderer.getSize( currentSize );
  19142. renderer.setDrawingBufferSize( renderWidth, renderHeight, 1 );
  19143. cameraL.viewport.set( 0, 0, renderWidth / 2, renderHeight );
  19144. cameraR.viewport.set( renderWidth / 2, 0, renderWidth / 2, renderHeight );
  19145. animation.start();
  19146. scope.dispatchEvent( { type: 'sessionstart' } );
  19147. } else {
  19148. if ( scope.enabled ) {
  19149. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  19150. }
  19151. animation.stop();
  19152. scope.dispatchEvent( { type: 'sessionend' } );
  19153. }
  19154. }
  19155. //
  19156. var triggers = [];
  19157. function findGamepad( id ) {
  19158. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19159. for ( var i = 0, j = 0, l = gamepads.length; i < l; i ++ ) {
  19160. var gamepad = gamepads[ i ];
  19161. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  19162. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  19163. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  19164. gamepad.id.startsWith( 'HTC Vive Focus' ) ||
  19165. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  19166. if ( j === id ) { return gamepad; }
  19167. j ++;
  19168. }
  19169. }
  19170. }
  19171. function updateControllers() {
  19172. for ( var i = 0; i < controllers.length; i ++ ) {
  19173. var controller = controllers[ i ];
  19174. var gamepad = findGamepad( i );
  19175. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  19176. if ( gamepad.pose === null ) { return; }
  19177. // Pose
  19178. var pose = gamepad.pose;
  19179. if ( pose.hasPosition === false ) { controller.position.set( 0.2, - 0.6, - 0.05 ); }
  19180. if ( pose.position !== null ) { controller.position.fromArray( pose.position ); }
  19181. if ( pose.orientation !== null ) { controller.quaternion.fromArray( pose.orientation ); }
  19182. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  19183. controller.matrix.premultiply( standingMatrix );
  19184. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  19185. controller.matrixWorldNeedsUpdate = true;
  19186. controller.visible = true;
  19187. // Trigger
  19188. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19189. if ( triggers[ i ] === undefined ) { triggers[ i ] = false; }
  19190. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  19191. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  19192. if ( triggers[ i ] === true ) {
  19193. controller.dispatchEvent( { type: 'selectstart' } );
  19194. } else {
  19195. controller.dispatchEvent( { type: 'selectend' } );
  19196. controller.dispatchEvent( { type: 'select' } );
  19197. }
  19198. }
  19199. } else {
  19200. controller.visible = false;
  19201. }
  19202. }
  19203. }
  19204. function updateViewportFromBounds( viewport, bounds ) {
  19205. if ( bounds !== null && bounds.length === 4 ) {
  19206. viewport.set( bounds[ 0 ] * renderWidth, bounds[ 1 ] * renderHeight, bounds[ 2 ] * renderWidth, bounds[ 3 ] * renderHeight );
  19207. }
  19208. }
  19209. //
  19210. this.enabled = false;
  19211. this.getController = function ( id ) {
  19212. var controller = controllers[ id ];
  19213. if ( controller === undefined ) {
  19214. controller = new Group();
  19215. controller.matrixAutoUpdate = false;
  19216. controller.visible = false;
  19217. controllers[ id ] = controller;
  19218. }
  19219. return controller;
  19220. };
  19221. this.getDevice = function () {
  19222. return device;
  19223. };
  19224. this.setDevice = function ( value ) {
  19225. if ( value !== undefined ) { device = value; }
  19226. animation.setContext( value );
  19227. };
  19228. this.setFramebufferScaleFactor = function ( value ) {
  19229. framebufferScaleFactor = value;
  19230. };
  19231. this.setReferenceSpaceType = function ( value ) {
  19232. referenceSpaceType = value;
  19233. };
  19234. this.setPoseTarget = function ( object ) {
  19235. if ( object !== undefined ) { poseTarget = object; }
  19236. };
  19237. this.getCamera = function ( camera ) {
  19238. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19239. if ( isPresenting() === false ) {
  19240. camera.position.set( 0, userHeight, 0 );
  19241. camera.rotation.set( 0, 0, 0 );
  19242. return camera;
  19243. }
  19244. device.depthNear = camera.near;
  19245. device.depthFar = camera.far;
  19246. device.getFrameData( frameData );
  19247. //
  19248. if ( referenceSpaceType === 'local-floor' ) {
  19249. var stageParameters = device.stageParameters;
  19250. if ( stageParameters ) {
  19251. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  19252. } else {
  19253. standingMatrix.makeTranslation( 0, userHeight, 0 );
  19254. }
  19255. }
  19256. var pose = frameData.pose;
  19257. var poseObject = poseTarget !== null ? poseTarget : camera;
  19258. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19259. poseObject.matrix.copy( standingMatrix );
  19260. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  19261. if ( pose.orientation !== null ) {
  19262. tempQuaternion.fromArray( pose.orientation );
  19263. poseObject.quaternion.multiply( tempQuaternion );
  19264. }
  19265. if ( pose.position !== null ) {
  19266. tempQuaternion.setFromRotationMatrix( standingMatrix );
  19267. tempPosition.fromArray( pose.position );
  19268. tempPosition.applyQuaternion( tempQuaternion );
  19269. poseObject.position.add( tempPosition );
  19270. }
  19271. poseObject.updateMatrixWorld();
  19272. //
  19273. cameraL.near = camera.near;
  19274. cameraR.near = camera.near;
  19275. cameraL.far = camera.far;
  19276. cameraR.far = camera.far;
  19277. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  19278. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  19279. // TODO (mrdoob) Double check this code
  19280. standingMatrixInverse.getInverse( standingMatrix );
  19281. if ( referenceSpaceType === 'local-floor' ) {
  19282. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  19283. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  19284. }
  19285. var parent = poseObject.parent;
  19286. if ( parent !== null ) {
  19287. matrixWorldInverse.getInverse( parent.matrixWorld );
  19288. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  19289. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  19290. }
  19291. // envMap and Mirror needs camera.matrixWorld
  19292. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  19293. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  19294. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  19295. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  19296. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  19297. //
  19298. var layers = device.getLayers();
  19299. if ( layers.length ) {
  19300. var layer = layers[ 0 ];
  19301. updateViewportFromBounds( cameraL.viewport, layer.leftBounds );
  19302. updateViewportFromBounds( cameraR.viewport, layer.rightBounds );
  19303. }
  19304. updateControllers();
  19305. return cameraVR;
  19306. };
  19307. this.getStandingMatrix = function () {
  19308. return standingMatrix;
  19309. };
  19310. this.isPresenting = isPresenting;
  19311. // Animation Loop
  19312. var animation = new WebGLAnimation();
  19313. this.setAnimationLoop = function ( callback ) {
  19314. animation.setAnimationLoop( callback );
  19315. if ( isPresenting() ) { animation.start(); }
  19316. };
  19317. this.submitFrame = function () {
  19318. if ( isPresenting() ) { device.submitFrame(); }
  19319. };
  19320. this.dispose = function () {
  19321. if ( typeof window !== 'undefined' ) {
  19322. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  19323. }
  19324. };
  19325. // DEPRECATED
  19326. this.setFrameOfReferenceType = function () {
  19327. console.warn( 'THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.' );
  19328. };
  19329. }
  19330. Object.assign( WebVRManager.prototype, EventDispatcher.prototype );
  19331. /**
  19332. * @author mrdoob / http://mrdoob.com/
  19333. */
  19334. function WebXRManager( renderer, gl ) {
  19335. var scope = this;
  19336. var session = null;
  19337. var referenceSpace = null;
  19338. var referenceSpaceType = 'local-floor';
  19339. var pose = null;
  19340. var poseTarget = null;
  19341. var controllers = [];
  19342. var inputSources = [];
  19343. function isPresenting() {
  19344. return session !== null && referenceSpace !== null;
  19345. }
  19346. //
  19347. var cameraL = new PerspectiveCamera();
  19348. cameraL.layers.enable( 1 );
  19349. cameraL.viewport = new Vector4();
  19350. var cameraR = new PerspectiveCamera();
  19351. cameraR.layers.enable( 2 );
  19352. cameraR.viewport = new Vector4();
  19353. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  19354. cameraVR.layers.enable( 1 );
  19355. cameraVR.layers.enable( 2 );
  19356. //
  19357. this.enabled = false;
  19358. this.getController = function ( id ) {
  19359. var controller = controllers[ id ];
  19360. if ( controller === undefined ) {
  19361. controller = new Group();
  19362. controller.matrixAutoUpdate = false;
  19363. controller.visible = false;
  19364. controllers[ id ] = controller;
  19365. }
  19366. return controller;
  19367. };
  19368. //
  19369. function onSessionEvent( event ) {
  19370. for ( var i = 0; i < controllers.length; i ++ ) {
  19371. if ( inputSources[ i ] === event.inputSource ) {
  19372. controllers[ i ].dispatchEvent( { type: event.type } );
  19373. }
  19374. }
  19375. }
  19376. function onSessionEnd() {
  19377. renderer.setFramebuffer( null );
  19378. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  19379. animation.stop();
  19380. scope.dispatchEvent( { type: 'sessionend' } );
  19381. }
  19382. function onRequestReferenceSpace( value ) {
  19383. referenceSpace = value;
  19384. animation.setContext( session );
  19385. animation.start();
  19386. scope.dispatchEvent( { type: 'sessionstart' } );
  19387. }
  19388. this.setFramebufferScaleFactor = function ( value ) {
  19389. };
  19390. this.setReferenceSpaceType = function ( value ) {
  19391. referenceSpaceType = value;
  19392. };
  19393. this.getSession = function () {
  19394. return session;
  19395. };
  19396. this.setSession = function ( value ) {
  19397. session = value;
  19398. if ( session !== null ) {
  19399. session.addEventListener( 'select', onSessionEvent );
  19400. session.addEventListener( 'selectstart', onSessionEvent );
  19401. session.addEventListener( 'selectend', onSessionEvent );
  19402. session.addEventListener( 'end', onSessionEnd );
  19403. session.updateRenderState( { baseLayer: new XRWebGLLayer( session, gl ) } );
  19404. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  19405. //
  19406. inputSources = session.inputSources;
  19407. session.addEventListener( 'inputsourceschange', function () {
  19408. inputSources = session.inputSources;
  19409. console.log( inputSources );
  19410. for ( var i = 0; i < controllers.length; i ++ ) {
  19411. var controller = controllers[ i ];
  19412. controller.userData.inputSource = inputSources[ i ];
  19413. }
  19414. } );
  19415. }
  19416. };
  19417. function updateCamera( camera, parent ) {
  19418. if ( parent === null ) {
  19419. camera.matrixWorld.copy( camera.matrix );
  19420. } else {
  19421. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  19422. }
  19423. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19424. }
  19425. this.setPoseTarget = function ( object ) {
  19426. if ( object !== undefined ) { poseTarget = object; }
  19427. };
  19428. this.getCamera = function ( camera ) {
  19429. if ( isPresenting() ) {
  19430. var parent = camera.parent;
  19431. var cameras = cameraVR.cameras;
  19432. var object = poseTarget || camera;
  19433. updateCamera( cameraVR, parent );
  19434. for ( var i = 0; i < cameras.length; i ++ ) {
  19435. updateCamera( cameras[ i ], parent );
  19436. }
  19437. // update camera and its children
  19438. object.matrixWorld.copy( cameraVR.matrixWorld );
  19439. var children = object.children;
  19440. for ( var i = 0, l = children.length; i < l; i ++ ) {
  19441. children[ i ].updateMatrixWorld( true );
  19442. }
  19443. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  19444. return cameraVR;
  19445. }
  19446. return camera;
  19447. };
  19448. this.getCameraPose = function ( ) {
  19449. return pose;
  19450. };
  19451. this.isPresenting = isPresenting;
  19452. // Animation Loop
  19453. var onAnimationFrameCallback = null;
  19454. function onAnimationFrame( time, frame ) {
  19455. pose = frame.getViewerPose( referenceSpace );
  19456. if ( pose !== null ) {
  19457. var views = pose.views;
  19458. var baseLayer = session.renderState.baseLayer;
  19459. renderer.setFramebuffer( baseLayer.framebuffer );
  19460. for ( var i = 0; i < views.length; i ++ ) {
  19461. var view = views[ i ];
  19462. var viewport = baseLayer.getViewport( view );
  19463. var viewMatrix = view.transform.inverse.matrix;
  19464. var camera = cameraVR.cameras[ i ];
  19465. camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix );
  19466. camera.projectionMatrix.fromArray( view.projectionMatrix );
  19467. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  19468. if ( i === 0 ) {
  19469. cameraVR.matrix.copy( camera.matrix );
  19470. }
  19471. }
  19472. }
  19473. //
  19474. for ( var i = 0; i < controllers.length; i ++ ) {
  19475. var controller = controllers[ i ];
  19476. var inputSource = inputSources[ i ];
  19477. if ( inputSource ) {
  19478. var inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  19479. if ( inputPose !== null ) {
  19480. controller.matrix.fromArray( inputPose.transform.matrix );
  19481. controller.matrix.decompose( controller.position, controller.rotation, controller.scale );
  19482. controller.visible = true;
  19483. continue;
  19484. }
  19485. }
  19486. controller.visible = false;
  19487. }
  19488. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame ); }
  19489. }
  19490. var animation = new WebGLAnimation();
  19491. animation.setAnimationLoop( onAnimationFrame );
  19492. this.setAnimationLoop = function ( callback ) {
  19493. onAnimationFrameCallback = callback;
  19494. };
  19495. this.dispose = function () {};
  19496. // DEPRECATED
  19497. this.getStandingMatrix = function () {
  19498. console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' );
  19499. return new Matrix4();
  19500. };
  19501. this.getDevice = function () {
  19502. console.warn( 'THREE.WebXRManager: getDevice() has been deprecated.' );
  19503. };
  19504. this.setDevice = function () {
  19505. console.warn( 'THREE.WebXRManager: setDevice() has been deprecated.' );
  19506. };
  19507. this.setFrameOfReferenceType = function () {
  19508. console.warn( 'THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.' );
  19509. };
  19510. this.submitFrame = function () {};
  19511. }
  19512. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  19513. /**
  19514. * @author supereggbert / http://www.paulbrunt.co.uk/
  19515. * @author mrdoob / http://mrdoob.com/
  19516. * @author alteredq / http://alteredqualia.com/
  19517. * @author szimek / https://github.com/szimek/
  19518. * @author tschw
  19519. */
  19520. function WebGLRenderer( parameters ) {
  19521. parameters = parameters || {};
  19522. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  19523. _context = parameters.context !== undefined ? parameters.context : null,
  19524. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  19525. _depth = parameters.depth !== undefined ? parameters.depth : true,
  19526. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  19527. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  19528. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  19529. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  19530. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  19531. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  19532. var currentRenderList = null;
  19533. var currentRenderState = null;
  19534. // public properties
  19535. this.domElement = _canvas;
  19536. // Debug configuration container
  19537. this.debug = {
  19538. /**
  19539. * Enables error checking and reporting when shader programs are being compiled
  19540. * @type {boolean}
  19541. */
  19542. checkShaderErrors: true
  19543. };
  19544. // clearing
  19545. this.autoClear = true;
  19546. this.autoClearColor = true;
  19547. this.autoClearDepth = true;
  19548. this.autoClearStencil = true;
  19549. // scene graph
  19550. this.sortObjects = true;
  19551. // user-defined clipping
  19552. this.clippingPlanes = [];
  19553. this.localClippingEnabled = false;
  19554. // physically based shading
  19555. this.gammaFactor = 2.0; // for backwards compatibility
  19556. this.gammaInput = false;
  19557. this.gammaOutput = false;
  19558. // physical lights
  19559. this.physicallyCorrectLights = false;
  19560. // tone mapping
  19561. this.toneMapping = LinearToneMapping;
  19562. this.toneMappingExposure = 1.0;
  19563. this.toneMappingWhitePoint = 1.0;
  19564. // morphs
  19565. this.maxMorphTargets = 8;
  19566. this.maxMorphNormals = 4;
  19567. // internal properties
  19568. var _this = this,
  19569. _isContextLost = false,
  19570. // internal state cache
  19571. _framebuffer = null,
  19572. _currentActiveCubeFace = 0,
  19573. _currentActiveMipmapLevel = 0,
  19574. _currentRenderTarget = null,
  19575. _currentFramebuffer = null,
  19576. _currentMaterialId = - 1,
  19577. // geometry and program caching
  19578. _currentGeometryProgram = {
  19579. geometry: null,
  19580. program: null,
  19581. wireframe: false
  19582. },
  19583. _currentCamera = null,
  19584. _currentArrayCamera = null,
  19585. _currentViewport = new Vector4(),
  19586. _currentScissor = new Vector4(),
  19587. _currentScissorTest = null,
  19588. //
  19589. _width = _canvas.width,
  19590. _height = _canvas.height,
  19591. _pixelRatio = 1,
  19592. _viewport = new Vector4( 0, 0, _width, _height ),
  19593. _scissor = new Vector4( 0, 0, _width, _height ),
  19594. _scissorTest = false,
  19595. // frustum
  19596. _frustum = new Frustum(),
  19597. // clipping
  19598. _clipping = new WebGLClipping(),
  19599. _clippingEnabled = false,
  19600. _localClippingEnabled = false,
  19601. // camera matrices cache
  19602. _projScreenMatrix = new Matrix4(),
  19603. _vector3 = new Vector3();
  19604. function getTargetPixelRatio() {
  19605. return _currentRenderTarget === null ? _pixelRatio : 1;
  19606. }
  19607. // initialize
  19608. var _gl;
  19609. try {
  19610. var contextAttributes = {
  19611. alpha: _alpha,
  19612. depth: _depth,
  19613. stencil: _stencil,
  19614. antialias: _antialias,
  19615. premultipliedAlpha: _premultipliedAlpha,
  19616. preserveDrawingBuffer: _preserveDrawingBuffer,
  19617. powerPreference: _powerPreference,
  19618. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  19619. xrCompatible: true
  19620. };
  19621. // event listeners must be registered before WebGL context is created, see #12753
  19622. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  19623. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  19624. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  19625. if ( _gl === null ) {
  19626. if ( _canvas.getContext( 'webgl' ) !== null ) {
  19627. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  19628. } else {
  19629. throw new Error( 'Error creating WebGL context.' );
  19630. }
  19631. }
  19632. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  19633. if ( _gl.getShaderPrecisionFormat === undefined ) {
  19634. _gl.getShaderPrecisionFormat = function () {
  19635. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  19636. };
  19637. }
  19638. } catch ( error ) {
  19639. console.error( 'THREE.WebGLRenderer: ' + error.message );
  19640. throw error;
  19641. }
  19642. var extensions, capabilities, state, info;
  19643. var properties, textures, attributes, geometries, objects;
  19644. var programCache, renderLists, renderStates;
  19645. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  19646. var utils;
  19647. function initGLContext() {
  19648. extensions = new WebGLExtensions( _gl );
  19649. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  19650. if ( ! capabilities.isWebGL2 ) {
  19651. extensions.get( 'WEBGL_depth_texture' );
  19652. extensions.get( 'OES_texture_float' );
  19653. extensions.get( 'OES_texture_half_float' );
  19654. extensions.get( 'OES_texture_half_float_linear' );
  19655. extensions.get( 'OES_standard_derivatives' );
  19656. extensions.get( 'OES_element_index_uint' );
  19657. extensions.get( 'ANGLE_instanced_arrays' );
  19658. }
  19659. extensions.get( 'OES_texture_float_linear' );
  19660. utils = new WebGLUtils( _gl, extensions, capabilities );
  19661. state = new WebGLState( _gl, extensions, utils, capabilities );
  19662. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  19663. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  19664. info = new WebGLInfo( _gl );
  19665. properties = new WebGLProperties();
  19666. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  19667. attributes = new WebGLAttributes( _gl );
  19668. geometries = new WebGLGeometries( _gl, attributes, info );
  19669. objects = new WebGLObjects( geometries, info );
  19670. morphtargets = new WebGLMorphtargets( _gl );
  19671. programCache = new WebGLPrograms( _this, extensions, capabilities );
  19672. renderLists = new WebGLRenderLists();
  19673. renderStates = new WebGLRenderStates();
  19674. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  19675. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  19676. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  19677. info.programs = programCache.programs;
  19678. _this.capabilities = capabilities;
  19679. _this.extensions = extensions;
  19680. _this.properties = properties;
  19681. _this.renderLists = renderLists;
  19682. _this.state = state;
  19683. _this.info = info;
  19684. }
  19685. initGLContext();
  19686. // vr
  19687. var vr = ( typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ) ? new WebXRManager( _this, _gl ) : new WebVRManager( _this );
  19688. this.vr = vr;
  19689. // Multiview
  19690. var multiview = new WebGLMultiview( _this, _gl );
  19691. // shadow map
  19692. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  19693. this.shadowMap = shadowMap;
  19694. // API
  19695. this.getContext = function () {
  19696. return _gl;
  19697. };
  19698. this.getContextAttributes = function () {
  19699. return _gl.getContextAttributes();
  19700. };
  19701. this.forceContextLoss = function () {
  19702. var extension = extensions.get( 'WEBGL_lose_context' );
  19703. if ( extension ) { extension.loseContext(); }
  19704. };
  19705. this.forceContextRestore = function () {
  19706. var extension = extensions.get( 'WEBGL_lose_context' );
  19707. if ( extension ) { extension.restoreContext(); }
  19708. };
  19709. this.getPixelRatio = function () {
  19710. return _pixelRatio;
  19711. };
  19712. this.setPixelRatio = function ( value ) {
  19713. if ( value === undefined ) { return; }
  19714. _pixelRatio = value;
  19715. this.setSize( _width, _height, false );
  19716. };
  19717. this.getSize = function ( target ) {
  19718. if ( target === undefined ) {
  19719. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  19720. target = new Vector2();
  19721. }
  19722. return target.set( _width, _height );
  19723. };
  19724. this.setSize = function ( width, height, updateStyle ) {
  19725. if ( vr.isPresenting() ) {
  19726. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  19727. return;
  19728. }
  19729. _width = width;
  19730. _height = height;
  19731. _canvas.width = Math.floor( width * _pixelRatio );
  19732. _canvas.height = Math.floor( height * _pixelRatio );
  19733. if ( updateStyle !== false ) {
  19734. _canvas.style.width = width + 'px';
  19735. _canvas.style.height = height + 'px';
  19736. }
  19737. this.setViewport( 0, 0, width, height );
  19738. };
  19739. this.getDrawingBufferSize = function ( target ) {
  19740. if ( target === undefined ) {
  19741. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  19742. target = new Vector2();
  19743. }
  19744. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  19745. };
  19746. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  19747. _width = width;
  19748. _height = height;
  19749. _pixelRatio = pixelRatio;
  19750. _canvas.width = Math.floor( width * pixelRatio );
  19751. _canvas.height = Math.floor( height * pixelRatio );
  19752. this.setViewport( 0, 0, width, height );
  19753. };
  19754. this.getCurrentViewport = function ( target ) {
  19755. if ( target === undefined ) {
  19756. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  19757. target = new Vector4();
  19758. }
  19759. return target.copy( _currentViewport );
  19760. };
  19761. this.getViewport = function ( target ) {
  19762. return target.copy( _viewport );
  19763. };
  19764. this.setViewport = function ( x, y, width, height ) {
  19765. if ( x.isVector4 ) {
  19766. _viewport.set( x.x, x.y, x.z, x.w );
  19767. } else {
  19768. _viewport.set( x, y, width, height );
  19769. }
  19770. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  19771. };
  19772. this.getScissor = function ( target ) {
  19773. return target.copy( _scissor );
  19774. };
  19775. this.setScissor = function ( x, y, width, height ) {
  19776. if ( x.isVector4 ) {
  19777. _scissor.set( x.x, x.y, x.z, x.w );
  19778. } else {
  19779. _scissor.set( x, y, width, height );
  19780. }
  19781. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  19782. };
  19783. this.getScissorTest = function () {
  19784. return _scissorTest;
  19785. };
  19786. this.setScissorTest = function ( boolean ) {
  19787. state.setScissorTest( _scissorTest = boolean );
  19788. };
  19789. // Clearing
  19790. this.getClearColor = function () {
  19791. return background.getClearColor();
  19792. };
  19793. this.setClearColor = function () {
  19794. background.setClearColor.apply( background, arguments );
  19795. };
  19796. this.getClearAlpha = function () {
  19797. return background.getClearAlpha();
  19798. };
  19799. this.setClearAlpha = function () {
  19800. background.setClearAlpha.apply( background, arguments );
  19801. };
  19802. this.clear = function ( color, depth, stencil ) {
  19803. var bits = 0;
  19804. if ( color === undefined || color ) { bits |= 16384; }
  19805. if ( depth === undefined || depth ) { bits |= 256; }
  19806. if ( stencil === undefined || stencil ) { bits |= 1024; }
  19807. _gl.clear( bits );
  19808. };
  19809. this.clearColor = function () {
  19810. this.clear( true, false, false );
  19811. };
  19812. this.clearDepth = function () {
  19813. this.clear( false, true, false );
  19814. };
  19815. this.clearStencil = function () {
  19816. this.clear( false, false, true );
  19817. };
  19818. //
  19819. this.dispose = function () {
  19820. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  19821. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  19822. renderLists.dispose();
  19823. renderStates.dispose();
  19824. properties.dispose();
  19825. objects.dispose();
  19826. vr.dispose();
  19827. animation.stop();
  19828. };
  19829. // Events
  19830. function onContextLost( event ) {
  19831. event.preventDefault();
  19832. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  19833. _isContextLost = true;
  19834. }
  19835. function onContextRestore( /* event */ ) {
  19836. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  19837. _isContextLost = false;
  19838. initGLContext();
  19839. }
  19840. function onMaterialDispose( event ) {
  19841. var material = event.target;
  19842. material.removeEventListener( 'dispose', onMaterialDispose );
  19843. deallocateMaterial( material );
  19844. }
  19845. // Buffer deallocation
  19846. function deallocateMaterial( material ) {
  19847. releaseMaterialProgramReference( material );
  19848. properties.remove( material );
  19849. }
  19850. function releaseMaterialProgramReference( material ) {
  19851. var programInfo = properties.get( material ).program;
  19852. material.program = undefined;
  19853. if ( programInfo !== undefined ) {
  19854. programCache.releaseProgram( programInfo );
  19855. }
  19856. }
  19857. // Buffer rendering
  19858. function renderObjectImmediate( object, program ) {
  19859. object.render( function ( object ) {
  19860. _this.renderBufferImmediate( object, program );
  19861. } );
  19862. }
  19863. this.renderBufferImmediate = function ( object, program ) {
  19864. state.initAttributes();
  19865. var buffers = properties.get( object );
  19866. if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); }
  19867. if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); }
  19868. if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); }
  19869. if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); }
  19870. var programAttributes = program.getAttributes();
  19871. if ( object.hasPositions ) {
  19872. _gl.bindBuffer( 34962, buffers.position );
  19873. _gl.bufferData( 34962, object.positionArray, 35048 );
  19874. state.enableAttribute( programAttributes.position );
  19875. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  19876. }
  19877. if ( object.hasNormals ) {
  19878. _gl.bindBuffer( 34962, buffers.normal );
  19879. _gl.bufferData( 34962, object.normalArray, 35048 );
  19880. state.enableAttribute( programAttributes.normal );
  19881. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  19882. }
  19883. if ( object.hasUvs ) {
  19884. _gl.bindBuffer( 34962, buffers.uv );
  19885. _gl.bufferData( 34962, object.uvArray, 35048 );
  19886. state.enableAttribute( programAttributes.uv );
  19887. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  19888. }
  19889. if ( object.hasColors ) {
  19890. _gl.bindBuffer( 34962, buffers.color );
  19891. _gl.bufferData( 34962, object.colorArray, 35048 );
  19892. state.enableAttribute( programAttributes.color );
  19893. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  19894. }
  19895. state.disableUnusedAttributes();
  19896. _gl.drawArrays( 4, 0, object.count );
  19897. object.count = 0;
  19898. };
  19899. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  19900. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  19901. state.setMaterial( material, frontFaceCW );
  19902. var program = setProgram( camera, fog, material, object );
  19903. var updateBuffers = false;
  19904. if ( _currentGeometryProgram.geometry !== geometry.id ||
  19905. _currentGeometryProgram.program !== program.id ||
  19906. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  19907. _currentGeometryProgram.geometry = geometry.id;
  19908. _currentGeometryProgram.program = program.id;
  19909. _currentGeometryProgram.wireframe = material.wireframe === true;
  19910. updateBuffers = true;
  19911. }
  19912. if ( object.morphTargetInfluences ) {
  19913. morphtargets.update( object, geometry, material, program );
  19914. updateBuffers = true;
  19915. }
  19916. //
  19917. var index = geometry.index;
  19918. var position = geometry.attributes.position;
  19919. var rangeFactor = 1;
  19920. if ( material.wireframe === true ) {
  19921. index = geometries.getWireframeAttribute( geometry );
  19922. rangeFactor = 2;
  19923. }
  19924. var attribute;
  19925. var renderer = bufferRenderer;
  19926. if ( index !== null ) {
  19927. attribute = attributes.get( index );
  19928. renderer = indexedBufferRenderer;
  19929. renderer.setIndex( attribute );
  19930. }
  19931. if ( updateBuffers ) {
  19932. setupVertexAttributes( material, program, geometry );
  19933. if ( index !== null ) {
  19934. _gl.bindBuffer( 34963, attribute.buffer );
  19935. }
  19936. }
  19937. //
  19938. var dataCount = Infinity;
  19939. if ( index !== null ) {
  19940. dataCount = index.count;
  19941. } else if ( position !== undefined ) {
  19942. dataCount = position.count;
  19943. }
  19944. var rangeStart = geometry.drawRange.start * rangeFactor;
  19945. var rangeCount = geometry.drawRange.count * rangeFactor;
  19946. var groupStart = group !== null ? group.start * rangeFactor : 0;
  19947. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  19948. var drawStart = Math.max( rangeStart, groupStart );
  19949. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  19950. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  19951. if ( drawCount === 0 ) { return; }
  19952. //
  19953. if ( object.isMesh ) {
  19954. if ( material.wireframe === true ) {
  19955. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  19956. renderer.setMode( 1 );
  19957. } else {
  19958. switch ( object.drawMode ) {
  19959. case TrianglesDrawMode:
  19960. renderer.setMode( 4 );
  19961. break;
  19962. case TriangleStripDrawMode:
  19963. renderer.setMode( 5 );
  19964. break;
  19965. case TriangleFanDrawMode:
  19966. renderer.setMode( 6 );
  19967. break;
  19968. }
  19969. }
  19970. } else if ( object.isLine ) {
  19971. var lineWidth = material.linewidth;
  19972. if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material
  19973. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  19974. if ( object.isLineSegments ) {
  19975. renderer.setMode( 1 );
  19976. } else if ( object.isLineLoop ) {
  19977. renderer.setMode( 2 );
  19978. } else {
  19979. renderer.setMode( 3 );
  19980. }
  19981. } else if ( object.isPoints ) {
  19982. renderer.setMode( 0 );
  19983. } else if ( object.isSprite ) {
  19984. renderer.setMode( 4 );
  19985. }
  19986. if ( geometry && geometry.isInstancedBufferGeometry ) {
  19987. if ( geometry.maxInstancedCount > 0 ) {
  19988. renderer.renderInstances( geometry, drawStart, drawCount );
  19989. }
  19990. } else {
  19991. renderer.render( drawStart, drawCount );
  19992. }
  19993. };
  19994. function setupVertexAttributes( material, program, geometry ) {
  19995. if ( geometry && geometry.isInstancedBufferGeometry && ! capabilities.isWebGL2 ) {
  19996. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  19997. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  19998. return;
  19999. }
  20000. }
  20001. state.initAttributes();
  20002. var geometryAttributes = geometry.attributes;
  20003. var programAttributes = program.getAttributes();
  20004. var materialDefaultAttributeValues = material.defaultAttributeValues;
  20005. for ( var name in programAttributes ) {
  20006. var programAttribute = programAttributes[ name ];
  20007. if ( programAttribute >= 0 ) {
  20008. var geometryAttribute = geometryAttributes[ name ];
  20009. if ( geometryAttribute !== undefined ) {
  20010. var normalized = geometryAttribute.normalized;
  20011. var size = geometryAttribute.itemSize;
  20012. var attribute = attributes.get( geometryAttribute );
  20013. // TODO Attribute may not be available on context restore
  20014. if ( attribute === undefined ) { continue; }
  20015. var buffer = attribute.buffer;
  20016. var type = attribute.type;
  20017. var bytesPerElement = attribute.bytesPerElement;
  20018. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  20019. var data = geometryAttribute.data;
  20020. var stride = data.stride;
  20021. var offset = geometryAttribute.offset;
  20022. if ( data && data.isInstancedInterleavedBuffer ) {
  20023. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  20024. if ( geometry.maxInstancedCount === undefined ) {
  20025. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  20026. }
  20027. } else {
  20028. state.enableAttribute( programAttribute );
  20029. }
  20030. _gl.bindBuffer( 34962, buffer );
  20031. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  20032. } else {
  20033. if ( geometryAttribute.isInstancedBufferAttribute ) {
  20034. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  20035. if ( geometry.maxInstancedCount === undefined ) {
  20036. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  20037. }
  20038. } else {
  20039. state.enableAttribute( programAttribute );
  20040. }
  20041. _gl.bindBuffer( 34962, buffer );
  20042. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  20043. }
  20044. } else if ( materialDefaultAttributeValues !== undefined ) {
  20045. var value = materialDefaultAttributeValues[ name ];
  20046. if ( value !== undefined ) {
  20047. switch ( value.length ) {
  20048. case 2:
  20049. _gl.vertexAttrib2fv( programAttribute, value );
  20050. break;
  20051. case 3:
  20052. _gl.vertexAttrib3fv( programAttribute, value );
  20053. break;
  20054. case 4:
  20055. _gl.vertexAttrib4fv( programAttribute, value );
  20056. break;
  20057. default:
  20058. _gl.vertexAttrib1fv( programAttribute, value );
  20059. }
  20060. }
  20061. }
  20062. }
  20063. }
  20064. state.disableUnusedAttributes();
  20065. }
  20066. // Compile
  20067. this.compile = function ( scene, camera ) {
  20068. currentRenderState = renderStates.get( scene, camera );
  20069. currentRenderState.init();
  20070. scene.traverse( function ( object ) {
  20071. if ( object.isLight ) {
  20072. currentRenderState.pushLight( object );
  20073. if ( object.castShadow ) {
  20074. currentRenderState.pushShadow( object );
  20075. }
  20076. }
  20077. } );
  20078. currentRenderState.setupLights( camera );
  20079. scene.traverse( function ( object ) {
  20080. if ( object.material ) {
  20081. if ( Array.isArray( object.material ) ) {
  20082. for ( var i = 0; i < object.material.length; i ++ ) {
  20083. initMaterial( object.material[ i ], scene.fog, object );
  20084. }
  20085. } else {
  20086. initMaterial( object.material, scene.fog, object );
  20087. }
  20088. }
  20089. } );
  20090. };
  20091. // Animation Loop
  20092. var onAnimationFrameCallback = null;
  20093. function onAnimationFrame( time ) {
  20094. if ( vr.isPresenting() ) { return; }
  20095. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); }
  20096. }
  20097. var animation = new WebGLAnimation();
  20098. animation.setAnimationLoop( onAnimationFrame );
  20099. if ( typeof window !== 'undefined' ) { animation.setContext( window ); }
  20100. this.setAnimationLoop = function ( callback ) {
  20101. onAnimationFrameCallback = callback;
  20102. vr.setAnimationLoop( callback );
  20103. animation.start();
  20104. };
  20105. // Rendering
  20106. this.render = function ( scene, camera ) {
  20107. var renderTarget, forceClear;
  20108. if ( arguments[ 2 ] !== undefined ) {
  20109. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  20110. renderTarget = arguments[ 2 ];
  20111. }
  20112. if ( arguments[ 3 ] !== undefined ) {
  20113. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  20114. forceClear = arguments[ 3 ];
  20115. }
  20116. if ( ! ( camera && camera.isCamera ) ) {
  20117. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  20118. return;
  20119. }
  20120. if ( _isContextLost ) { return; }
  20121. // reset caching for this frame
  20122. _currentGeometryProgram.geometry = null;
  20123. _currentGeometryProgram.program = null;
  20124. _currentGeometryProgram.wireframe = false;
  20125. _currentMaterialId = - 1;
  20126. _currentCamera = null;
  20127. // update scene graph
  20128. if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); }
  20129. // update camera matrices and frustum
  20130. if ( camera.parent === null ) { camera.updateMatrixWorld(); }
  20131. if ( vr.enabled ) {
  20132. camera = vr.getCamera( camera );
  20133. }
  20134. //
  20135. currentRenderState = renderStates.get( scene, camera );
  20136. currentRenderState.init();
  20137. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  20138. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  20139. _frustum.setFromMatrix( _projScreenMatrix );
  20140. _localClippingEnabled = this.localClippingEnabled;
  20141. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  20142. currentRenderList = renderLists.get( scene, camera );
  20143. currentRenderList.init();
  20144. projectObject( scene, camera, 0, _this.sortObjects );
  20145. if ( _this.sortObjects === true ) {
  20146. currentRenderList.sort();
  20147. }
  20148. //
  20149. if ( _clippingEnabled ) { _clipping.beginShadows(); }
  20150. var shadowsArray = currentRenderState.state.shadowsArray;
  20151. shadowMap.render( shadowsArray, scene, camera );
  20152. currentRenderState.setupLights( camera );
  20153. if ( _clippingEnabled ) { _clipping.endShadows(); }
  20154. //
  20155. if ( this.info.autoReset ) { this.info.reset(); }
  20156. if ( renderTarget !== undefined ) {
  20157. this.setRenderTarget( renderTarget );
  20158. }
  20159. if ( capabilities.multiview ) {
  20160. multiview.attachCamera( camera );
  20161. }
  20162. //
  20163. background.render( currentRenderList, scene, camera, forceClear );
  20164. // render scene
  20165. var opaqueObjects = currentRenderList.opaque;
  20166. var transparentObjects = currentRenderList.transparent;
  20167. if ( scene.overrideMaterial ) {
  20168. var overrideMaterial = scene.overrideMaterial;
  20169. if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera, overrideMaterial ); }
  20170. if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera, overrideMaterial ); }
  20171. } else {
  20172. // opaque pass (front-to-back order)
  20173. if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera ); }
  20174. // transparent pass (back-to-front order)
  20175. if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera ); }
  20176. }
  20177. //
  20178. scene.onAfterRender( _this, scene, camera );
  20179. //
  20180. if ( _currentRenderTarget !== null ) {
  20181. // Generate mipmap if we're using any kind of mipmap filtering
  20182. textures.updateRenderTargetMipmap( _currentRenderTarget );
  20183. // resolve multisample renderbuffers to a single-sample texture if necessary
  20184. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  20185. }
  20186. // Ensure depth buffer writing is enabled so it can be cleared on next render
  20187. state.buffers.depth.setTest( true );
  20188. state.buffers.depth.setMask( true );
  20189. state.buffers.color.setMask( true );
  20190. state.setPolygonOffset( false );
  20191. if ( capabilities.multiview ) {
  20192. multiview.detachCamera( camera );
  20193. }
  20194. if ( vr.enabled ) {
  20195. vr.submitFrame();
  20196. }
  20197. // _gl.finish();
  20198. currentRenderList = null;
  20199. currentRenderState = null;
  20200. };
  20201. function projectObject( object, camera, groupOrder, sortObjects ) {
  20202. if ( object.visible === false ) { return; }
  20203. var visible = object.layers.test( camera.layers );
  20204. if ( visible ) {
  20205. if ( object.isGroup ) {
  20206. groupOrder = object.renderOrder;
  20207. } else if ( object.isLOD ) {
  20208. if ( object.autoUpdate === true ) { object.update( camera ); }
  20209. } else if ( object.isLight ) {
  20210. currentRenderState.pushLight( object );
  20211. if ( object.castShadow ) {
  20212. currentRenderState.pushShadow( object );
  20213. }
  20214. } else if ( object.isSprite ) {
  20215. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  20216. if ( sortObjects ) {
  20217. _vector3.setFromMatrixPosition( object.matrixWorld )
  20218. .applyMatrix4( _projScreenMatrix );
  20219. }
  20220. var geometry = objects.update( object );
  20221. var material = object.material;
  20222. if ( material.visible ) {
  20223. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  20224. }
  20225. }
  20226. } else if ( object.isImmediateRenderObject ) {
  20227. if ( sortObjects ) {
  20228. _vector3.setFromMatrixPosition( object.matrixWorld )
  20229. .applyMatrix4( _projScreenMatrix );
  20230. }
  20231. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  20232. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  20233. if ( object.isSkinnedMesh ) {
  20234. object.skeleton.update();
  20235. }
  20236. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  20237. if ( sortObjects ) {
  20238. _vector3.setFromMatrixPosition( object.matrixWorld )
  20239. .applyMatrix4( _projScreenMatrix );
  20240. }
  20241. var geometry = objects.update( object );
  20242. var material = object.material;
  20243. if ( Array.isArray( material ) ) {
  20244. var groups = geometry.groups;
  20245. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  20246. var group = groups[ i ];
  20247. var groupMaterial = material[ group.materialIndex ];
  20248. if ( groupMaterial && groupMaterial.visible ) {
  20249. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  20250. }
  20251. }
  20252. } else if ( material.visible ) {
  20253. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  20254. }
  20255. }
  20256. }
  20257. }
  20258. var children = object.children;
  20259. for ( var i = 0, l = children.length; i < l; i ++ ) {
  20260. projectObject( children[ i ], camera, groupOrder, sortObjects );
  20261. }
  20262. }
  20263. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  20264. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  20265. var renderItem = renderList[ i ];
  20266. var object = renderItem.object;
  20267. var geometry = renderItem.geometry;
  20268. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  20269. var group = renderItem.group;
  20270. if ( camera.isArrayCamera ) {
  20271. _currentArrayCamera = camera;
  20272. if ( capabilities.multiview ) {
  20273. renderObject( object, scene, camera, geometry, material, group );
  20274. } else {
  20275. var cameras = camera.cameras;
  20276. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  20277. var camera2 = cameras[ j ];
  20278. if ( object.layers.test( camera2.layers ) ) {
  20279. state.viewport( _currentViewport.copy( camera2.viewport ) );
  20280. currentRenderState.setupLights( camera2 );
  20281. renderObject( object, scene, camera2, geometry, material, group );
  20282. }
  20283. }
  20284. }
  20285. } else {
  20286. _currentArrayCamera = null;
  20287. renderObject( object, scene, camera, geometry, material, group );
  20288. }
  20289. }
  20290. }
  20291. function renderObject( object, scene, camera, geometry, material, group ) {
  20292. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  20293. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  20294. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  20295. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  20296. if ( object.isImmediateRenderObject ) {
  20297. state.setMaterial( material );
  20298. var program = setProgram( camera, scene.fog, material, object );
  20299. _currentGeometryProgram.geometry = null;
  20300. _currentGeometryProgram.program = null;
  20301. _currentGeometryProgram.wireframe = false;
  20302. renderObjectImmediate( object, program );
  20303. } else {
  20304. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  20305. }
  20306. object.onAfterRender( _this, scene, camera, geometry, material, group );
  20307. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  20308. }
  20309. function initMaterial( material, fog, object ) {
  20310. var materialProperties = properties.get( material );
  20311. var lights = currentRenderState.state.lights;
  20312. var shadowsArray = currentRenderState.state.shadowsArray;
  20313. var lightsStateVersion = lights.state.version;
  20314. var parameters = programCache.getParameters(
  20315. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  20316. var code = programCache.getProgramCode( material, parameters );
  20317. var program = materialProperties.program;
  20318. var programChange = true;
  20319. if ( program === undefined ) {
  20320. // new material
  20321. material.addEventListener( 'dispose', onMaterialDispose );
  20322. } else if ( program.code !== code ) {
  20323. // changed glsl or parameters
  20324. releaseMaterialProgramReference( material );
  20325. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  20326. materialProperties.lightsStateVersion = lightsStateVersion;
  20327. programChange = false;
  20328. } else if ( parameters.shaderID !== undefined ) {
  20329. // same glsl and uniform list
  20330. return;
  20331. } else {
  20332. // only rebuild uniform list
  20333. programChange = false;
  20334. }
  20335. if ( programChange ) {
  20336. if ( parameters.shaderID ) {
  20337. var shader = ShaderLib[ parameters.shaderID ];
  20338. materialProperties.shader = {
  20339. name: material.type,
  20340. uniforms: cloneUniforms( shader.uniforms ),
  20341. vertexShader: shader.vertexShader,
  20342. fragmentShader: shader.fragmentShader
  20343. };
  20344. } else {
  20345. materialProperties.shader = {
  20346. name: material.type,
  20347. uniforms: material.uniforms,
  20348. vertexShader: material.vertexShader,
  20349. fragmentShader: material.fragmentShader
  20350. };
  20351. }
  20352. material.onBeforeCompile( materialProperties.shader, _this );
  20353. // Computing code again as onBeforeCompile may have changed the shaders
  20354. code = programCache.getProgramCode( material, parameters );
  20355. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  20356. materialProperties.program = program;
  20357. material.program = program;
  20358. }
  20359. var programAttributes = program.getAttributes();
  20360. if ( material.morphTargets ) {
  20361. material.numSupportedMorphTargets = 0;
  20362. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  20363. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  20364. material.numSupportedMorphTargets ++;
  20365. }
  20366. }
  20367. }
  20368. if ( material.morphNormals ) {
  20369. material.numSupportedMorphNormals = 0;
  20370. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  20371. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  20372. material.numSupportedMorphNormals ++;
  20373. }
  20374. }
  20375. }
  20376. var uniforms = materialProperties.shader.uniforms;
  20377. if ( ! material.isShaderMaterial &&
  20378. ! material.isRawShaderMaterial ||
  20379. material.clipping === true ) {
  20380. materialProperties.numClippingPlanes = _clipping.numPlanes;
  20381. materialProperties.numIntersection = _clipping.numIntersection;
  20382. uniforms.clippingPlanes = _clipping.uniform;
  20383. }
  20384. materialProperties.fog = fog;
  20385. // store the light setup it was created for
  20386. materialProperties.lightsStateVersion = lightsStateVersion;
  20387. if ( material.lights ) {
  20388. // wire up the material to this renderer's lighting state
  20389. uniforms.ambientLightColor.value = lights.state.ambient;
  20390. uniforms.lightProbe.value = lights.state.probe;
  20391. uniforms.directionalLights.value = lights.state.directional;
  20392. uniforms.spotLights.value = lights.state.spot;
  20393. uniforms.rectAreaLights.value = lights.state.rectArea;
  20394. uniforms.pointLights.value = lights.state.point;
  20395. uniforms.hemisphereLights.value = lights.state.hemi;
  20396. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  20397. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  20398. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  20399. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  20400. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  20401. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  20402. // TODO (abelnation): add area lights shadow info to uniforms
  20403. }
  20404. var progUniforms = materialProperties.program.getUniforms(),
  20405. uniformsList =
  20406. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  20407. materialProperties.uniformsList = uniformsList;
  20408. }
  20409. function setProgram( camera, fog, material, object ) {
  20410. textures.resetTextureUnits();
  20411. var materialProperties = properties.get( material );
  20412. var lights = currentRenderState.state.lights;
  20413. if ( _clippingEnabled ) {
  20414. if ( _localClippingEnabled || camera !== _currentCamera ) {
  20415. var useCache =
  20416. camera === _currentCamera &&
  20417. material.id === _currentMaterialId;
  20418. // we might want to call this function with some ClippingGroup
  20419. // object instead of the material, once it becomes feasible
  20420. // (#8465, #8379)
  20421. _clipping.setState(
  20422. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  20423. camera, materialProperties, useCache );
  20424. }
  20425. }
  20426. if ( material.needsUpdate === false ) {
  20427. if ( materialProperties.program === undefined ) {
  20428. material.needsUpdate = true;
  20429. } else if ( material.fog && materialProperties.fog !== fog ) {
  20430. material.needsUpdate = true;
  20431. } else if ( material.lights && materialProperties.lightsStateVersion !== lights.state.version ) {
  20432. material.needsUpdate = true;
  20433. } else if ( materialProperties.numClippingPlanes !== undefined &&
  20434. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  20435. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  20436. material.needsUpdate = true;
  20437. }
  20438. }
  20439. if ( material.needsUpdate ) {
  20440. initMaterial( material, fog, object );
  20441. material.needsUpdate = false;
  20442. }
  20443. var refreshProgram = false;
  20444. var refreshMaterial = false;
  20445. var refreshLights = false;
  20446. var program = materialProperties.program,
  20447. p_uniforms = program.getUniforms(),
  20448. m_uniforms = materialProperties.shader.uniforms;
  20449. if ( state.useProgram( program.program ) ) {
  20450. refreshProgram = true;
  20451. refreshMaterial = true;
  20452. refreshLights = true;
  20453. }
  20454. if ( material.id !== _currentMaterialId ) {
  20455. _currentMaterialId = material.id;
  20456. refreshMaterial = true;
  20457. }
  20458. if ( refreshProgram || _currentCamera !== camera ) {
  20459. if ( program.numMultiviewViews > 0 ) {
  20460. multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms );
  20461. } else {
  20462. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  20463. }
  20464. if ( capabilities.logarithmicDepthBuffer ) {
  20465. p_uniforms.setValue( _gl, 'logDepthBufFC',
  20466. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  20467. }
  20468. if ( _currentCamera !== camera ) {
  20469. _currentCamera = camera;
  20470. // lighting uniforms depend on the camera so enforce an update
  20471. // now, in case this material supports lights - or later, when
  20472. // the next material that does gets activated:
  20473. refreshMaterial = true; // set to true on material change
  20474. refreshLights = true; // remains set until update done
  20475. }
  20476. // load material specific uniforms
  20477. // (shader material also gets them for the sake of genericity)
  20478. if ( material.isShaderMaterial ||
  20479. material.isMeshPhongMaterial ||
  20480. material.isMeshStandardMaterial ||
  20481. material.envMap ) {
  20482. var uCamPos = p_uniforms.map.cameraPosition;
  20483. if ( uCamPos !== undefined ) {
  20484. uCamPos.setValue( _gl,
  20485. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  20486. }
  20487. }
  20488. if ( material.isMeshPhongMaterial ||
  20489. material.isMeshLambertMaterial ||
  20490. material.isMeshBasicMaterial ||
  20491. material.isMeshStandardMaterial ||
  20492. material.isShaderMaterial ||
  20493. material.skinning ) {
  20494. if ( program.numMultiviewViews > 0 ) {
  20495. multiview.updateCameraViewMatricesUniform( camera, p_uniforms );
  20496. } else {
  20497. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  20498. }
  20499. }
  20500. }
  20501. // skinning uniforms must be set even if material didn't change
  20502. // auto-setting of texture unit for bone texture must go before other textures
  20503. // not sure why, but otherwise weird things happen
  20504. if ( material.skinning ) {
  20505. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  20506. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  20507. var skeleton = object.skeleton;
  20508. if ( skeleton ) {
  20509. var bones = skeleton.bones;
  20510. if ( capabilities.floatVertexTextures ) {
  20511. if ( skeleton.boneTexture === undefined ) {
  20512. // layout (1 matrix = 4 pixels)
  20513. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20514. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  20515. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  20516. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  20517. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  20518. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  20519. size = _Math.ceilPowerOfTwo( size );
  20520. size = Math.max( size, 4 );
  20521. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20522. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  20523. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  20524. skeleton.boneMatrices = boneMatrices;
  20525. skeleton.boneTexture = boneTexture;
  20526. skeleton.boneTextureSize = size;
  20527. }
  20528. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  20529. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  20530. } else {
  20531. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  20532. }
  20533. }
  20534. }
  20535. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  20536. materialProperties.receiveShadow = object.receiveShadow;
  20537. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  20538. }
  20539. if ( refreshMaterial ) {
  20540. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  20541. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  20542. if ( material.lights ) {
  20543. // the current material requires lighting info
  20544. // note: all lighting uniforms are always set correctly
  20545. // they simply reference the renderer's state for their
  20546. // values
  20547. //
  20548. // use the current material's .needsUpdate flags to set
  20549. // the GL state when required
  20550. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  20551. }
  20552. // refresh uniforms common to several materials
  20553. if ( fog && material.fog ) {
  20554. refreshUniformsFog( m_uniforms, fog );
  20555. }
  20556. if ( material.isMeshBasicMaterial ) {
  20557. refreshUniformsCommon( m_uniforms, material );
  20558. } else if ( material.isMeshLambertMaterial ) {
  20559. refreshUniformsCommon( m_uniforms, material );
  20560. refreshUniformsLambert( m_uniforms, material );
  20561. } else if ( material.isMeshPhongMaterial ) {
  20562. refreshUniformsCommon( m_uniforms, material );
  20563. if ( material.isMeshToonMaterial ) {
  20564. refreshUniformsToon( m_uniforms, material );
  20565. } else {
  20566. refreshUniformsPhong( m_uniforms, material );
  20567. }
  20568. } else if ( material.isMeshStandardMaterial ) {
  20569. refreshUniformsCommon( m_uniforms, material );
  20570. if ( material.isMeshPhysicalMaterial ) {
  20571. refreshUniformsPhysical( m_uniforms, material );
  20572. } else {
  20573. refreshUniformsStandard( m_uniforms, material );
  20574. }
  20575. } else if ( material.isMeshMatcapMaterial ) {
  20576. refreshUniformsCommon( m_uniforms, material );
  20577. refreshUniformsMatcap( m_uniforms, material );
  20578. } else if ( material.isMeshDepthMaterial ) {
  20579. refreshUniformsCommon( m_uniforms, material );
  20580. refreshUniformsDepth( m_uniforms, material );
  20581. } else if ( material.isMeshDistanceMaterial ) {
  20582. refreshUniformsCommon( m_uniforms, material );
  20583. refreshUniformsDistance( m_uniforms, material );
  20584. } else if ( material.isMeshNormalMaterial ) {
  20585. refreshUniformsCommon( m_uniforms, material );
  20586. refreshUniformsNormal( m_uniforms, material );
  20587. } else if ( material.isLineBasicMaterial ) {
  20588. refreshUniformsLine( m_uniforms, material );
  20589. if ( material.isLineDashedMaterial ) {
  20590. refreshUniformsDash( m_uniforms, material );
  20591. }
  20592. } else if ( material.isPointsMaterial ) {
  20593. refreshUniformsPoints( m_uniforms, material );
  20594. } else if ( material.isSpriteMaterial ) {
  20595. refreshUniformsSprites( m_uniforms, material );
  20596. } else if ( material.isShadowMaterial ) {
  20597. m_uniforms.color.value.copy( material.color );
  20598. m_uniforms.opacity.value = material.opacity;
  20599. }
  20600. // RectAreaLight Texture
  20601. // TODO (mrdoob): Find a nicer implementation
  20602. if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; }
  20603. if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; }
  20604. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  20605. }
  20606. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  20607. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  20608. material.uniformsNeedUpdate = false;
  20609. }
  20610. if ( material.isSpriteMaterial ) {
  20611. p_uniforms.setValue( _gl, 'center', object.center );
  20612. }
  20613. // common matrices
  20614. if ( program.numMultiviewViews > 0 ) {
  20615. multiview.updateObjectMatricesUniforms( object, camera, p_uniforms );
  20616. } else {
  20617. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  20618. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  20619. }
  20620. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  20621. return program;
  20622. }
  20623. // Uniforms (refresh uniforms objects)
  20624. function refreshUniformsCommon( uniforms, material ) {
  20625. uniforms.opacity.value = material.opacity;
  20626. if ( material.color ) {
  20627. uniforms.diffuse.value.copy( material.color );
  20628. }
  20629. if ( material.emissive ) {
  20630. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  20631. }
  20632. if ( material.map ) {
  20633. uniforms.map.value = material.map;
  20634. }
  20635. if ( material.alphaMap ) {
  20636. uniforms.alphaMap.value = material.alphaMap;
  20637. }
  20638. if ( material.specularMap ) {
  20639. uniforms.specularMap.value = material.specularMap;
  20640. }
  20641. if ( material.envMap ) {
  20642. uniforms.envMap.value = material.envMap;
  20643. // don't flip CubeTexture envMaps, flip everything else:
  20644. // WebGLRenderTargetCube will be flipped for backwards compatibility
  20645. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  20646. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  20647. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  20648. uniforms.reflectivity.value = material.reflectivity;
  20649. uniforms.refractionRatio.value = material.refractionRatio;
  20650. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  20651. }
  20652. if ( material.lightMap ) {
  20653. uniforms.lightMap.value = material.lightMap;
  20654. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  20655. }
  20656. if ( material.aoMap ) {
  20657. uniforms.aoMap.value = material.aoMap;
  20658. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  20659. }
  20660. // uv repeat and offset setting priorities
  20661. // 1. color map
  20662. // 2. specular map
  20663. // 3. normal map
  20664. // 4. bump map
  20665. // 5. alpha map
  20666. // 6. emissive map
  20667. var uvScaleMap;
  20668. if ( material.map ) {
  20669. uvScaleMap = material.map;
  20670. } else if ( material.specularMap ) {
  20671. uvScaleMap = material.specularMap;
  20672. } else if ( material.displacementMap ) {
  20673. uvScaleMap = material.displacementMap;
  20674. } else if ( material.normalMap ) {
  20675. uvScaleMap = material.normalMap;
  20676. } else if ( material.bumpMap ) {
  20677. uvScaleMap = material.bumpMap;
  20678. } else if ( material.roughnessMap ) {
  20679. uvScaleMap = material.roughnessMap;
  20680. } else if ( material.metalnessMap ) {
  20681. uvScaleMap = material.metalnessMap;
  20682. } else if ( material.alphaMap ) {
  20683. uvScaleMap = material.alphaMap;
  20684. } else if ( material.emissiveMap ) {
  20685. uvScaleMap = material.emissiveMap;
  20686. }
  20687. if ( uvScaleMap !== undefined ) {
  20688. // backwards compatibility
  20689. if ( uvScaleMap.isWebGLRenderTarget ) {
  20690. uvScaleMap = uvScaleMap.texture;
  20691. }
  20692. if ( uvScaleMap.matrixAutoUpdate === true ) {
  20693. uvScaleMap.updateMatrix();
  20694. }
  20695. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  20696. }
  20697. }
  20698. function refreshUniformsLine( uniforms, material ) {
  20699. uniforms.diffuse.value.copy( material.color );
  20700. uniforms.opacity.value = material.opacity;
  20701. }
  20702. function refreshUniformsDash( uniforms, material ) {
  20703. uniforms.dashSize.value = material.dashSize;
  20704. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20705. uniforms.scale.value = material.scale;
  20706. }
  20707. function refreshUniformsPoints( uniforms, material ) {
  20708. uniforms.diffuse.value.copy( material.color );
  20709. uniforms.opacity.value = material.opacity;
  20710. uniforms.size.value = material.size * _pixelRatio;
  20711. uniforms.scale.value = _height * 0.5;
  20712. uniforms.map.value = material.map;
  20713. if ( material.map !== null ) {
  20714. if ( material.map.matrixAutoUpdate === true ) {
  20715. material.map.updateMatrix();
  20716. }
  20717. uniforms.uvTransform.value.copy( material.map.matrix );
  20718. }
  20719. }
  20720. function refreshUniformsSprites( uniforms, material ) {
  20721. uniforms.diffuse.value.copy( material.color );
  20722. uniforms.opacity.value = material.opacity;
  20723. uniforms.rotation.value = material.rotation;
  20724. uniforms.map.value = material.map;
  20725. if ( material.map !== null ) {
  20726. if ( material.map.matrixAutoUpdate === true ) {
  20727. material.map.updateMatrix();
  20728. }
  20729. uniforms.uvTransform.value.copy( material.map.matrix );
  20730. }
  20731. }
  20732. function refreshUniformsFog( uniforms, fog ) {
  20733. uniforms.fogColor.value.copy( fog.color );
  20734. if ( fog.isFog ) {
  20735. uniforms.fogNear.value = fog.near;
  20736. uniforms.fogFar.value = fog.far;
  20737. } else if ( fog.isFogExp2 ) {
  20738. uniforms.fogDensity.value = fog.density;
  20739. }
  20740. }
  20741. function refreshUniformsLambert( uniforms, material ) {
  20742. if ( material.emissiveMap ) {
  20743. uniforms.emissiveMap.value = material.emissiveMap;
  20744. }
  20745. }
  20746. function refreshUniformsPhong( uniforms, material ) {
  20747. uniforms.specular.value.copy( material.specular );
  20748. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  20749. if ( material.emissiveMap ) {
  20750. uniforms.emissiveMap.value = material.emissiveMap;
  20751. }
  20752. if ( material.bumpMap ) {
  20753. uniforms.bumpMap.value = material.bumpMap;
  20754. uniforms.bumpScale.value = material.bumpScale;
  20755. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20756. }
  20757. if ( material.normalMap ) {
  20758. uniforms.normalMap.value = material.normalMap;
  20759. uniforms.normalScale.value.copy( material.normalScale );
  20760. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20761. }
  20762. if ( material.displacementMap ) {
  20763. uniforms.displacementMap.value = material.displacementMap;
  20764. uniforms.displacementScale.value = material.displacementScale;
  20765. uniforms.displacementBias.value = material.displacementBias;
  20766. }
  20767. }
  20768. function refreshUniformsToon( uniforms, material ) {
  20769. refreshUniformsPhong( uniforms, material );
  20770. if ( material.gradientMap ) {
  20771. uniforms.gradientMap.value = material.gradientMap;
  20772. }
  20773. }
  20774. function refreshUniformsStandard( uniforms, material ) {
  20775. uniforms.roughness.value = material.roughness;
  20776. uniforms.metalness.value = material.metalness;
  20777. if ( material.roughnessMap ) {
  20778. uniforms.roughnessMap.value = material.roughnessMap;
  20779. }
  20780. if ( material.metalnessMap ) {
  20781. uniforms.metalnessMap.value = material.metalnessMap;
  20782. }
  20783. if ( material.emissiveMap ) {
  20784. uniforms.emissiveMap.value = material.emissiveMap;
  20785. }
  20786. if ( material.bumpMap ) {
  20787. uniforms.bumpMap.value = material.bumpMap;
  20788. uniforms.bumpScale.value = material.bumpScale;
  20789. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20790. }
  20791. if ( material.normalMap ) {
  20792. uniforms.normalMap.value = material.normalMap;
  20793. uniforms.normalScale.value.copy( material.normalScale );
  20794. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20795. }
  20796. if ( material.displacementMap ) {
  20797. uniforms.displacementMap.value = material.displacementMap;
  20798. uniforms.displacementScale.value = material.displacementScale;
  20799. uniforms.displacementBias.value = material.displacementBias;
  20800. }
  20801. if ( material.envMap ) {
  20802. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20803. uniforms.envMapIntensity.value = material.envMapIntensity;
  20804. }
  20805. }
  20806. function refreshUniformsPhysical( uniforms, material ) {
  20807. refreshUniformsStandard( uniforms, material );
  20808. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  20809. uniforms.clearcoat.value = material.clearcoat;
  20810. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20811. if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); }
  20812. if ( material.clearcoatNormalMap ) {
  20813. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  20814. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20815. if ( material.side === BackSide ) {
  20816. uniforms.clearcoatNormalScale.value.negate();
  20817. }
  20818. }
  20819. uniforms.transparency.value = material.transparency;
  20820. }
  20821. function refreshUniformsMatcap( uniforms, material ) {
  20822. if ( material.matcap ) {
  20823. uniforms.matcap.value = material.matcap;
  20824. }
  20825. if ( material.bumpMap ) {
  20826. uniforms.bumpMap.value = material.bumpMap;
  20827. uniforms.bumpScale.value = material.bumpScale;
  20828. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20829. }
  20830. if ( material.normalMap ) {
  20831. uniforms.normalMap.value = material.normalMap;
  20832. uniforms.normalScale.value.copy( material.normalScale );
  20833. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20834. }
  20835. if ( material.displacementMap ) {
  20836. uniforms.displacementMap.value = material.displacementMap;
  20837. uniforms.displacementScale.value = material.displacementScale;
  20838. uniforms.displacementBias.value = material.displacementBias;
  20839. }
  20840. }
  20841. function refreshUniformsDepth( uniforms, material ) {
  20842. if ( material.displacementMap ) {
  20843. uniforms.displacementMap.value = material.displacementMap;
  20844. uniforms.displacementScale.value = material.displacementScale;
  20845. uniforms.displacementBias.value = material.displacementBias;
  20846. }
  20847. }
  20848. function refreshUniformsDistance( uniforms, material ) {
  20849. if ( material.displacementMap ) {
  20850. uniforms.displacementMap.value = material.displacementMap;
  20851. uniforms.displacementScale.value = material.displacementScale;
  20852. uniforms.displacementBias.value = material.displacementBias;
  20853. }
  20854. uniforms.referencePosition.value.copy( material.referencePosition );
  20855. uniforms.nearDistance.value = material.nearDistance;
  20856. uniforms.farDistance.value = material.farDistance;
  20857. }
  20858. function refreshUniformsNormal( uniforms, material ) {
  20859. if ( material.bumpMap ) {
  20860. uniforms.bumpMap.value = material.bumpMap;
  20861. uniforms.bumpScale.value = material.bumpScale;
  20862. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  20863. }
  20864. if ( material.normalMap ) {
  20865. uniforms.normalMap.value = material.normalMap;
  20866. uniforms.normalScale.value.copy( material.normalScale );
  20867. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  20868. }
  20869. if ( material.displacementMap ) {
  20870. uniforms.displacementMap.value = material.displacementMap;
  20871. uniforms.displacementScale.value = material.displacementScale;
  20872. uniforms.displacementBias.value = material.displacementBias;
  20873. }
  20874. }
  20875. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  20876. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  20877. uniforms.ambientLightColor.needsUpdate = value;
  20878. uniforms.lightProbe.needsUpdate = value;
  20879. uniforms.directionalLights.needsUpdate = value;
  20880. uniforms.pointLights.needsUpdate = value;
  20881. uniforms.spotLights.needsUpdate = value;
  20882. uniforms.rectAreaLights.needsUpdate = value;
  20883. uniforms.hemisphereLights.needsUpdate = value;
  20884. }
  20885. // this.setTexture2D = setTexture2D;
  20886. this.setTexture2D = ( function () {
  20887. var warned = false;
  20888. // backwards compatibility: peel texture.texture
  20889. return function setTexture2D( texture, slot ) {
  20890. if ( texture && texture.isWebGLRenderTarget ) {
  20891. if ( ! warned ) {
  20892. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  20893. warned = true;
  20894. }
  20895. texture = texture.texture;
  20896. }
  20897. textures.setTexture2D( texture, slot );
  20898. };
  20899. }() );
  20900. //
  20901. this.setFramebuffer = function ( value ) {
  20902. if ( _framebuffer !== value ) { _gl.bindFramebuffer( 36160, value ); }
  20903. _framebuffer = value;
  20904. };
  20905. this.getActiveCubeFace = function () {
  20906. return _currentActiveCubeFace;
  20907. };
  20908. this.getActiveMipmapLevel = function () {
  20909. return _currentActiveMipmapLevel;
  20910. };
  20911. this.getRenderTarget = function () {
  20912. return _currentRenderTarget;
  20913. };
  20914. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
  20915. _currentRenderTarget = renderTarget;
  20916. _currentActiveCubeFace = activeCubeFace;
  20917. _currentActiveMipmapLevel = activeMipmapLevel;
  20918. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  20919. textures.setupRenderTarget( renderTarget );
  20920. }
  20921. var framebuffer = _framebuffer;
  20922. var isCube = false;
  20923. if ( renderTarget ) {
  20924. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  20925. if ( renderTarget.isWebGLRenderTargetCube ) {
  20926. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  20927. isCube = true;
  20928. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  20929. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  20930. } else {
  20931. framebuffer = __webglFramebuffer;
  20932. }
  20933. _currentViewport.copy( renderTarget.viewport );
  20934. _currentScissor.copy( renderTarget.scissor );
  20935. _currentScissorTest = renderTarget.scissorTest;
  20936. } else {
  20937. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  20938. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  20939. _currentScissorTest = _scissorTest;
  20940. }
  20941. if ( _currentFramebuffer !== framebuffer ) {
  20942. _gl.bindFramebuffer( 36160, framebuffer );
  20943. _currentFramebuffer = framebuffer;
  20944. }
  20945. state.viewport( _currentViewport );
  20946. state.scissor( _currentScissor );
  20947. state.setScissorTest( _currentScissorTest );
  20948. if ( isCube ) {
  20949. var textureProperties = properties.get( renderTarget.texture );
  20950. _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
  20951. }
  20952. };
  20953. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  20954. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  20955. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  20956. return;
  20957. }
  20958. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  20959. if ( renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined ) {
  20960. framebuffer = framebuffer[ activeCubeFaceIndex ];
  20961. }
  20962. if ( framebuffer ) {
  20963. var restore = false;
  20964. if ( framebuffer !== _currentFramebuffer ) {
  20965. _gl.bindFramebuffer( 36160, framebuffer );
  20966. restore = true;
  20967. }
  20968. try {
  20969. var texture = renderTarget.texture;
  20970. var textureFormat = texture.format;
  20971. var textureType = texture.type;
  20972. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  20973. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  20974. return;
  20975. }
  20976. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  20977. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  20978. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  20979. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  20980. return;
  20981. }
  20982. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  20983. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  20984. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  20985. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  20986. }
  20987. } else {
  20988. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  20989. }
  20990. } finally {
  20991. if ( restore ) {
  20992. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  20993. }
  20994. }
  20995. }
  20996. };
  20997. this.copyFramebufferToTexture = function ( position, texture, level ) {
  20998. var width = texture.image.width;
  20999. var height = texture.image.height;
  21000. var glFormat = utils.convert( texture.format );
  21001. textures.setTexture2D( texture, 0 );
  21002. _gl.copyTexImage2D( 3553, level || 0, glFormat, position.x, position.y, width, height, 0 );
  21003. };
  21004. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  21005. var width = srcTexture.image.width;
  21006. var height = srcTexture.image.height;
  21007. var glFormat = utils.convert( dstTexture.format );
  21008. var glType = utils.convert( dstTexture.type );
  21009. textures.setTexture2D( dstTexture, 0 );
  21010. if ( srcTexture.isDataTexture ) {
  21011. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  21012. } else {
  21013. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  21014. }
  21015. };
  21016. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  21017. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  21018. }
  21019. }
  21020. /**
  21021. * @author mrdoob / http://mrdoob.com/
  21022. * @author alteredq / http://alteredqualia.com/
  21023. */
  21024. function FogExp2( color, density ) {
  21025. this.name = '';
  21026. this.color = new Color( color );
  21027. this.density = ( density !== undefined ) ? density : 0.00025;
  21028. }
  21029. Object.assign( FogExp2.prototype, {
  21030. isFogExp2: true,
  21031. clone: function () {
  21032. return new FogExp2( this.color, this.density );
  21033. },
  21034. toJSON: function ( /* meta */ ) {
  21035. return {
  21036. type: 'FogExp2',
  21037. color: this.color.getHex(),
  21038. density: this.density
  21039. };
  21040. }
  21041. } );
  21042. /**
  21043. * @author mrdoob / http://mrdoob.com/
  21044. * @author alteredq / http://alteredqualia.com/
  21045. */
  21046. function Fog( color, near, far ) {
  21047. this.name = '';
  21048. this.color = new Color( color );
  21049. this.near = ( near !== undefined ) ? near : 1;
  21050. this.far = ( far !== undefined ) ? far : 1000;
  21051. }
  21052. Object.assign( Fog.prototype, {
  21053. isFog: true,
  21054. clone: function () {
  21055. return new Fog( this.color, this.near, this.far );
  21056. },
  21057. toJSON: function ( /* meta */ ) {
  21058. return {
  21059. type: 'Fog',
  21060. color: this.color.getHex(),
  21061. near: this.near,
  21062. far: this.far
  21063. };
  21064. }
  21065. } );
  21066. /**
  21067. * @author benaadams / https://twitter.com/ben_a_adams
  21068. */
  21069. function InterleavedBuffer( array, stride ) {
  21070. this.array = array;
  21071. this.stride = stride;
  21072. this.count = array !== undefined ? array.length / stride : 0;
  21073. this.dynamic = false;
  21074. this.updateRange = { offset: 0, count: - 1 };
  21075. this.version = 0;
  21076. }
  21077. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  21078. set: function ( value ) {
  21079. if ( value === true ) { this.version ++; }
  21080. }
  21081. } );
  21082. Object.assign( InterleavedBuffer.prototype, {
  21083. isInterleavedBuffer: true,
  21084. onUploadCallback: function () {},
  21085. setDynamic: function ( value ) {
  21086. this.dynamic = value;
  21087. return this;
  21088. },
  21089. copy: function ( source ) {
  21090. this.array = new source.array.constructor( source.array );
  21091. this.count = source.count;
  21092. this.stride = source.stride;
  21093. this.dynamic = source.dynamic;
  21094. return this;
  21095. },
  21096. copyAt: function ( index1, attribute, index2 ) {
  21097. index1 *= this.stride;
  21098. index2 *= attribute.stride;
  21099. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21100. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21101. }
  21102. return this;
  21103. },
  21104. set: function ( value, offset ) {
  21105. if ( offset === undefined ) { offset = 0; }
  21106. this.array.set( value, offset );
  21107. return this;
  21108. },
  21109. clone: function () {
  21110. return new this.constructor().copy( this );
  21111. },
  21112. onUpload: function ( callback ) {
  21113. this.onUploadCallback = callback;
  21114. return this;
  21115. }
  21116. } );
  21117. /**
  21118. * @author benaadams / https://twitter.com/ben_a_adams
  21119. */
  21120. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21121. this.data = interleavedBuffer;
  21122. this.itemSize = itemSize;
  21123. this.offset = offset;
  21124. this.normalized = normalized === true;
  21125. }
  21126. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  21127. count: {
  21128. get: function () {
  21129. return this.data.count;
  21130. }
  21131. },
  21132. array: {
  21133. get: function () {
  21134. return this.data.array;
  21135. }
  21136. }
  21137. } );
  21138. Object.assign( InterleavedBufferAttribute.prototype, {
  21139. isInterleavedBufferAttribute: true,
  21140. setX: function ( index, x ) {
  21141. this.data.array[ index * this.data.stride + this.offset ] = x;
  21142. return this;
  21143. },
  21144. setY: function ( index, y ) {
  21145. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21146. return this;
  21147. },
  21148. setZ: function ( index, z ) {
  21149. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21150. return this;
  21151. },
  21152. setW: function ( index, w ) {
  21153. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21154. return this;
  21155. },
  21156. getX: function ( index ) {
  21157. return this.data.array[ index * this.data.stride + this.offset ];
  21158. },
  21159. getY: function ( index ) {
  21160. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21161. },
  21162. getZ: function ( index ) {
  21163. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21164. },
  21165. getW: function ( index ) {
  21166. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21167. },
  21168. setXY: function ( index, x, y ) {
  21169. index = index * this.data.stride + this.offset;
  21170. this.data.array[ index + 0 ] = x;
  21171. this.data.array[ index + 1 ] = y;
  21172. return this;
  21173. },
  21174. setXYZ: function ( index, x, y, z ) {
  21175. index = index * this.data.stride + this.offset;
  21176. this.data.array[ index + 0 ] = x;
  21177. this.data.array[ index + 1 ] = y;
  21178. this.data.array[ index + 2 ] = z;
  21179. return this;
  21180. },
  21181. setXYZW: function ( index, x, y, z, w ) {
  21182. index = index * this.data.stride + this.offset;
  21183. this.data.array[ index + 0 ] = x;
  21184. this.data.array[ index + 1 ] = y;
  21185. this.data.array[ index + 2 ] = z;
  21186. this.data.array[ index + 3 ] = w;
  21187. return this;
  21188. }
  21189. } );
  21190. /**
  21191. * @author alteredq / http://alteredqualia.com/
  21192. *
  21193. * parameters = {
  21194. * color: <hex>,
  21195. * map: new THREE.Texture( <Image> ),
  21196. * rotation: <float>,
  21197. * sizeAttenuation: <bool>
  21198. * }
  21199. */
  21200. function SpriteMaterial( parameters ) {
  21201. Material.call( this );
  21202. this.type = 'SpriteMaterial';
  21203. this.color = new Color( 0xffffff );
  21204. this.map = null;
  21205. this.rotation = 0;
  21206. this.sizeAttenuation = true;
  21207. this.lights = false;
  21208. this.transparent = true;
  21209. this.setValues( parameters );
  21210. }
  21211. SpriteMaterial.prototype = Object.create( Material.prototype );
  21212. SpriteMaterial.prototype.constructor = SpriteMaterial;
  21213. SpriteMaterial.prototype.isSpriteMaterial = true;
  21214. SpriteMaterial.prototype.copy = function ( source ) {
  21215. Material.prototype.copy.call( this, source );
  21216. this.color.copy( source.color );
  21217. this.map = source.map;
  21218. this.rotation = source.rotation;
  21219. this.sizeAttenuation = source.sizeAttenuation;
  21220. return this;
  21221. };
  21222. /**
  21223. * @author mikael emtinger / http://gomo.se/
  21224. * @author alteredq / http://alteredqualia.com/
  21225. */
  21226. var _geometry;
  21227. var _intersectPoint = new Vector3();
  21228. var _worldScale = new Vector3();
  21229. var _mvPosition = new Vector3();
  21230. var _alignedPosition = new Vector2();
  21231. var _rotatedPosition = new Vector2();
  21232. var _viewWorldMatrix = new Matrix4();
  21233. var _vA$1 = new Vector3();
  21234. var _vB$1 = new Vector3();
  21235. var _vC$1 = new Vector3();
  21236. var _uvA$1 = new Vector2();
  21237. var _uvB$1 = new Vector2();
  21238. var _uvC$1 = new Vector2();
  21239. function Sprite( material ) {
  21240. Object3D.call( this );
  21241. this.type = 'Sprite';
  21242. if ( _geometry === undefined ) {
  21243. _geometry = new BufferGeometry();
  21244. var float32Array = new Float32Array( [
  21245. - 0.5, - 0.5, 0, 0, 0,
  21246. 0.5, - 0.5, 0, 1, 0,
  21247. 0.5, 0.5, 0, 1, 1,
  21248. - 0.5, 0.5, 0, 0, 1
  21249. ] );
  21250. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  21251. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  21252. _geometry.addAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  21253. _geometry.addAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  21254. }
  21255. this.geometry = _geometry;
  21256. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  21257. this.center = new Vector2( 0.5, 0.5 );
  21258. }
  21259. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21260. constructor: Sprite,
  21261. isSprite: true,
  21262. raycast: function ( raycaster, intersects ) {
  21263. if ( raycaster.camera === null ) {
  21264. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  21265. }
  21266. _worldScale.setFromMatrixScale( this.matrixWorld );
  21267. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  21268. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  21269. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  21270. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  21271. _worldScale.multiplyScalar( - _mvPosition.z );
  21272. }
  21273. var rotation = this.material.rotation;
  21274. var sin, cos;
  21275. if ( rotation !== 0 ) {
  21276. cos = Math.cos( rotation );
  21277. sin = Math.sin( rotation );
  21278. }
  21279. var center = this.center;
  21280. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21281. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21282. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21283. _uvA$1.set( 0, 0 );
  21284. _uvB$1.set( 1, 0 );
  21285. _uvC$1.set( 1, 1 );
  21286. // check first triangle
  21287. var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  21288. if ( intersect === null ) {
  21289. // check second triangle
  21290. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21291. _uvB$1.set( 0, 1 );
  21292. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  21293. if ( intersect === null ) {
  21294. return;
  21295. }
  21296. }
  21297. var distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  21298. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  21299. intersects.push( {
  21300. distance: distance,
  21301. point: _intersectPoint.clone(),
  21302. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  21303. face: null,
  21304. object: this
  21305. } );
  21306. },
  21307. clone: function () {
  21308. return new this.constructor( this.material ).copy( this );
  21309. },
  21310. copy: function ( source ) {
  21311. Object3D.prototype.copy.call( this, source );
  21312. if ( source.center !== undefined ) { this.center.copy( source.center ); }
  21313. return this;
  21314. }
  21315. } );
  21316. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  21317. // compute position in camera space
  21318. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  21319. // to check if rotation is not zero
  21320. if ( sin !== undefined ) {
  21321. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  21322. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  21323. } else {
  21324. _rotatedPosition.copy( _alignedPosition );
  21325. }
  21326. vertexPosition.copy( mvPosition );
  21327. vertexPosition.x += _rotatedPosition.x;
  21328. vertexPosition.y += _rotatedPosition.y;
  21329. // transform to world space
  21330. vertexPosition.applyMatrix4( _viewWorldMatrix );
  21331. }
  21332. /**
  21333. * @author mikael emtinger / http://gomo.se/
  21334. * @author alteredq / http://alteredqualia.com/
  21335. * @author mrdoob / http://mrdoob.com/
  21336. */
  21337. var _v1$4 = new Vector3();
  21338. var _v2$2 = new Vector3();
  21339. function LOD() {
  21340. Object3D.call( this );
  21341. this.type = 'LOD';
  21342. Object.defineProperties( this, {
  21343. levels: {
  21344. enumerable: true,
  21345. value: []
  21346. }
  21347. } );
  21348. this.autoUpdate = true;
  21349. }
  21350. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21351. constructor: LOD,
  21352. isLOD: true,
  21353. copy: function ( source ) {
  21354. Object3D.prototype.copy.call( this, source, false );
  21355. var levels = source.levels;
  21356. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  21357. var level = levels[ i ];
  21358. this.addLevel( level.object.clone(), level.distance );
  21359. }
  21360. return this;
  21361. },
  21362. addLevel: function ( object, distance ) {
  21363. if ( distance === undefined ) { distance = 0; }
  21364. distance = Math.abs( distance );
  21365. var levels = this.levels;
  21366. for ( var l = 0; l < levels.length; l ++ ) {
  21367. if ( distance < levels[ l ].distance ) {
  21368. break;
  21369. }
  21370. }
  21371. levels.splice( l, 0, { distance: distance, object: object } );
  21372. this.add( object );
  21373. return this;
  21374. },
  21375. getObjectForDistance: function ( distance ) {
  21376. var levels = this.levels;
  21377. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  21378. if ( distance < levels[ i ].distance ) {
  21379. break;
  21380. }
  21381. }
  21382. return levels[ i - 1 ].object;
  21383. },
  21384. raycast: function ( raycaster, intersects ) {
  21385. _v1$4.setFromMatrixPosition( this.matrixWorld );
  21386. var distance = raycaster.ray.origin.distanceTo( _v1$4 );
  21387. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  21388. },
  21389. update: function ( camera ) {
  21390. var levels = this.levels;
  21391. if ( levels.length > 1 ) {
  21392. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  21393. _v2$2.setFromMatrixPosition( this.matrixWorld );
  21394. var distance = _v1$4.distanceTo( _v2$2 );
  21395. levels[ 0 ].object.visible = true;
  21396. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  21397. if ( distance >= levels[ i ].distance ) {
  21398. levels[ i - 1 ].object.visible = false;
  21399. levels[ i ].object.visible = true;
  21400. } else {
  21401. break;
  21402. }
  21403. }
  21404. for ( ; i < l; i ++ ) {
  21405. levels[ i ].object.visible = false;
  21406. }
  21407. }
  21408. },
  21409. toJSON: function ( meta ) {
  21410. var data = Object3D.prototype.toJSON.call( this, meta );
  21411. data.object.levels = [];
  21412. var levels = this.levels;
  21413. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  21414. var level = levels[ i ];
  21415. data.object.levels.push( {
  21416. object: level.object.uuid,
  21417. distance: level.distance
  21418. } );
  21419. }
  21420. return data;
  21421. }
  21422. } );
  21423. /**
  21424. * @author mikael emtinger / http://gomo.se/
  21425. * @author alteredq / http://alteredqualia.com/
  21426. * @author ikerr / http://verold.com
  21427. */
  21428. function SkinnedMesh( geometry, material ) {
  21429. if ( geometry && geometry.isGeometry ) {
  21430. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  21431. }
  21432. Mesh.call( this, geometry, material );
  21433. this.type = 'SkinnedMesh';
  21434. this.bindMode = 'attached';
  21435. this.bindMatrix = new Matrix4();
  21436. this.bindMatrixInverse = new Matrix4();
  21437. }
  21438. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  21439. constructor: SkinnedMesh,
  21440. isSkinnedMesh: true,
  21441. bind: function ( skeleton, bindMatrix ) {
  21442. this.skeleton = skeleton;
  21443. if ( bindMatrix === undefined ) {
  21444. this.updateMatrixWorld( true );
  21445. this.skeleton.calculateInverses();
  21446. bindMatrix = this.matrixWorld;
  21447. }
  21448. this.bindMatrix.copy( bindMatrix );
  21449. this.bindMatrixInverse.getInverse( bindMatrix );
  21450. },
  21451. pose: function () {
  21452. this.skeleton.pose();
  21453. },
  21454. normalizeSkinWeights: function () {
  21455. var vector = new Vector4();
  21456. var skinWeight = this.geometry.attributes.skinWeight;
  21457. for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
  21458. vector.x = skinWeight.getX( i );
  21459. vector.y = skinWeight.getY( i );
  21460. vector.z = skinWeight.getZ( i );
  21461. vector.w = skinWeight.getW( i );
  21462. var scale = 1.0 / vector.manhattanLength();
  21463. if ( scale !== Infinity ) {
  21464. vector.multiplyScalar( scale );
  21465. } else {
  21466. vector.set( 1, 0, 0, 0 ); // do something reasonable
  21467. }
  21468. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  21469. }
  21470. },
  21471. updateMatrixWorld: function ( force ) {
  21472. Mesh.prototype.updateMatrixWorld.call( this, force );
  21473. if ( this.bindMode === 'attached' ) {
  21474. this.bindMatrixInverse.getInverse( this.matrixWorld );
  21475. } else if ( this.bindMode === 'detached' ) {
  21476. this.bindMatrixInverse.getInverse( this.bindMatrix );
  21477. } else {
  21478. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  21479. }
  21480. },
  21481. clone: function () {
  21482. return new this.constructor( this.geometry, this.material ).copy( this );
  21483. }
  21484. } );
  21485. /**
  21486. * @author mikael emtinger / http://gomo.se/
  21487. * @author alteredq / http://alteredqualia.com/
  21488. * @author michael guerrero / http://realitymeltdown.com
  21489. * @author ikerr / http://verold.com
  21490. */
  21491. var _offsetMatrix = new Matrix4();
  21492. var _identityMatrix = new Matrix4();
  21493. function Skeleton( bones, boneInverses ) {
  21494. // copy the bone array
  21495. bones = bones || [];
  21496. this.bones = bones.slice( 0 );
  21497. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  21498. // use the supplied bone inverses or calculate the inverses
  21499. if ( boneInverses === undefined ) {
  21500. this.calculateInverses();
  21501. } else {
  21502. if ( this.bones.length === boneInverses.length ) {
  21503. this.boneInverses = boneInverses.slice( 0 );
  21504. } else {
  21505. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  21506. this.boneInverses = [];
  21507. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  21508. this.boneInverses.push( new Matrix4() );
  21509. }
  21510. }
  21511. }
  21512. }
  21513. Object.assign( Skeleton.prototype, {
  21514. calculateInverses: function () {
  21515. this.boneInverses = [];
  21516. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  21517. var inverse = new Matrix4();
  21518. if ( this.bones[ i ] ) {
  21519. inverse.getInverse( this.bones[ i ].matrixWorld );
  21520. }
  21521. this.boneInverses.push( inverse );
  21522. }
  21523. },
  21524. pose: function () {
  21525. var bone, i, il;
  21526. // recover the bind-time world matrices
  21527. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  21528. bone = this.bones[ i ];
  21529. if ( bone ) {
  21530. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  21531. }
  21532. }
  21533. // compute the local matrices, positions, rotations and scales
  21534. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  21535. bone = this.bones[ i ];
  21536. if ( bone ) {
  21537. if ( bone.parent && bone.parent.isBone ) {
  21538. bone.matrix.getInverse( bone.parent.matrixWorld );
  21539. bone.matrix.multiply( bone.matrixWorld );
  21540. } else {
  21541. bone.matrix.copy( bone.matrixWorld );
  21542. }
  21543. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  21544. }
  21545. }
  21546. },
  21547. update: function () {
  21548. var bones = this.bones;
  21549. var boneInverses = this.boneInverses;
  21550. var boneMatrices = this.boneMatrices;
  21551. var boneTexture = this.boneTexture;
  21552. // flatten bone matrices to array
  21553. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  21554. // compute the offset between the current and the original transform
  21555. var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  21556. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  21557. _offsetMatrix.toArray( boneMatrices, i * 16 );
  21558. }
  21559. if ( boneTexture !== undefined ) {
  21560. boneTexture.needsUpdate = true;
  21561. }
  21562. },
  21563. clone: function () {
  21564. return new Skeleton( this.bones, this.boneInverses );
  21565. },
  21566. getBoneByName: function ( name ) {
  21567. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  21568. var bone = this.bones[ i ];
  21569. if ( bone.name === name ) {
  21570. return bone;
  21571. }
  21572. }
  21573. return undefined;
  21574. }
  21575. } );
  21576. /**
  21577. * @author mikael emtinger / http://gomo.se/
  21578. * @author alteredq / http://alteredqualia.com/
  21579. * @author ikerr / http://verold.com
  21580. */
  21581. function Bone() {
  21582. Object3D.call( this );
  21583. this.type = 'Bone';
  21584. }
  21585. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21586. constructor: Bone,
  21587. isBone: true
  21588. } );
  21589. /**
  21590. * @author mrdoob / http://mrdoob.com/
  21591. * @author alteredq / http://alteredqualia.com/
  21592. *
  21593. * parameters = {
  21594. * color: <hex>,
  21595. * opacity: <float>,
  21596. *
  21597. * linewidth: <float>,
  21598. * linecap: "round",
  21599. * linejoin: "round"
  21600. * }
  21601. */
  21602. function LineBasicMaterial( parameters ) {
  21603. Material.call( this );
  21604. this.type = 'LineBasicMaterial';
  21605. this.color = new Color( 0xffffff );
  21606. this.linewidth = 1;
  21607. this.linecap = 'round';
  21608. this.linejoin = 'round';
  21609. this.lights = false;
  21610. this.setValues( parameters );
  21611. }
  21612. LineBasicMaterial.prototype = Object.create( Material.prototype );
  21613. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  21614. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  21615. LineBasicMaterial.prototype.copy = function ( source ) {
  21616. Material.prototype.copy.call( this, source );
  21617. this.color.copy( source.color );
  21618. this.linewidth = source.linewidth;
  21619. this.linecap = source.linecap;
  21620. this.linejoin = source.linejoin;
  21621. return this;
  21622. };
  21623. /**
  21624. * @author mrdoob / http://mrdoob.com/
  21625. */
  21626. var _start = new Vector3();
  21627. var _end = new Vector3();
  21628. var _inverseMatrix$1 = new Matrix4();
  21629. var _ray$1 = new Ray();
  21630. var _sphere$2 = new Sphere();
  21631. function Line( geometry, material, mode ) {
  21632. if ( mode === 1 ) {
  21633. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  21634. }
  21635. Object3D.call( this );
  21636. this.type = 'Line';
  21637. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  21638. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  21639. }
  21640. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21641. constructor: Line,
  21642. isLine: true,
  21643. computeLineDistances: function () {
  21644. var geometry = this.geometry;
  21645. if ( geometry.isBufferGeometry ) {
  21646. // we assume non-indexed geometry
  21647. if ( geometry.index === null ) {
  21648. var positionAttribute = geometry.attributes.position;
  21649. var lineDistances = [ 0 ];
  21650. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21651. _start.fromBufferAttribute( positionAttribute, i - 1 );
  21652. _end.fromBufferAttribute( positionAttribute, i );
  21653. lineDistances[ i ] = lineDistances[ i - 1 ];
  21654. lineDistances[ i ] += _start.distanceTo( _end );
  21655. }
  21656. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21657. } else {
  21658. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21659. }
  21660. } else if ( geometry.isGeometry ) {
  21661. var vertices = geometry.vertices;
  21662. var lineDistances = geometry.lineDistances;
  21663. lineDistances[ 0 ] = 0;
  21664. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  21665. lineDistances[ i ] = lineDistances[ i - 1 ];
  21666. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  21667. }
  21668. }
  21669. return this;
  21670. },
  21671. raycast: function ( raycaster, intersects ) {
  21672. var precision = raycaster.linePrecision;
  21673. var geometry = this.geometry;
  21674. var matrixWorld = this.matrixWorld;
  21675. // Checking boundingSphere distance to ray
  21676. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  21677. _sphere$2.copy( geometry.boundingSphere );
  21678. _sphere$2.applyMatrix4( matrixWorld );
  21679. _sphere$2.radius += precision;
  21680. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; }
  21681. //
  21682. _inverseMatrix$1.getInverse( matrixWorld );
  21683. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21684. var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21685. var localPrecisionSq = localPrecision * localPrecision;
  21686. var vStart = new Vector3();
  21687. var vEnd = new Vector3();
  21688. var interSegment = new Vector3();
  21689. var interRay = new Vector3();
  21690. var step = ( this && this.isLineSegments ) ? 2 : 1;
  21691. if ( geometry.isBufferGeometry ) {
  21692. var index = geometry.index;
  21693. var attributes = geometry.attributes;
  21694. var positions = attributes.position.array;
  21695. if ( index !== null ) {
  21696. var indices = index.array;
  21697. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  21698. var a = indices[ i ];
  21699. var b = indices[ i + 1 ];
  21700. vStart.fromArray( positions, a * 3 );
  21701. vEnd.fromArray( positions, b * 3 );
  21702. var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  21703. if ( distSq > localPrecisionSq ) { continue; }
  21704. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  21705. var distance = raycaster.ray.origin.distanceTo( interRay );
  21706. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  21707. intersects.push( {
  21708. distance: distance,
  21709. // What do we want? intersection point on the ray or on the segment??
  21710. // point: raycaster.ray.at( distance ),
  21711. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  21712. index: i,
  21713. face: null,
  21714. faceIndex: null,
  21715. object: this
  21716. } );
  21717. }
  21718. } else {
  21719. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  21720. vStart.fromArray( positions, 3 * i );
  21721. vEnd.fromArray( positions, 3 * i + 3 );
  21722. var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  21723. if ( distSq > localPrecisionSq ) { continue; }
  21724. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  21725. var distance = raycaster.ray.origin.distanceTo( interRay );
  21726. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  21727. intersects.push( {
  21728. distance: distance,
  21729. // What do we want? intersection point on the ray or on the segment??
  21730. // point: raycaster.ray.at( distance ),
  21731. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  21732. index: i,
  21733. face: null,
  21734. faceIndex: null,
  21735. object: this
  21736. } );
  21737. }
  21738. }
  21739. } else if ( geometry.isGeometry ) {
  21740. var vertices = geometry.vertices;
  21741. var nbVertices = vertices.length;
  21742. for ( var i = 0; i < nbVertices - 1; i += step ) {
  21743. var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  21744. if ( distSq > localPrecisionSq ) { continue; }
  21745. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  21746. var distance = raycaster.ray.origin.distanceTo( interRay );
  21747. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  21748. intersects.push( {
  21749. distance: distance,
  21750. // What do we want? intersection point on the ray or on the segment??
  21751. // point: raycaster.ray.at( distance ),
  21752. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  21753. index: i,
  21754. face: null,
  21755. faceIndex: null,
  21756. object: this
  21757. } );
  21758. }
  21759. }
  21760. },
  21761. clone: function () {
  21762. return new this.constructor( this.geometry, this.material ).copy( this );
  21763. }
  21764. } );
  21765. /**
  21766. * @author mrdoob / http://mrdoob.com/
  21767. */
  21768. var _start$1 = new Vector3();
  21769. var _end$1 = new Vector3();
  21770. function LineSegments( geometry, material ) {
  21771. Line.call( this, geometry, material );
  21772. this.type = 'LineSegments';
  21773. }
  21774. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  21775. constructor: LineSegments,
  21776. isLineSegments: true,
  21777. computeLineDistances: function () {
  21778. var geometry = this.geometry;
  21779. if ( geometry.isBufferGeometry ) {
  21780. // we assume non-indexed geometry
  21781. if ( geometry.index === null ) {
  21782. var positionAttribute = geometry.attributes.position;
  21783. var lineDistances = [];
  21784. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21785. _start$1.fromBufferAttribute( positionAttribute, i );
  21786. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  21787. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21788. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  21789. }
  21790. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21791. } else {
  21792. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21793. }
  21794. } else if ( geometry.isGeometry ) {
  21795. var vertices = geometry.vertices;
  21796. var lineDistances = geometry.lineDistances;
  21797. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  21798. _start$1.copy( vertices[ i ] );
  21799. _end$1.copy( vertices[ i + 1 ] );
  21800. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21801. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  21802. }
  21803. }
  21804. return this;
  21805. }
  21806. } );
  21807. /**
  21808. * @author mgreter / http://github.com/mgreter
  21809. */
  21810. function LineLoop( geometry, material ) {
  21811. Line.call( this, geometry, material );
  21812. this.type = 'LineLoop';
  21813. }
  21814. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  21815. constructor: LineLoop,
  21816. isLineLoop: true,
  21817. } );
  21818. /**
  21819. * @author mrdoob / http://mrdoob.com/
  21820. * @author alteredq / http://alteredqualia.com/
  21821. *
  21822. * parameters = {
  21823. * color: <hex>,
  21824. * opacity: <float>,
  21825. * map: new THREE.Texture( <Image> ),
  21826. *
  21827. * size: <float>,
  21828. * sizeAttenuation: <bool>
  21829. *
  21830. * morphTargets: <bool>
  21831. * }
  21832. */
  21833. function PointsMaterial( parameters ) {
  21834. Material.call( this );
  21835. this.type = 'PointsMaterial';
  21836. this.color = new Color( 0xffffff );
  21837. this.map = null;
  21838. this.size = 1;
  21839. this.sizeAttenuation = true;
  21840. this.morphTargets = false;
  21841. this.lights = false;
  21842. this.setValues( parameters );
  21843. }
  21844. PointsMaterial.prototype = Object.create( Material.prototype );
  21845. PointsMaterial.prototype.constructor = PointsMaterial;
  21846. PointsMaterial.prototype.isPointsMaterial = true;
  21847. PointsMaterial.prototype.copy = function ( source ) {
  21848. Material.prototype.copy.call( this, source );
  21849. this.color.copy( source.color );
  21850. this.map = source.map;
  21851. this.size = source.size;
  21852. this.sizeAttenuation = source.sizeAttenuation;
  21853. this.morphTargets = source.morphTargets;
  21854. return this;
  21855. };
  21856. /**
  21857. * @author alteredq / http://alteredqualia.com/
  21858. */
  21859. var _inverseMatrix$2 = new Matrix4();
  21860. var _ray$2 = new Ray();
  21861. var _sphere$3 = new Sphere();
  21862. var _position$1 = new Vector3();
  21863. function Points( geometry, material ) {
  21864. Object3D.call( this );
  21865. this.type = 'Points';
  21866. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  21867. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  21868. this.updateMorphTargets();
  21869. }
  21870. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21871. constructor: Points,
  21872. isPoints: true,
  21873. raycast: function ( raycaster, intersects ) {
  21874. var geometry = this.geometry;
  21875. var matrixWorld = this.matrixWorld;
  21876. var threshold = raycaster.params.Points.threshold;
  21877. // Checking boundingSphere distance to ray
  21878. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  21879. _sphere$3.copy( geometry.boundingSphere );
  21880. _sphere$3.applyMatrix4( matrixWorld );
  21881. _sphere$3.radius += threshold;
  21882. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; }
  21883. //
  21884. _inverseMatrix$2.getInverse( matrixWorld );
  21885. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  21886. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21887. var localThresholdSq = localThreshold * localThreshold;
  21888. if ( geometry.isBufferGeometry ) {
  21889. var index = geometry.index;
  21890. var attributes = geometry.attributes;
  21891. var positions = attributes.position.array;
  21892. if ( index !== null ) {
  21893. var indices = index.array;
  21894. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  21895. var a = indices[ i ];
  21896. _position$1.fromArray( positions, a * 3 );
  21897. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21898. }
  21899. } else {
  21900. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  21901. _position$1.fromArray( positions, i * 3 );
  21902. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21903. }
  21904. }
  21905. } else {
  21906. var vertices = geometry.vertices;
  21907. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  21908. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21909. }
  21910. }
  21911. },
  21912. updateMorphTargets: function () {
  21913. var geometry = this.geometry;
  21914. var m, ml, name;
  21915. if ( geometry.isBufferGeometry ) {
  21916. var morphAttributes = geometry.morphAttributes;
  21917. var keys = Object.keys( morphAttributes );
  21918. if ( keys.length > 0 ) {
  21919. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  21920. if ( morphAttribute !== undefined ) {
  21921. this.morphTargetInfluences = [];
  21922. this.morphTargetDictionary = {};
  21923. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21924. name = morphAttribute[ m ].name || String( m );
  21925. this.morphTargetInfluences.push( 0 );
  21926. this.morphTargetDictionary[ name ] = m;
  21927. }
  21928. }
  21929. }
  21930. } else {
  21931. var morphTargets = geometry.morphTargets;
  21932. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  21933. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  21934. }
  21935. }
  21936. },
  21937. clone: function () {
  21938. return new this.constructor( this.geometry, this.material ).copy( this );
  21939. }
  21940. } );
  21941. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21942. var rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  21943. if ( rayPointDistanceSq < localThresholdSq ) {
  21944. var intersectPoint = new Vector3();
  21945. _ray$2.closestPointToPoint( point, intersectPoint );
  21946. intersectPoint.applyMatrix4( matrixWorld );
  21947. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21948. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  21949. intersects.push( {
  21950. distance: distance,
  21951. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21952. point: intersectPoint,
  21953. index: index,
  21954. face: null,
  21955. object: object
  21956. } );
  21957. }
  21958. }
  21959. /**
  21960. * @author mrdoob / http://mrdoob.com/
  21961. */
  21962. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21963. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21964. this.format = format !== undefined ? format : RGBFormat;
  21965. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  21966. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  21967. this.generateMipmaps = false;
  21968. }
  21969. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  21970. constructor: VideoTexture,
  21971. isVideoTexture: true,
  21972. update: function () {
  21973. var video = this.image;
  21974. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  21975. this.needsUpdate = true;
  21976. }
  21977. }
  21978. } );
  21979. /**
  21980. * @author alteredq / http://alteredqualia.com/
  21981. */
  21982. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  21983. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  21984. this.image = { width: width, height: height };
  21985. this.mipmaps = mipmaps;
  21986. // no flipping for cube textures
  21987. // (also flipping doesn't work for compressed textures )
  21988. this.flipY = false;
  21989. // can't generate mipmaps for compressed textures
  21990. // mips must be embedded in DDS files
  21991. this.generateMipmaps = false;
  21992. }
  21993. CompressedTexture.prototype = Object.create( Texture.prototype );
  21994. CompressedTexture.prototype.constructor = CompressedTexture;
  21995. CompressedTexture.prototype.isCompressedTexture = true;
  21996. /**
  21997. * @author mrdoob / http://mrdoob.com/
  21998. */
  21999. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22000. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22001. this.needsUpdate = true;
  22002. }
  22003. CanvasTexture.prototype = Object.create( Texture.prototype );
  22004. CanvasTexture.prototype.constructor = CanvasTexture;
  22005. CanvasTexture.prototype.isCanvasTexture = true;
  22006. /**
  22007. * @author Matt DesLauriers / @mattdesl
  22008. * @author atix / arthursilber.de
  22009. */
  22010. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  22011. format = format !== undefined ? format : DepthFormat;
  22012. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22013. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22014. }
  22015. if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; }
  22016. if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; }
  22017. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22018. this.image = { width: width, height: height };
  22019. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  22020. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  22021. this.flipY = false;
  22022. this.generateMipmaps = false;
  22023. }
  22024. DepthTexture.prototype = Object.create( Texture.prototype );
  22025. DepthTexture.prototype.constructor = DepthTexture;
  22026. DepthTexture.prototype.isDepthTexture = true;
  22027. /**
  22028. * @author mrdoob / http://mrdoob.com/
  22029. * @author Mugen87 / https://github.com/Mugen87
  22030. */
  22031. function WireframeGeometry( geometry ) {
  22032. BufferGeometry.call( this );
  22033. this.type = 'WireframeGeometry';
  22034. // buffer
  22035. var vertices = [];
  22036. // helper variables
  22037. var i, j, l, o, ol;
  22038. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  22039. var key, keys = [ 'a', 'b', 'c' ];
  22040. var vertex;
  22041. // different logic for Geometry and BufferGeometry
  22042. if ( geometry && geometry.isGeometry ) {
  22043. // create a data structure that contains all edges without duplicates
  22044. var faces = geometry.faces;
  22045. for ( i = 0, l = faces.length; i < l; i ++ ) {
  22046. var face = faces[ i ];
  22047. for ( j = 0; j < 3; j ++ ) {
  22048. edge1 = face[ keys[ j ] ];
  22049. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  22050. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  22051. edge[ 1 ] = Math.max( edge1, edge2 );
  22052. key = edge[ 0 ] + ',' + edge[ 1 ];
  22053. if ( edges[ key ] === undefined ) {
  22054. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22055. }
  22056. }
  22057. }
  22058. // generate vertices
  22059. for ( key in edges ) {
  22060. e = edges[ key ];
  22061. vertex = geometry.vertices[ e.index1 ];
  22062. vertices.push( vertex.x, vertex.y, vertex.z );
  22063. vertex = geometry.vertices[ e.index2 ];
  22064. vertices.push( vertex.x, vertex.y, vertex.z );
  22065. }
  22066. } else if ( geometry && geometry.isBufferGeometry ) {
  22067. var position, indices, groups;
  22068. var group, start, count;
  22069. var index1, index2;
  22070. vertex = new Vector3();
  22071. if ( geometry.index !== null ) {
  22072. // indexed BufferGeometry
  22073. position = geometry.attributes.position;
  22074. indices = geometry.index;
  22075. groups = geometry.groups;
  22076. if ( groups.length === 0 ) {
  22077. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22078. }
  22079. // create a data structure that contains all eges without duplicates
  22080. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  22081. group = groups[ o ];
  22082. start = group.start;
  22083. count = group.count;
  22084. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  22085. for ( j = 0; j < 3; j ++ ) {
  22086. edge1 = indices.getX( i + j );
  22087. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  22088. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  22089. edge[ 1 ] = Math.max( edge1, edge2 );
  22090. key = edge[ 0 ] + ',' + edge[ 1 ];
  22091. if ( edges[ key ] === undefined ) {
  22092. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22093. }
  22094. }
  22095. }
  22096. }
  22097. // generate vertices
  22098. for ( key in edges ) {
  22099. e = edges[ key ];
  22100. vertex.fromBufferAttribute( position, e.index1 );
  22101. vertices.push( vertex.x, vertex.y, vertex.z );
  22102. vertex.fromBufferAttribute( position, e.index2 );
  22103. vertices.push( vertex.x, vertex.y, vertex.z );
  22104. }
  22105. } else {
  22106. // non-indexed BufferGeometry
  22107. position = geometry.attributes.position;
  22108. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22109. for ( j = 0; j < 3; j ++ ) {
  22110. // three edges per triangle, an edge is represented as (index1, index2)
  22111. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22112. index1 = 3 * i + j;
  22113. vertex.fromBufferAttribute( position, index1 );
  22114. vertices.push( vertex.x, vertex.y, vertex.z );
  22115. index2 = 3 * i + ( ( j + 1 ) % 3 );
  22116. vertex.fromBufferAttribute( position, index2 );
  22117. vertices.push( vertex.x, vertex.y, vertex.z );
  22118. }
  22119. }
  22120. }
  22121. }
  22122. // build geometry
  22123. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22124. }
  22125. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  22126. WireframeGeometry.prototype.constructor = WireframeGeometry;
  22127. /**
  22128. * @author zz85 / https://github.com/zz85
  22129. * @author Mugen87 / https://github.com/Mugen87
  22130. *
  22131. * Parametric Surfaces Geometry
  22132. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  22133. */
  22134. // ParametricGeometry
  22135. function ParametricGeometry( func, slices, stacks ) {
  22136. Geometry.call( this );
  22137. this.type = 'ParametricGeometry';
  22138. this.parameters = {
  22139. func: func,
  22140. slices: slices,
  22141. stacks: stacks
  22142. };
  22143. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  22144. this.mergeVertices();
  22145. }
  22146. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  22147. ParametricGeometry.prototype.constructor = ParametricGeometry;
  22148. // ParametricBufferGeometry
  22149. function ParametricBufferGeometry( func, slices, stacks ) {
  22150. BufferGeometry.call( this );
  22151. this.type = 'ParametricBufferGeometry';
  22152. this.parameters = {
  22153. func: func,
  22154. slices: slices,
  22155. stacks: stacks
  22156. };
  22157. // buffers
  22158. var indices = [];
  22159. var vertices = [];
  22160. var normals = [];
  22161. var uvs = [];
  22162. var EPS = 0.00001;
  22163. var normal = new Vector3();
  22164. var p0 = new Vector3(), p1 = new Vector3();
  22165. var pu = new Vector3(), pv = new Vector3();
  22166. var i, j;
  22167. if ( func.length < 3 ) {
  22168. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  22169. }
  22170. // generate vertices, normals and uvs
  22171. var sliceCount = slices + 1;
  22172. for ( i = 0; i <= stacks; i ++ ) {
  22173. var v = i / stacks;
  22174. for ( j = 0; j <= slices; j ++ ) {
  22175. var u = j / slices;
  22176. // vertex
  22177. func( u, v, p0 );
  22178. vertices.push( p0.x, p0.y, p0.z );
  22179. // normal
  22180. // approximate tangent vectors via finite differences
  22181. if ( u - EPS >= 0 ) {
  22182. func( u - EPS, v, p1 );
  22183. pu.subVectors( p0, p1 );
  22184. } else {
  22185. func( u + EPS, v, p1 );
  22186. pu.subVectors( p1, p0 );
  22187. }
  22188. if ( v - EPS >= 0 ) {
  22189. func( u, v - EPS, p1 );
  22190. pv.subVectors( p0, p1 );
  22191. } else {
  22192. func( u, v + EPS, p1 );
  22193. pv.subVectors( p1, p0 );
  22194. }
  22195. // cross product of tangent vectors returns surface normal
  22196. normal.crossVectors( pu, pv ).normalize();
  22197. normals.push( normal.x, normal.y, normal.z );
  22198. // uv
  22199. uvs.push( u, v );
  22200. }
  22201. }
  22202. // generate indices
  22203. for ( i = 0; i < stacks; i ++ ) {
  22204. for ( j = 0; j < slices; j ++ ) {
  22205. var a = i * sliceCount + j;
  22206. var b = i * sliceCount + j + 1;
  22207. var c = ( i + 1 ) * sliceCount + j + 1;
  22208. var d = ( i + 1 ) * sliceCount + j;
  22209. // faces one and two
  22210. indices.push( a, b, d );
  22211. indices.push( b, c, d );
  22212. }
  22213. }
  22214. // build geometry
  22215. this.setIndex( indices );
  22216. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22217. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22218. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22219. }
  22220. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22221. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  22222. /**
  22223. * @author clockworkgeek / https://github.com/clockworkgeek
  22224. * @author timothypratley / https://github.com/timothypratley
  22225. * @author WestLangley / http://github.com/WestLangley
  22226. * @author Mugen87 / https://github.com/Mugen87
  22227. */
  22228. // PolyhedronGeometry
  22229. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  22230. Geometry.call( this );
  22231. this.type = 'PolyhedronGeometry';
  22232. this.parameters = {
  22233. vertices: vertices,
  22234. indices: indices,
  22235. radius: radius,
  22236. detail: detail
  22237. };
  22238. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  22239. this.mergeVertices();
  22240. }
  22241. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  22242. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  22243. // PolyhedronBufferGeometry
  22244. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  22245. BufferGeometry.call( this );
  22246. this.type = 'PolyhedronBufferGeometry';
  22247. this.parameters = {
  22248. vertices: vertices,
  22249. indices: indices,
  22250. radius: radius,
  22251. detail: detail
  22252. };
  22253. radius = radius || 1;
  22254. detail = detail || 0;
  22255. // default buffer data
  22256. var vertexBuffer = [];
  22257. var uvBuffer = [];
  22258. // the subdivision creates the vertex buffer data
  22259. subdivide( detail );
  22260. // all vertices should lie on a conceptual sphere with a given radius
  22261. applyRadius( radius );
  22262. // finally, create the uv data
  22263. generateUVs();
  22264. // build non-indexed geometry
  22265. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22266. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22267. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22268. if ( detail === 0 ) {
  22269. this.computeVertexNormals(); // flat normals
  22270. } else {
  22271. this.normalizeNormals(); // smooth normals
  22272. }
  22273. // helper functions
  22274. function subdivide( detail ) {
  22275. var a = new Vector3();
  22276. var b = new Vector3();
  22277. var c = new Vector3();
  22278. // iterate over all faces and apply a subdivison with the given detail value
  22279. for ( var i = 0; i < indices.length; i += 3 ) {
  22280. // get the vertices of the face
  22281. getVertexByIndex( indices[ i + 0 ], a );
  22282. getVertexByIndex( indices[ i + 1 ], b );
  22283. getVertexByIndex( indices[ i + 2 ], c );
  22284. // perform subdivision
  22285. subdivideFace( a, b, c, detail );
  22286. }
  22287. }
  22288. function subdivideFace( a, b, c, detail ) {
  22289. var cols = Math.pow( 2, detail );
  22290. // we use this multidimensional array as a data structure for creating the subdivision
  22291. var v = [];
  22292. var i, j;
  22293. // construct all of the vertices for this subdivision
  22294. for ( i = 0; i <= cols; i ++ ) {
  22295. v[ i ] = [];
  22296. var aj = a.clone().lerp( c, i / cols );
  22297. var bj = b.clone().lerp( c, i / cols );
  22298. var rows = cols - i;
  22299. for ( j = 0; j <= rows; j ++ ) {
  22300. if ( j === 0 && i === cols ) {
  22301. v[ i ][ j ] = aj;
  22302. } else {
  22303. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22304. }
  22305. }
  22306. }
  22307. // construct all of the faces
  22308. for ( i = 0; i < cols; i ++ ) {
  22309. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22310. var k = Math.floor( j / 2 );
  22311. if ( j % 2 === 0 ) {
  22312. pushVertex( v[ i ][ k + 1 ] );
  22313. pushVertex( v[ i + 1 ][ k ] );
  22314. pushVertex( v[ i ][ k ] );
  22315. } else {
  22316. pushVertex( v[ i ][ k + 1 ] );
  22317. pushVertex( v[ i + 1 ][ k + 1 ] );
  22318. pushVertex( v[ i + 1 ][ k ] );
  22319. }
  22320. }
  22321. }
  22322. }
  22323. function applyRadius( radius ) {
  22324. var vertex = new Vector3();
  22325. // iterate over the entire buffer and apply the radius to each vertex
  22326. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  22327. vertex.x = vertexBuffer[ i + 0 ];
  22328. vertex.y = vertexBuffer[ i + 1 ];
  22329. vertex.z = vertexBuffer[ i + 2 ];
  22330. vertex.normalize().multiplyScalar( radius );
  22331. vertexBuffer[ i + 0 ] = vertex.x;
  22332. vertexBuffer[ i + 1 ] = vertex.y;
  22333. vertexBuffer[ i + 2 ] = vertex.z;
  22334. }
  22335. }
  22336. function generateUVs() {
  22337. var vertex = new Vector3();
  22338. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  22339. vertex.x = vertexBuffer[ i + 0 ];
  22340. vertex.y = vertexBuffer[ i + 1 ];
  22341. vertex.z = vertexBuffer[ i + 2 ];
  22342. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22343. var v = inclination( vertex ) / Math.PI + 0.5;
  22344. uvBuffer.push( u, 1 - v );
  22345. }
  22346. correctUVs();
  22347. correctSeam();
  22348. }
  22349. function correctSeam() {
  22350. // handle case when face straddles the seam, see #3269
  22351. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  22352. // uv data of a single face
  22353. var x0 = uvBuffer[ i + 0 ];
  22354. var x1 = uvBuffer[ i + 2 ];
  22355. var x2 = uvBuffer[ i + 4 ];
  22356. var max = Math.max( x0, x1, x2 );
  22357. var min = Math.min( x0, x1, x2 );
  22358. // 0.9 is somewhat arbitrary
  22359. if ( max > 0.9 && min < 0.1 ) {
  22360. if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; }
  22361. if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; }
  22362. if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; }
  22363. }
  22364. }
  22365. }
  22366. function pushVertex( vertex ) {
  22367. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22368. }
  22369. function getVertexByIndex( index, vertex ) {
  22370. var stride = index * 3;
  22371. vertex.x = vertices[ stride + 0 ];
  22372. vertex.y = vertices[ stride + 1 ];
  22373. vertex.z = vertices[ stride + 2 ];
  22374. }
  22375. function correctUVs() {
  22376. var a = new Vector3();
  22377. var b = new Vector3();
  22378. var c = new Vector3();
  22379. var centroid = new Vector3();
  22380. var uvA = new Vector2();
  22381. var uvB = new Vector2();
  22382. var uvC = new Vector2();
  22383. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22384. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22385. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22386. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22387. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22388. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22389. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22390. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22391. var azi = azimuth( centroid );
  22392. correctUV( uvA, j + 0, a, azi );
  22393. correctUV( uvB, j + 2, b, azi );
  22394. correctUV( uvC, j + 4, c, azi );
  22395. }
  22396. }
  22397. function correctUV( uv, stride, vector, azimuth ) {
  22398. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22399. uvBuffer[ stride ] = uv.x - 1;
  22400. }
  22401. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22402. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22403. }
  22404. }
  22405. // Angle around the Y axis, counter-clockwise when looking from above.
  22406. function azimuth( vector ) {
  22407. return Math.atan2( vector.z, - vector.x );
  22408. }
  22409. // Angle above the XZ plane.
  22410. function inclination( vector ) {
  22411. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22412. }
  22413. }
  22414. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22415. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  22416. /**
  22417. * @author timothypratley / https://github.com/timothypratley
  22418. * @author Mugen87 / https://github.com/Mugen87
  22419. */
  22420. // TetrahedronGeometry
  22421. function TetrahedronGeometry( radius, detail ) {
  22422. Geometry.call( this );
  22423. this.type = 'TetrahedronGeometry';
  22424. this.parameters = {
  22425. radius: radius,
  22426. detail: detail
  22427. };
  22428. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  22429. this.mergeVertices();
  22430. }
  22431. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  22432. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  22433. // TetrahedronBufferGeometry
  22434. function TetrahedronBufferGeometry( radius, detail ) {
  22435. var vertices = [
  22436. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22437. ];
  22438. var indices = [
  22439. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22440. ];
  22441. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  22442. this.type = 'TetrahedronBufferGeometry';
  22443. this.parameters = {
  22444. radius: radius,
  22445. detail: detail
  22446. };
  22447. }
  22448. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  22449. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  22450. /**
  22451. * @author timothypratley / https://github.com/timothypratley
  22452. * @author Mugen87 / https://github.com/Mugen87
  22453. */
  22454. // OctahedronGeometry
  22455. function OctahedronGeometry( radius, detail ) {
  22456. Geometry.call( this );
  22457. this.type = 'OctahedronGeometry';
  22458. this.parameters = {
  22459. radius: radius,
  22460. detail: detail
  22461. };
  22462. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  22463. this.mergeVertices();
  22464. }
  22465. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  22466. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  22467. // OctahedronBufferGeometry
  22468. function OctahedronBufferGeometry( radius, detail ) {
  22469. var vertices = [
  22470. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  22471. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22472. ];
  22473. var indices = [
  22474. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  22475. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  22476. 1, 3, 4, 1, 4, 2
  22477. ];
  22478. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  22479. this.type = 'OctahedronBufferGeometry';
  22480. this.parameters = {
  22481. radius: radius,
  22482. detail: detail
  22483. };
  22484. }
  22485. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  22486. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  22487. /**
  22488. * @author timothypratley / https://github.com/timothypratley
  22489. * @author Mugen87 / https://github.com/Mugen87
  22490. */
  22491. // IcosahedronGeometry
  22492. function IcosahedronGeometry( radius, detail ) {
  22493. Geometry.call( this );
  22494. this.type = 'IcosahedronGeometry';
  22495. this.parameters = {
  22496. radius: radius,
  22497. detail: detail
  22498. };
  22499. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  22500. this.mergeVertices();
  22501. }
  22502. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  22503. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  22504. // IcosahedronBufferGeometry
  22505. function IcosahedronBufferGeometry( radius, detail ) {
  22506. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22507. var vertices = [
  22508. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22509. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22510. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22511. ];
  22512. var indices = [
  22513. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22514. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22515. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22516. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22517. ];
  22518. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  22519. this.type = 'IcosahedronBufferGeometry';
  22520. this.parameters = {
  22521. radius: radius,
  22522. detail: detail
  22523. };
  22524. }
  22525. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  22526. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  22527. /**
  22528. * @author Abe Pazos / https://hamoid.com
  22529. * @author Mugen87 / https://github.com/Mugen87
  22530. */
  22531. // DodecahedronGeometry
  22532. function DodecahedronGeometry( radius, detail ) {
  22533. Geometry.call( this );
  22534. this.type = 'DodecahedronGeometry';
  22535. this.parameters = {
  22536. radius: radius,
  22537. detail: detail
  22538. };
  22539. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  22540. this.mergeVertices();
  22541. }
  22542. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  22543. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  22544. // DodecahedronBufferGeometry
  22545. function DodecahedronBufferGeometry( radius, detail ) {
  22546. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22547. var r = 1 / t;
  22548. var vertices = [
  22549. // (±1, ±1, ±1)
  22550. - 1, - 1, - 1, - 1, - 1, 1,
  22551. - 1, 1, - 1, - 1, 1, 1,
  22552. 1, - 1, - 1, 1, - 1, 1,
  22553. 1, 1, - 1, 1, 1, 1,
  22554. // (0, ±1/φ, ±φ)
  22555. 0, - r, - t, 0, - r, t,
  22556. 0, r, - t, 0, r, t,
  22557. // (±1/φ, ±φ, 0)
  22558. - r, - t, 0, - r, t, 0,
  22559. r, - t, 0, r, t, 0,
  22560. // (±φ, 0, ±1/φ)
  22561. - t, 0, - r, t, 0, - r,
  22562. - t, 0, r, t, 0, r
  22563. ];
  22564. var indices = [
  22565. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22566. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22567. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22568. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22569. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22570. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22571. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22572. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22573. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22574. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22575. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22576. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22577. ];
  22578. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  22579. this.type = 'DodecahedronBufferGeometry';
  22580. this.parameters = {
  22581. radius: radius,
  22582. detail: detail
  22583. };
  22584. }
  22585. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  22586. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  22587. /**
  22588. * @author oosmoxiecode / https://github.com/oosmoxiecode
  22589. * @author WestLangley / https://github.com/WestLangley
  22590. * @author zz85 / https://github.com/zz85
  22591. * @author miningold / https://github.com/miningold
  22592. * @author jonobr1 / https://github.com/jonobr1
  22593. * @author Mugen87 / https://github.com/Mugen87
  22594. *
  22595. */
  22596. // TubeGeometry
  22597. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  22598. Geometry.call( this );
  22599. this.type = 'TubeGeometry';
  22600. this.parameters = {
  22601. path: path,
  22602. tubularSegments: tubularSegments,
  22603. radius: radius,
  22604. radialSegments: radialSegments,
  22605. closed: closed
  22606. };
  22607. if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); }
  22608. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  22609. // expose internals
  22610. this.tangents = bufferGeometry.tangents;
  22611. this.normals = bufferGeometry.normals;
  22612. this.binormals = bufferGeometry.binormals;
  22613. // create geometry
  22614. this.fromBufferGeometry( bufferGeometry );
  22615. this.mergeVertices();
  22616. }
  22617. TubeGeometry.prototype = Object.create( Geometry.prototype );
  22618. TubeGeometry.prototype.constructor = TubeGeometry;
  22619. // TubeBufferGeometry
  22620. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  22621. BufferGeometry.call( this );
  22622. this.type = 'TubeBufferGeometry';
  22623. this.parameters = {
  22624. path: path,
  22625. tubularSegments: tubularSegments,
  22626. radius: radius,
  22627. radialSegments: radialSegments,
  22628. closed: closed
  22629. };
  22630. tubularSegments = tubularSegments || 64;
  22631. radius = radius || 1;
  22632. radialSegments = radialSegments || 8;
  22633. closed = closed || false;
  22634. var frames = path.computeFrenetFrames( tubularSegments, closed );
  22635. // expose internals
  22636. this.tangents = frames.tangents;
  22637. this.normals = frames.normals;
  22638. this.binormals = frames.binormals;
  22639. // helper variables
  22640. var vertex = new Vector3();
  22641. var normal = new Vector3();
  22642. var uv = new Vector2();
  22643. var P = new Vector3();
  22644. var i, j;
  22645. // buffer
  22646. var vertices = [];
  22647. var normals = [];
  22648. var uvs = [];
  22649. var indices = [];
  22650. // create buffer data
  22651. generateBufferData();
  22652. // build geometry
  22653. this.setIndex( indices );
  22654. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22655. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22656. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22657. // functions
  22658. function generateBufferData() {
  22659. for ( i = 0; i < tubularSegments; i ++ ) {
  22660. generateSegment( i );
  22661. }
  22662. // if the geometry is not closed, generate the last row of vertices and normals
  22663. // at the regular position on the given path
  22664. //
  22665. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22666. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22667. // uvs are generated in a separate function.
  22668. // this makes it easy compute correct values for closed geometries
  22669. generateUVs();
  22670. // finally create faces
  22671. generateIndices();
  22672. }
  22673. function generateSegment( i ) {
  22674. // we use getPointAt to sample evenly distributed points from the given path
  22675. P = path.getPointAt( i / tubularSegments, P );
  22676. // retrieve corresponding normal and binormal
  22677. var N = frames.normals[ i ];
  22678. var B = frames.binormals[ i ];
  22679. // generate normals and vertices for the current segment
  22680. for ( j = 0; j <= radialSegments; j ++ ) {
  22681. var v = j / radialSegments * Math.PI * 2;
  22682. var sin = Math.sin( v );
  22683. var cos = - Math.cos( v );
  22684. // normal
  22685. normal.x = ( cos * N.x + sin * B.x );
  22686. normal.y = ( cos * N.y + sin * B.y );
  22687. normal.z = ( cos * N.z + sin * B.z );
  22688. normal.normalize();
  22689. normals.push( normal.x, normal.y, normal.z );
  22690. // vertex
  22691. vertex.x = P.x + radius * normal.x;
  22692. vertex.y = P.y + radius * normal.y;
  22693. vertex.z = P.z + radius * normal.z;
  22694. vertices.push( vertex.x, vertex.y, vertex.z );
  22695. }
  22696. }
  22697. function generateIndices() {
  22698. for ( j = 1; j <= tubularSegments; j ++ ) {
  22699. for ( i = 1; i <= radialSegments; i ++ ) {
  22700. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22701. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  22702. var c = ( radialSegments + 1 ) * j + i;
  22703. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22704. // faces
  22705. indices.push( a, b, d );
  22706. indices.push( b, c, d );
  22707. }
  22708. }
  22709. }
  22710. function generateUVs() {
  22711. for ( i = 0; i <= tubularSegments; i ++ ) {
  22712. for ( j = 0; j <= radialSegments; j ++ ) {
  22713. uv.x = i / tubularSegments;
  22714. uv.y = j / radialSegments;
  22715. uvs.push( uv.x, uv.y );
  22716. }
  22717. }
  22718. }
  22719. }
  22720. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22721. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  22722. TubeBufferGeometry.prototype.toJSON = function () {
  22723. var data = BufferGeometry.prototype.toJSON.call( this );
  22724. data.path = this.parameters.path.toJSON();
  22725. return data;
  22726. };
  22727. /**
  22728. * @author oosmoxiecode
  22729. * @author Mugen87 / https://github.com/Mugen87
  22730. *
  22731. * based on http://www.blackpawn.com/texts/pqtorus/
  22732. */
  22733. // TorusKnotGeometry
  22734. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  22735. Geometry.call( this );
  22736. this.type = 'TorusKnotGeometry';
  22737. this.parameters = {
  22738. radius: radius,
  22739. tube: tube,
  22740. tubularSegments: tubularSegments,
  22741. radialSegments: radialSegments,
  22742. p: p,
  22743. q: q
  22744. };
  22745. if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); }
  22746. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  22747. this.mergeVertices();
  22748. }
  22749. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  22750. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  22751. // TorusKnotBufferGeometry
  22752. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  22753. BufferGeometry.call( this );
  22754. this.type = 'TorusKnotBufferGeometry';
  22755. this.parameters = {
  22756. radius: radius,
  22757. tube: tube,
  22758. tubularSegments: tubularSegments,
  22759. radialSegments: radialSegments,
  22760. p: p,
  22761. q: q
  22762. };
  22763. radius = radius || 1;
  22764. tube = tube || 0.4;
  22765. tubularSegments = Math.floor( tubularSegments ) || 64;
  22766. radialSegments = Math.floor( radialSegments ) || 8;
  22767. p = p || 2;
  22768. q = q || 3;
  22769. // buffers
  22770. var indices = [];
  22771. var vertices = [];
  22772. var normals = [];
  22773. var uvs = [];
  22774. // helper variables
  22775. var i, j;
  22776. var vertex = new Vector3();
  22777. var normal = new Vector3();
  22778. var P1 = new Vector3();
  22779. var P2 = new Vector3();
  22780. var B = new Vector3();
  22781. var T = new Vector3();
  22782. var N = new Vector3();
  22783. // generate vertices, normals and uvs
  22784. for ( i = 0; i <= tubularSegments; ++ i ) {
  22785. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  22786. var u = i / tubularSegments * p * Math.PI * 2;
  22787. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22788. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22789. calculatePositionOnCurve( u, p, q, radius, P1 );
  22790. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22791. // calculate orthonormal basis
  22792. T.subVectors( P2, P1 );
  22793. N.addVectors( P2, P1 );
  22794. B.crossVectors( T, N );
  22795. N.crossVectors( B, T );
  22796. // normalize B, N. T can be ignored, we don't use it
  22797. B.normalize();
  22798. N.normalize();
  22799. for ( j = 0; j <= radialSegments; ++ j ) {
  22800. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22801. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22802. var v = j / radialSegments * Math.PI * 2;
  22803. var cx = - tube * Math.cos( v );
  22804. var cy = tube * Math.sin( v );
  22805. // now calculate the final vertex position.
  22806. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  22807. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22808. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22809. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22810. vertices.push( vertex.x, vertex.y, vertex.z );
  22811. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22812. normal.subVectors( vertex, P1 ).normalize();
  22813. normals.push( normal.x, normal.y, normal.z );
  22814. // uv
  22815. uvs.push( i / tubularSegments );
  22816. uvs.push( j / radialSegments );
  22817. }
  22818. }
  22819. // generate indices
  22820. for ( j = 1; j <= tubularSegments; j ++ ) {
  22821. for ( i = 1; i <= radialSegments; i ++ ) {
  22822. // indices
  22823. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22824. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  22825. var c = ( radialSegments + 1 ) * j + i;
  22826. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22827. // faces
  22828. indices.push( a, b, d );
  22829. indices.push( b, c, d );
  22830. }
  22831. }
  22832. // build geometry
  22833. this.setIndex( indices );
  22834. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22835. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22836. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22837. // this function calculates the current position on the torus curve
  22838. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22839. var cu = Math.cos( u );
  22840. var su = Math.sin( u );
  22841. var quOverP = q / p * u;
  22842. var cs = Math.cos( quOverP );
  22843. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22844. position.y = radius * ( 2 + cs ) * su * 0.5;
  22845. position.z = radius * Math.sin( quOverP ) * 0.5;
  22846. }
  22847. }
  22848. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22849. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  22850. /**
  22851. * @author oosmoxiecode
  22852. * @author mrdoob / http://mrdoob.com/
  22853. * @author Mugen87 / https://github.com/Mugen87
  22854. */
  22855. // TorusGeometry
  22856. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  22857. Geometry.call( this );
  22858. this.type = 'TorusGeometry';
  22859. this.parameters = {
  22860. radius: radius,
  22861. tube: tube,
  22862. radialSegments: radialSegments,
  22863. tubularSegments: tubularSegments,
  22864. arc: arc
  22865. };
  22866. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  22867. this.mergeVertices();
  22868. }
  22869. TorusGeometry.prototype = Object.create( Geometry.prototype );
  22870. TorusGeometry.prototype.constructor = TorusGeometry;
  22871. // TorusBufferGeometry
  22872. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  22873. BufferGeometry.call( this );
  22874. this.type = 'TorusBufferGeometry';
  22875. this.parameters = {
  22876. radius: radius,
  22877. tube: tube,
  22878. radialSegments: radialSegments,
  22879. tubularSegments: tubularSegments,
  22880. arc: arc
  22881. };
  22882. radius = radius || 1;
  22883. tube = tube || 0.4;
  22884. radialSegments = Math.floor( radialSegments ) || 8;
  22885. tubularSegments = Math.floor( tubularSegments ) || 6;
  22886. arc = arc || Math.PI * 2;
  22887. // buffers
  22888. var indices = [];
  22889. var vertices = [];
  22890. var normals = [];
  22891. var uvs = [];
  22892. // helper variables
  22893. var center = new Vector3();
  22894. var vertex = new Vector3();
  22895. var normal = new Vector3();
  22896. var j, i;
  22897. // generate vertices, normals and uvs
  22898. for ( j = 0; j <= radialSegments; j ++ ) {
  22899. for ( i = 0; i <= tubularSegments; i ++ ) {
  22900. var u = i / tubularSegments * arc;
  22901. var v = j / radialSegments * Math.PI * 2;
  22902. // vertex
  22903. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22904. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22905. vertex.z = tube * Math.sin( v );
  22906. vertices.push( vertex.x, vertex.y, vertex.z );
  22907. // normal
  22908. center.x = radius * Math.cos( u );
  22909. center.y = radius * Math.sin( u );
  22910. normal.subVectors( vertex, center ).normalize();
  22911. normals.push( normal.x, normal.y, normal.z );
  22912. // uv
  22913. uvs.push( i / tubularSegments );
  22914. uvs.push( j / radialSegments );
  22915. }
  22916. }
  22917. // generate indices
  22918. for ( j = 1; j <= radialSegments; j ++ ) {
  22919. for ( i = 1; i <= tubularSegments; i ++ ) {
  22920. // indices
  22921. var a = ( tubularSegments + 1 ) * j + i - 1;
  22922. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22923. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22924. var d = ( tubularSegments + 1 ) * j + i;
  22925. // faces
  22926. indices.push( a, b, d );
  22927. indices.push( b, c, d );
  22928. }
  22929. }
  22930. // build geometry
  22931. this.setIndex( indices );
  22932. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22933. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22934. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22935. }
  22936. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22937. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  22938. /**
  22939. * @author Mugen87 / https://github.com/Mugen87
  22940. * Port from https://github.com/mapbox/earcut (v2.1.5)
  22941. */
  22942. var Earcut = {
  22943. triangulate: function ( data, holeIndices, dim ) {
  22944. dim = dim || 2;
  22945. var hasHoles = holeIndices && holeIndices.length,
  22946. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  22947. outerNode = linkedList( data, 0, outerLen, dim, true ),
  22948. triangles = [];
  22949. if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; }
  22950. var minX, minY, maxX, maxY, x, y, invSize;
  22951. if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); }
  22952. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22953. if ( data.length > 80 * dim ) {
  22954. minX = maxX = data[ 0 ];
  22955. minY = maxY = data[ 1 ];
  22956. for ( var i = dim; i < outerLen; i += dim ) {
  22957. x = data[ i ];
  22958. y = data[ i + 1 ];
  22959. if ( x < minX ) { minX = x; }
  22960. if ( y < minY ) { minY = y; }
  22961. if ( x > maxX ) { maxX = x; }
  22962. if ( y > maxY ) { maxY = y; }
  22963. }
  22964. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22965. invSize = Math.max( maxX - minX, maxY - minY );
  22966. invSize = invSize !== 0 ? 1 / invSize : 0;
  22967. }
  22968. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  22969. return triangles;
  22970. }
  22971. };
  22972. // create a circular doubly linked list from polygon points in the specified winding order
  22973. function linkedList( data, start, end, dim, clockwise ) {
  22974. var i, last;
  22975. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22976. for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  22977. } else {
  22978. for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  22979. }
  22980. if ( last && equals( last, last.next ) ) {
  22981. removeNode( last );
  22982. last = last.next;
  22983. }
  22984. return last;
  22985. }
  22986. // eliminate colinear or duplicate points
  22987. function filterPoints( start, end ) {
  22988. if ( ! start ) { return start; }
  22989. if ( ! end ) { end = start; }
  22990. var p = start,
  22991. again;
  22992. do {
  22993. again = false;
  22994. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22995. removeNode( p );
  22996. p = end = p.prev;
  22997. if ( p === p.next ) { break; }
  22998. again = true;
  22999. } else {
  23000. p = p.next;
  23001. }
  23002. } while ( again || p !== end );
  23003. return end;
  23004. }
  23005. // main ear slicing loop which triangulates a polygon (given as a linked list)
  23006. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  23007. if ( ! ear ) { return; }
  23008. // interlink polygon nodes in z-order
  23009. if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); }
  23010. var stop = ear,
  23011. prev, next;
  23012. // iterate through ears, slicing them one by one
  23013. while ( ear.prev !== ear.next ) {
  23014. prev = ear.prev;
  23015. next = ear.next;
  23016. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  23017. // cut off the triangle
  23018. triangles.push( prev.i / dim );
  23019. triangles.push( ear.i / dim );
  23020. triangles.push( next.i / dim );
  23021. removeNode( ear );
  23022. // skipping the next vertex leads to less sliver triangles
  23023. ear = next.next;
  23024. stop = next.next;
  23025. continue;
  23026. }
  23027. ear = next;
  23028. // if we looped through the whole remaining polygon and can't find any more ears
  23029. if ( ear === stop ) {
  23030. // try filtering points and slicing again
  23031. if ( ! pass ) {
  23032. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  23033. // if this didn't work, try curing all small self-intersections locally
  23034. } else if ( pass === 1 ) {
  23035. ear = cureLocalIntersections( ear, triangles, dim );
  23036. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  23037. // as a last resort, try splitting the remaining polygon into two
  23038. } else if ( pass === 2 ) {
  23039. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  23040. }
  23041. break;
  23042. }
  23043. }
  23044. }
  23045. // check whether a polygon node forms a valid ear with adjacent nodes
  23046. function isEar( ear ) {
  23047. var a = ear.prev,
  23048. b = ear,
  23049. c = ear.next;
  23050. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23051. // now make sure we don't have other points inside the potential ear
  23052. var p = ear.next.next;
  23053. while ( p !== ear.prev ) {
  23054. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23055. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23056. p = p.next;
  23057. }
  23058. return true;
  23059. }
  23060. function isEarHashed( ear, minX, minY, invSize ) {
  23061. var a = ear.prev,
  23062. b = ear,
  23063. c = ear.next;
  23064. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23065. // triangle bbox; min & max are calculated like this for speed
  23066. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  23067. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  23068. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  23069. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  23070. // z-order range for the current triangle bbox;
  23071. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  23072. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  23073. var p = ear.prevZ,
  23074. n = ear.nextZ;
  23075. // look for points inside the triangle in both directions
  23076. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  23077. if ( p !== ear.prev && p !== ear.next &&
  23078. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23079. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23080. p = p.prevZ;
  23081. if ( n !== ear.prev && n !== ear.next &&
  23082. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23083. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23084. n = n.nextZ;
  23085. }
  23086. // look for remaining points in decreasing z-order
  23087. while ( p && p.z >= minZ ) {
  23088. if ( p !== ear.prev && p !== ear.next &&
  23089. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23090. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23091. p = p.prevZ;
  23092. }
  23093. // look for remaining points in increasing z-order
  23094. while ( n && n.z <= maxZ ) {
  23095. if ( n !== ear.prev && n !== ear.next &&
  23096. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23097. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23098. n = n.nextZ;
  23099. }
  23100. return true;
  23101. }
  23102. // go through all polygon nodes and cure small local self-intersections
  23103. function cureLocalIntersections( start, triangles, dim ) {
  23104. var p = start;
  23105. do {
  23106. var a = p.prev,
  23107. b = p.next.next;
  23108. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  23109. triangles.push( a.i / dim );
  23110. triangles.push( p.i / dim );
  23111. triangles.push( b.i / dim );
  23112. // remove two nodes involved
  23113. removeNode( p );
  23114. removeNode( p.next );
  23115. p = start = b;
  23116. }
  23117. p = p.next;
  23118. } while ( p !== start );
  23119. return p;
  23120. }
  23121. // try splitting polygon into two and triangulate them independently
  23122. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  23123. // look for a valid diagonal that divides the polygon into two
  23124. var a = start;
  23125. do {
  23126. var b = a.next.next;
  23127. while ( b !== a.prev ) {
  23128. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  23129. // split the polygon in two by the diagonal
  23130. var c = splitPolygon( a, b );
  23131. // filter colinear points around the cuts
  23132. a = filterPoints( a, a.next );
  23133. c = filterPoints( c, c.next );
  23134. // run earcut on each half
  23135. earcutLinked( a, triangles, dim, minX, minY, invSize );
  23136. earcutLinked( c, triangles, dim, minX, minY, invSize );
  23137. return;
  23138. }
  23139. b = b.next;
  23140. }
  23141. a = a.next;
  23142. } while ( a !== start );
  23143. }
  23144. // link every hole into the outer loop, producing a single-ring polygon without holes
  23145. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  23146. var queue = [],
  23147. i, len, start, end, list;
  23148. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  23149. start = holeIndices[ i ] * dim;
  23150. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  23151. list = linkedList( data, start, end, dim, false );
  23152. if ( list === list.next ) { list.steiner = true; }
  23153. queue.push( getLeftmost( list ) );
  23154. }
  23155. queue.sort( compareX );
  23156. // process holes from left to right
  23157. for ( i = 0; i < queue.length; i ++ ) {
  23158. eliminateHole( queue[ i ], outerNode );
  23159. outerNode = filterPoints( outerNode, outerNode.next );
  23160. }
  23161. return outerNode;
  23162. }
  23163. function compareX( a, b ) {
  23164. return a.x - b.x;
  23165. }
  23166. // find a bridge between vertices that connects hole with an outer ring and and link it
  23167. function eliminateHole( hole, outerNode ) {
  23168. outerNode = findHoleBridge( hole, outerNode );
  23169. if ( outerNode ) {
  23170. var b = splitPolygon( outerNode, hole );
  23171. filterPoints( b, b.next );
  23172. }
  23173. }
  23174. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23175. function findHoleBridge( hole, outerNode ) {
  23176. var p = outerNode,
  23177. hx = hole.x,
  23178. hy = hole.y,
  23179. qx = - Infinity,
  23180. m;
  23181. // find a segment intersected by a ray from the hole's leftmost point to the left;
  23182. // segment's endpoint with lesser x will be potential connection point
  23183. do {
  23184. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  23185. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  23186. if ( x <= hx && x > qx ) {
  23187. qx = x;
  23188. if ( x === hx ) {
  23189. if ( hy === p.y ) { return p; }
  23190. if ( hy === p.next.y ) { return p.next; }
  23191. }
  23192. m = p.x < p.next.x ? p : p.next;
  23193. }
  23194. }
  23195. p = p.next;
  23196. } while ( p !== outerNode );
  23197. if ( ! m ) { return null; }
  23198. if ( hx === qx ) { return m.prev; } // hole touches outer segment; pick lower endpoint
  23199. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23200. // if there are no points found, we have a valid connection;
  23201. // otherwise choose the point of the minimum angle with the ray as connection point
  23202. var stop = m,
  23203. mx = m.x,
  23204. my = m.y,
  23205. tanMin = Infinity,
  23206. tan;
  23207. p = m.next;
  23208. while ( p !== stop ) {
  23209. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  23210. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  23211. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  23212. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  23213. m = p;
  23214. tanMin = tan;
  23215. }
  23216. }
  23217. p = p.next;
  23218. }
  23219. return m;
  23220. }
  23221. // interlink polygon nodes in z-order
  23222. function indexCurve( start, minX, minY, invSize ) {
  23223. var p = start;
  23224. do {
  23225. if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); }
  23226. p.prevZ = p.prev;
  23227. p.nextZ = p.next;
  23228. p = p.next;
  23229. } while ( p !== start );
  23230. p.prevZ.nextZ = null;
  23231. p.prevZ = null;
  23232. sortLinked( p );
  23233. }
  23234. // Simon Tatham's linked list merge sort algorithm
  23235. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23236. function sortLinked( list ) {
  23237. var i, p, q, e, tail, numMerges, pSize, qSize,
  23238. inSize = 1;
  23239. do {
  23240. p = list;
  23241. list = null;
  23242. tail = null;
  23243. numMerges = 0;
  23244. while ( p ) {
  23245. numMerges ++;
  23246. q = p;
  23247. pSize = 0;
  23248. for ( i = 0; i < inSize; i ++ ) {
  23249. pSize ++;
  23250. q = q.nextZ;
  23251. if ( ! q ) { break; }
  23252. }
  23253. qSize = inSize;
  23254. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  23255. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  23256. e = p;
  23257. p = p.nextZ;
  23258. pSize --;
  23259. } else {
  23260. e = q;
  23261. q = q.nextZ;
  23262. qSize --;
  23263. }
  23264. if ( tail ) { tail.nextZ = e; }
  23265. else { list = e; }
  23266. e.prevZ = tail;
  23267. tail = e;
  23268. }
  23269. p = q;
  23270. }
  23271. tail.nextZ = null;
  23272. inSize *= 2;
  23273. } while ( numMerges > 1 );
  23274. return list;
  23275. }
  23276. // z-order of a point given coords and inverse of the longer side of data bbox
  23277. function zOrder( x, y, minX, minY, invSize ) {
  23278. // coords are transformed into non-negative 15-bit integer range
  23279. x = 32767 * ( x - minX ) * invSize;
  23280. y = 32767 * ( y - minY ) * invSize;
  23281. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  23282. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  23283. x = ( x | ( x << 2 ) ) & 0x33333333;
  23284. x = ( x | ( x << 1 ) ) & 0x55555555;
  23285. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  23286. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  23287. y = ( y | ( y << 2 ) ) & 0x33333333;
  23288. y = ( y | ( y << 1 ) ) & 0x55555555;
  23289. return x | ( y << 1 );
  23290. }
  23291. // find the leftmost node of a polygon ring
  23292. function getLeftmost( start ) {
  23293. var p = start,
  23294. leftmost = start;
  23295. do {
  23296. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; }
  23297. p = p.next;
  23298. } while ( p !== start );
  23299. return leftmost;
  23300. }
  23301. // check if a point lies within a convex triangle
  23302. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  23303. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  23304. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  23305. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  23306. }
  23307. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23308. function isValidDiagonal( a, b ) {
  23309. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  23310. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  23311. }
  23312. // signed area of a triangle
  23313. function area( p, q, r ) {
  23314. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  23315. }
  23316. // check if two points are equal
  23317. function equals( p1, p2 ) {
  23318. return p1.x === p2.x && p1.y === p2.y;
  23319. }
  23320. // check if two segments intersect
  23321. function intersects( p1, q1, p2, q2 ) {
  23322. if ( ( equals( p1, p2 ) && equals( q1, q2 ) ) ||
  23323. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) { return true; }
  23324. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  23325. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  23326. }
  23327. // check if a polygon diagonal intersects any polygon segments
  23328. function intersectsPolygon( a, b ) {
  23329. var p = a;
  23330. do {
  23331. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  23332. intersects( p, p.next, a, b ) ) { return true; }
  23333. p = p.next;
  23334. } while ( p !== a );
  23335. return false;
  23336. }
  23337. // check if a polygon diagonal is locally inside the polygon
  23338. function locallyInside( a, b ) {
  23339. return area( a.prev, a, a.next ) < 0 ?
  23340. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  23341. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  23342. }
  23343. // check if the middle point of a polygon diagonal is inside the polygon
  23344. function middleInside( a, b ) {
  23345. var p = a,
  23346. inside = false,
  23347. px = ( a.x + b.x ) / 2,
  23348. py = ( a.y + b.y ) / 2;
  23349. do {
  23350. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  23351. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  23352. { inside = ! inside; }
  23353. p = p.next;
  23354. } while ( p !== a );
  23355. return inside;
  23356. }
  23357. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  23358. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  23359. function splitPolygon( a, b ) {
  23360. var a2 = new Node( a.i, a.x, a.y ),
  23361. b2 = new Node( b.i, b.x, b.y ),
  23362. an = a.next,
  23363. bp = b.prev;
  23364. a.next = b;
  23365. b.prev = a;
  23366. a2.next = an;
  23367. an.prev = a2;
  23368. b2.next = a2;
  23369. a2.prev = b2;
  23370. bp.next = b2;
  23371. b2.prev = bp;
  23372. return b2;
  23373. }
  23374. // create a node and optionally link it with previous one (in a circular doubly linked list)
  23375. function insertNode( i, x, y, last ) {
  23376. var p = new Node( i, x, y );
  23377. if ( ! last ) {
  23378. p.prev = p;
  23379. p.next = p;
  23380. } else {
  23381. p.next = last.next;
  23382. p.prev = last;
  23383. last.next.prev = p;
  23384. last.next = p;
  23385. }
  23386. return p;
  23387. }
  23388. function removeNode( p ) {
  23389. p.next.prev = p.prev;
  23390. p.prev.next = p.next;
  23391. if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; }
  23392. if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; }
  23393. }
  23394. function Node( i, x, y ) {
  23395. // vertex index in coordinates array
  23396. this.i = i;
  23397. // vertex coordinates
  23398. this.x = x;
  23399. this.y = y;
  23400. // previous and next vertex nodes in a polygon ring
  23401. this.prev = null;
  23402. this.next = null;
  23403. // z-order curve value
  23404. this.z = null;
  23405. // previous and next nodes in z-order
  23406. this.prevZ = null;
  23407. this.nextZ = null;
  23408. // indicates whether this is a steiner point
  23409. this.steiner = false;
  23410. }
  23411. function signedArea( data, start, end, dim ) {
  23412. var sum = 0;
  23413. for ( var i = start, j = end - dim; i < end; i += dim ) {
  23414. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  23415. j = i;
  23416. }
  23417. return sum;
  23418. }
  23419. /**
  23420. * @author zz85 / http://www.lab4games.net/zz85/blog
  23421. */
  23422. var ShapeUtils = {
  23423. // calculate area of the contour polygon
  23424. area: function ( contour ) {
  23425. var n = contour.length;
  23426. var a = 0.0;
  23427. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  23428. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  23429. }
  23430. return a * 0.5;
  23431. },
  23432. isClockWise: function ( pts ) {
  23433. return ShapeUtils.area( pts ) < 0;
  23434. },
  23435. triangulateShape: function ( contour, holes ) {
  23436. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  23437. var holeIndices = []; // array of hole indices
  23438. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  23439. removeDupEndPts( contour );
  23440. addContour( vertices, contour );
  23441. //
  23442. var holeIndex = contour.length;
  23443. holes.forEach( removeDupEndPts );
  23444. for ( var i = 0; i < holes.length; i ++ ) {
  23445. holeIndices.push( holeIndex );
  23446. holeIndex += holes[ i ].length;
  23447. addContour( vertices, holes[ i ] );
  23448. }
  23449. //
  23450. var triangles = Earcut.triangulate( vertices, holeIndices );
  23451. //
  23452. for ( var i = 0; i < triangles.length; i += 3 ) {
  23453. faces.push( triangles.slice( i, i + 3 ) );
  23454. }
  23455. return faces;
  23456. }
  23457. };
  23458. function removeDupEndPts( points ) {
  23459. var l = points.length;
  23460. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  23461. points.pop();
  23462. }
  23463. }
  23464. function addContour( vertices, contour ) {
  23465. for ( var i = 0; i < contour.length; i ++ ) {
  23466. vertices.push( contour[ i ].x );
  23467. vertices.push( contour[ i ].y );
  23468. }
  23469. }
  23470. /**
  23471. * @author zz85 / http://www.lab4games.net/zz85/blog
  23472. *
  23473. * Creates extruded geometry from a path shape.
  23474. *
  23475. * parameters = {
  23476. *
  23477. * curveSegments: <int>, // number of points on the curves
  23478. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  23479. * depth: <float>, // Depth to extrude the shape
  23480. *
  23481. * bevelEnabled: <bool>, // turn on bevel
  23482. * bevelThickness: <float>, // how deep into the original shape bevel goes
  23483. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  23484. * bevelOffset: <float>, // how far from shape outline does bevel start
  23485. * bevelSegments: <int>, // number of bevel layers
  23486. *
  23487. * extrudePath: <THREE.Curve> // curve to extrude shape along
  23488. *
  23489. * UVGenerator: <Object> // object that provides UV generator functions
  23490. *
  23491. * }
  23492. */
  23493. // ExtrudeGeometry
  23494. function ExtrudeGeometry( shapes, options ) {
  23495. Geometry.call( this );
  23496. this.type = 'ExtrudeGeometry';
  23497. this.parameters = {
  23498. shapes: shapes,
  23499. options: options
  23500. };
  23501. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  23502. this.mergeVertices();
  23503. }
  23504. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  23505. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  23506. ExtrudeGeometry.prototype.toJSON = function () {
  23507. var data = Geometry.prototype.toJSON.call( this );
  23508. var shapes = this.parameters.shapes;
  23509. var options = this.parameters.options;
  23510. return toJSON( shapes, options, data );
  23511. };
  23512. // ExtrudeBufferGeometry
  23513. function ExtrudeBufferGeometry( shapes, options ) {
  23514. BufferGeometry.call( this );
  23515. this.type = 'ExtrudeBufferGeometry';
  23516. this.parameters = {
  23517. shapes: shapes,
  23518. options: options
  23519. };
  23520. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  23521. var scope = this;
  23522. var verticesArray = [];
  23523. var uvArray = [];
  23524. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  23525. var shape = shapes[ i ];
  23526. addShape( shape );
  23527. }
  23528. // build geometry
  23529. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  23530. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  23531. this.computeVertexNormals();
  23532. // functions
  23533. function addShape( shape ) {
  23534. var placeholder = [];
  23535. // options
  23536. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  23537. var steps = options.steps !== undefined ? options.steps : 1;
  23538. var depth = options.depth !== undefined ? options.depth : 100;
  23539. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  23540. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  23541. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  23542. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  23543. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  23544. var extrudePath = options.extrudePath;
  23545. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  23546. // deprecated options
  23547. if ( options.amount !== undefined ) {
  23548. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  23549. depth = options.amount;
  23550. }
  23551. //
  23552. var extrudePts, extrudeByPath = false;
  23553. var splineTube, binormal, normal, position2;
  23554. if ( extrudePath ) {
  23555. extrudePts = extrudePath.getSpacedPoints( steps );
  23556. extrudeByPath = true;
  23557. bevelEnabled = false; // bevels not supported for path extrusion
  23558. // SETUP TNB variables
  23559. // TODO1 - have a .isClosed in spline?
  23560. splineTube = extrudePath.computeFrenetFrames( steps, false );
  23561. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  23562. binormal = new Vector3();
  23563. normal = new Vector3();
  23564. position2 = new Vector3();
  23565. }
  23566. // Safeguards if bevels are not enabled
  23567. if ( ! bevelEnabled ) {
  23568. bevelSegments = 0;
  23569. bevelThickness = 0;
  23570. bevelSize = 0;
  23571. bevelOffset = 0;
  23572. }
  23573. // Variables initialization
  23574. var ahole, h, hl; // looping of holes
  23575. var shapePoints = shape.extractPoints( curveSegments );
  23576. var vertices = shapePoints.shape;
  23577. var holes = shapePoints.holes;
  23578. var reverse = ! ShapeUtils.isClockWise( vertices );
  23579. if ( reverse ) {
  23580. vertices = vertices.reverse();
  23581. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  23582. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23583. ahole = holes[ h ];
  23584. if ( ShapeUtils.isClockWise( ahole ) ) {
  23585. holes[ h ] = ahole.reverse();
  23586. }
  23587. }
  23588. }
  23589. var faces = ShapeUtils.triangulateShape( vertices, holes );
  23590. /* Vertices */
  23591. var contour = vertices; // vertices has all points but contour has only points of circumference
  23592. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23593. ahole = holes[ h ];
  23594. vertices = vertices.concat( ahole );
  23595. }
  23596. function scalePt2( pt, vec, size ) {
  23597. if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); }
  23598. return vec.clone().multiplyScalar( size ).add( pt );
  23599. }
  23600. var b, bs, t, z,
  23601. vert, vlen = vertices.length,
  23602. face, flen = faces.length;
  23603. // Find directions for point movement
  23604. function getBevelVec( inPt, inPrev, inNext ) {
  23605. // computes for inPt the corresponding point inPt' on a new contour
  23606. // shifted by 1 unit (length of normalized vector) to the left
  23607. // if we walk along contour clockwise, this new contour is outside the old one
  23608. //
  23609. // inPt' is the intersection of the two lines parallel to the two
  23610. // adjacent edges of inPt at a distance of 1 unit on the left side.
  23611. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  23612. // good reading for geometry algorithms (here: line-line intersection)
  23613. // http://geomalgorithms.com/a05-_intersect-1.html
  23614. var v_prev_x = inPt.x - inPrev.x,
  23615. v_prev_y = inPt.y - inPrev.y;
  23616. var v_next_x = inNext.x - inPt.x,
  23617. v_next_y = inNext.y - inPt.y;
  23618. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  23619. // check for collinear edges
  23620. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23621. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  23622. // not collinear
  23623. // length of vectors for normalizing
  23624. var v_prev_len = Math.sqrt( v_prev_lensq );
  23625. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  23626. // shift adjacent points by unit vectors to the left
  23627. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  23628. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  23629. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  23630. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  23631. // scaling factor for v_prev to intersection point
  23632. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  23633. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  23634. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23635. // vector from inPt to intersection point
  23636. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  23637. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  23638. // Don't normalize!, otherwise sharp corners become ugly
  23639. // but prevent crazy spikes
  23640. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  23641. if ( v_trans_lensq <= 2 ) {
  23642. return new Vector2( v_trans_x, v_trans_y );
  23643. } else {
  23644. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  23645. }
  23646. } else {
  23647. // handle special case of collinear edges
  23648. var direction_eq = false; // assumes: opposite
  23649. if ( v_prev_x > Number.EPSILON ) {
  23650. if ( v_next_x > Number.EPSILON ) {
  23651. direction_eq = true;
  23652. }
  23653. } else {
  23654. if ( v_prev_x < - Number.EPSILON ) {
  23655. if ( v_next_x < - Number.EPSILON ) {
  23656. direction_eq = true;
  23657. }
  23658. } else {
  23659. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23660. direction_eq = true;
  23661. }
  23662. }
  23663. }
  23664. if ( direction_eq ) {
  23665. // console.log("Warning: lines are a straight sequence");
  23666. v_trans_x = - v_prev_y;
  23667. v_trans_y = v_prev_x;
  23668. shrink_by = Math.sqrt( v_prev_lensq );
  23669. } else {
  23670. // console.log("Warning: lines are a straight spike");
  23671. v_trans_x = v_prev_x;
  23672. v_trans_y = v_prev_y;
  23673. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23674. }
  23675. }
  23676. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23677. }
  23678. var contourMovements = [];
  23679. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23680. if ( j === il ) { j = 0; }
  23681. if ( k === il ) { k = 0; }
  23682. // (j)---(i)---(k)
  23683. // console.log('i,j,k', i, j , k)
  23684. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23685. }
  23686. var holesMovements = [],
  23687. oneHoleMovements, verticesMovements = contourMovements.concat();
  23688. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23689. ahole = holes[ h ];
  23690. oneHoleMovements = [];
  23691. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23692. if ( j === il ) { j = 0; }
  23693. if ( k === il ) { k = 0; }
  23694. // (j)---(i)---(k)
  23695. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23696. }
  23697. holesMovements.push( oneHoleMovements );
  23698. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23699. }
  23700. // Loop bevelSegments, 1 for the front, 1 for the back
  23701. for ( b = 0; b < bevelSegments; b ++ ) {
  23702. //for ( b = bevelSegments; b > 0; b -- ) {
  23703. t = b / bevelSegments;
  23704. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23705. bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23706. // contract shape
  23707. for ( i = 0, il = contour.length; i < il; i ++ ) {
  23708. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23709. v( vert.x, vert.y, - z );
  23710. }
  23711. // expand holes
  23712. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23713. ahole = holes[ h ];
  23714. oneHoleMovements = holesMovements[ h ];
  23715. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  23716. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23717. v( vert.x, vert.y, - z );
  23718. }
  23719. }
  23720. }
  23721. bs = bevelSize + bevelOffset;
  23722. // Back facing vertices
  23723. for ( i = 0; i < vlen; i ++ ) {
  23724. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23725. if ( ! extrudeByPath ) {
  23726. v( vert.x, vert.y, 0 );
  23727. } else {
  23728. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23729. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23730. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23731. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23732. v( position2.x, position2.y, position2.z );
  23733. }
  23734. }
  23735. // Add stepped vertices...
  23736. // Including front facing vertices
  23737. var s;
  23738. for ( s = 1; s <= steps; s ++ ) {
  23739. for ( i = 0; i < vlen; i ++ ) {
  23740. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23741. if ( ! extrudeByPath ) {
  23742. v( vert.x, vert.y, depth / steps * s );
  23743. } else {
  23744. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23745. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23746. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23747. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23748. v( position2.x, position2.y, position2.z );
  23749. }
  23750. }
  23751. }
  23752. // Add bevel segments planes
  23753. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23754. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  23755. t = b / bevelSegments;
  23756. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23757. bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23758. // contract shape
  23759. for ( i = 0, il = contour.length; i < il; i ++ ) {
  23760. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23761. v( vert.x, vert.y, depth + z );
  23762. }
  23763. // expand holes
  23764. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23765. ahole = holes[ h ];
  23766. oneHoleMovements = holesMovements[ h ];
  23767. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  23768. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23769. if ( ! extrudeByPath ) {
  23770. v( vert.x, vert.y, depth + z );
  23771. } else {
  23772. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23773. }
  23774. }
  23775. }
  23776. }
  23777. /* Faces */
  23778. // Top and bottom faces
  23779. buildLidFaces();
  23780. // Sides faces
  23781. buildSideFaces();
  23782. ///// Internal functions
  23783. function buildLidFaces() {
  23784. var start = verticesArray.length / 3;
  23785. if ( bevelEnabled ) {
  23786. var layer = 0; // steps + 1
  23787. var offset = vlen * layer;
  23788. // Bottom faces
  23789. for ( i = 0; i < flen; i ++ ) {
  23790. face = faces[ i ];
  23791. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23792. }
  23793. layer = steps + bevelSegments * 2;
  23794. offset = vlen * layer;
  23795. // Top faces
  23796. for ( i = 0; i < flen; i ++ ) {
  23797. face = faces[ i ];
  23798. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23799. }
  23800. } else {
  23801. // Bottom faces
  23802. for ( i = 0; i < flen; i ++ ) {
  23803. face = faces[ i ];
  23804. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23805. }
  23806. // Top faces
  23807. for ( i = 0; i < flen; i ++ ) {
  23808. face = faces[ i ];
  23809. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23810. }
  23811. }
  23812. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23813. }
  23814. // Create faces for the z-sides of the shape
  23815. function buildSideFaces() {
  23816. var start = verticesArray.length / 3;
  23817. var layeroffset = 0;
  23818. sidewalls( contour, layeroffset );
  23819. layeroffset += contour.length;
  23820. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  23821. ahole = holes[ h ];
  23822. sidewalls( ahole, layeroffset );
  23823. //, true
  23824. layeroffset += ahole.length;
  23825. }
  23826. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23827. }
  23828. function sidewalls( contour, layeroffset ) {
  23829. var j, k;
  23830. i = contour.length;
  23831. while ( -- i >= 0 ) {
  23832. j = i;
  23833. k = i - 1;
  23834. if ( k < 0 ) { k = contour.length - 1; }
  23835. //console.log('b', i,j, i-1, k,vertices.length);
  23836. var s = 0,
  23837. sl = steps + bevelSegments * 2;
  23838. for ( s = 0; s < sl; s ++ ) {
  23839. var slen1 = vlen * s;
  23840. var slen2 = vlen * ( s + 1 );
  23841. var a = layeroffset + j + slen1,
  23842. b = layeroffset + k + slen1,
  23843. c = layeroffset + k + slen2,
  23844. d = layeroffset + j + slen2;
  23845. f4( a, b, c, d );
  23846. }
  23847. }
  23848. }
  23849. function v( x, y, z ) {
  23850. placeholder.push( x );
  23851. placeholder.push( y );
  23852. placeholder.push( z );
  23853. }
  23854. function f3( a, b, c ) {
  23855. addVertex( a );
  23856. addVertex( b );
  23857. addVertex( c );
  23858. var nextIndex = verticesArray.length / 3;
  23859. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23860. addUV( uvs[ 0 ] );
  23861. addUV( uvs[ 1 ] );
  23862. addUV( uvs[ 2 ] );
  23863. }
  23864. function f4( a, b, c, d ) {
  23865. addVertex( a );
  23866. addVertex( b );
  23867. addVertex( d );
  23868. addVertex( b );
  23869. addVertex( c );
  23870. addVertex( d );
  23871. var nextIndex = verticesArray.length / 3;
  23872. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23873. addUV( uvs[ 0 ] );
  23874. addUV( uvs[ 1 ] );
  23875. addUV( uvs[ 3 ] );
  23876. addUV( uvs[ 1 ] );
  23877. addUV( uvs[ 2 ] );
  23878. addUV( uvs[ 3 ] );
  23879. }
  23880. function addVertex( index ) {
  23881. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23882. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23883. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23884. }
  23885. function addUV( vector2 ) {
  23886. uvArray.push( vector2.x );
  23887. uvArray.push( vector2.y );
  23888. }
  23889. }
  23890. }
  23891. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23892. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  23893. ExtrudeBufferGeometry.prototype.toJSON = function () {
  23894. var data = BufferGeometry.prototype.toJSON.call( this );
  23895. var shapes = this.parameters.shapes;
  23896. var options = this.parameters.options;
  23897. return toJSON( shapes, options, data );
  23898. };
  23899. //
  23900. var WorldUVGenerator = {
  23901. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23902. var a_x = vertices[ indexA * 3 ];
  23903. var a_y = vertices[ indexA * 3 + 1 ];
  23904. var b_x = vertices[ indexB * 3 ];
  23905. var b_y = vertices[ indexB * 3 + 1 ];
  23906. var c_x = vertices[ indexC * 3 ];
  23907. var c_y = vertices[ indexC * 3 + 1 ];
  23908. return [
  23909. new Vector2( a_x, a_y ),
  23910. new Vector2( b_x, b_y ),
  23911. new Vector2( c_x, c_y )
  23912. ];
  23913. },
  23914. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23915. var a_x = vertices[ indexA * 3 ];
  23916. var a_y = vertices[ indexA * 3 + 1 ];
  23917. var a_z = vertices[ indexA * 3 + 2 ];
  23918. var b_x = vertices[ indexB * 3 ];
  23919. var b_y = vertices[ indexB * 3 + 1 ];
  23920. var b_z = vertices[ indexB * 3 + 2 ];
  23921. var c_x = vertices[ indexC * 3 ];
  23922. var c_y = vertices[ indexC * 3 + 1 ];
  23923. var c_z = vertices[ indexC * 3 + 2 ];
  23924. var d_x = vertices[ indexD * 3 ];
  23925. var d_y = vertices[ indexD * 3 + 1 ];
  23926. var d_z = vertices[ indexD * 3 + 2 ];
  23927. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  23928. return [
  23929. new Vector2( a_x, 1 - a_z ),
  23930. new Vector2( b_x, 1 - b_z ),
  23931. new Vector2( c_x, 1 - c_z ),
  23932. new Vector2( d_x, 1 - d_z )
  23933. ];
  23934. } else {
  23935. return [
  23936. new Vector2( a_y, 1 - a_z ),
  23937. new Vector2( b_y, 1 - b_z ),
  23938. new Vector2( c_y, 1 - c_z ),
  23939. new Vector2( d_y, 1 - d_z )
  23940. ];
  23941. }
  23942. }
  23943. };
  23944. function toJSON( shapes, options, data ) {
  23945. //
  23946. data.shapes = [];
  23947. if ( Array.isArray( shapes ) ) {
  23948. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  23949. var shape = shapes[ i ];
  23950. data.shapes.push( shape.uuid );
  23951. }
  23952. } else {
  23953. data.shapes.push( shapes.uuid );
  23954. }
  23955. //
  23956. if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); }
  23957. return data;
  23958. }
  23959. /**
  23960. * @author zz85 / http://www.lab4games.net/zz85/blog
  23961. * @author alteredq / http://alteredqualia.com/
  23962. *
  23963. * Text = 3D Text
  23964. *
  23965. * parameters = {
  23966. * font: <THREE.Font>, // font
  23967. *
  23968. * size: <float>, // size of the text
  23969. * height: <float>, // thickness to extrude text
  23970. * curveSegments: <int>, // number of points on the curves
  23971. *
  23972. * bevelEnabled: <bool>, // turn on bevel
  23973. * bevelThickness: <float>, // how deep into text bevel goes
  23974. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  23975. * bevelOffset: <float> // how far from text outline does bevel start
  23976. * }
  23977. */
  23978. // TextGeometry
  23979. function TextGeometry( text, parameters ) {
  23980. Geometry.call( this );
  23981. this.type = 'TextGeometry';
  23982. this.parameters = {
  23983. text: text,
  23984. parameters: parameters
  23985. };
  23986. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  23987. this.mergeVertices();
  23988. }
  23989. TextGeometry.prototype = Object.create( Geometry.prototype );
  23990. TextGeometry.prototype.constructor = TextGeometry;
  23991. // TextBufferGeometry
  23992. function TextBufferGeometry( text, parameters ) {
  23993. parameters = parameters || {};
  23994. var font = parameters.font;
  23995. if ( ! ( font && font.isFont ) ) {
  23996. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  23997. return new Geometry();
  23998. }
  23999. var shapes = font.generateShapes( text, parameters.size );
  24000. // translate parameters to ExtrudeGeometry API
  24001. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  24002. // defaults
  24003. if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; }
  24004. if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; }
  24005. if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; }
  24006. ExtrudeBufferGeometry.call( this, shapes, parameters );
  24007. this.type = 'TextBufferGeometry';
  24008. }
  24009. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  24010. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  24011. /**
  24012. * @author mrdoob / http://mrdoob.com/
  24013. * @author benaadams / https://twitter.com/ben_a_adams
  24014. * @author Mugen87 / https://github.com/Mugen87
  24015. */
  24016. // SphereGeometry
  24017. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24018. Geometry.call( this );
  24019. this.type = 'SphereGeometry';
  24020. this.parameters = {
  24021. radius: radius,
  24022. widthSegments: widthSegments,
  24023. heightSegments: heightSegments,
  24024. phiStart: phiStart,
  24025. phiLength: phiLength,
  24026. thetaStart: thetaStart,
  24027. thetaLength: thetaLength
  24028. };
  24029. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  24030. this.mergeVertices();
  24031. }
  24032. SphereGeometry.prototype = Object.create( Geometry.prototype );
  24033. SphereGeometry.prototype.constructor = SphereGeometry;
  24034. // SphereBufferGeometry
  24035. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24036. BufferGeometry.call( this );
  24037. this.type = 'SphereBufferGeometry';
  24038. this.parameters = {
  24039. radius: radius,
  24040. widthSegments: widthSegments,
  24041. heightSegments: heightSegments,
  24042. phiStart: phiStart,
  24043. phiLength: phiLength,
  24044. thetaStart: thetaStart,
  24045. thetaLength: thetaLength
  24046. };
  24047. radius = radius || 1;
  24048. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  24049. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  24050. phiStart = phiStart !== undefined ? phiStart : 0;
  24051. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  24052. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24053. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  24054. var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  24055. var ix, iy;
  24056. var index = 0;
  24057. var grid = [];
  24058. var vertex = new Vector3();
  24059. var normal = new Vector3();
  24060. // buffers
  24061. var indices = [];
  24062. var vertices = [];
  24063. var normals = [];
  24064. var uvs = [];
  24065. // generate vertices, normals and uvs
  24066. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  24067. var verticesRow = [];
  24068. var v = iy / heightSegments;
  24069. // special case for the poles
  24070. var uOffset = 0;
  24071. if ( iy == 0 && thetaStart == 0 ) {
  24072. uOffset = 0.5 / widthSegments;
  24073. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  24074. uOffset = - 0.5 / widthSegments;
  24075. }
  24076. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  24077. var u = ix / widthSegments;
  24078. // vertex
  24079. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24080. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  24081. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24082. vertices.push( vertex.x, vertex.y, vertex.z );
  24083. // normal
  24084. normal.copy( vertex ).normalize();
  24085. normals.push( normal.x, normal.y, normal.z );
  24086. // uv
  24087. uvs.push( u + uOffset, 1 - v );
  24088. verticesRow.push( index ++ );
  24089. }
  24090. grid.push( verticesRow );
  24091. }
  24092. // indices
  24093. for ( iy = 0; iy < heightSegments; iy ++ ) {
  24094. for ( ix = 0; ix < widthSegments; ix ++ ) {
  24095. var a = grid[ iy ][ ix + 1 ];
  24096. var b = grid[ iy ][ ix ];
  24097. var c = grid[ iy + 1 ][ ix ];
  24098. var d = grid[ iy + 1 ][ ix + 1 ];
  24099. if ( iy !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); }
  24100. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); }
  24101. }
  24102. }
  24103. // build geometry
  24104. this.setIndex( indices );
  24105. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24106. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24107. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24108. }
  24109. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24110. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  24111. /**
  24112. * @author Kaleb Murphy
  24113. * @author Mugen87 / https://github.com/Mugen87
  24114. */
  24115. // RingGeometry
  24116. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24117. Geometry.call( this );
  24118. this.type = 'RingGeometry';
  24119. this.parameters = {
  24120. innerRadius: innerRadius,
  24121. outerRadius: outerRadius,
  24122. thetaSegments: thetaSegments,
  24123. phiSegments: phiSegments,
  24124. thetaStart: thetaStart,
  24125. thetaLength: thetaLength
  24126. };
  24127. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  24128. this.mergeVertices();
  24129. }
  24130. RingGeometry.prototype = Object.create( Geometry.prototype );
  24131. RingGeometry.prototype.constructor = RingGeometry;
  24132. // RingBufferGeometry
  24133. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24134. BufferGeometry.call( this );
  24135. this.type = 'RingBufferGeometry';
  24136. this.parameters = {
  24137. innerRadius: innerRadius,
  24138. outerRadius: outerRadius,
  24139. thetaSegments: thetaSegments,
  24140. phiSegments: phiSegments,
  24141. thetaStart: thetaStart,
  24142. thetaLength: thetaLength
  24143. };
  24144. innerRadius = innerRadius || 0.5;
  24145. outerRadius = outerRadius || 1;
  24146. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24147. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24148. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  24149. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  24150. // buffers
  24151. var indices = [];
  24152. var vertices = [];
  24153. var normals = [];
  24154. var uvs = [];
  24155. // some helper variables
  24156. var segment;
  24157. var radius = innerRadius;
  24158. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  24159. var vertex = new Vector3();
  24160. var uv = new Vector2();
  24161. var j, i;
  24162. // generate vertices, normals and uvs
  24163. for ( j = 0; j <= phiSegments; j ++ ) {
  24164. for ( i = 0; i <= thetaSegments; i ++ ) {
  24165. // values are generate from the inside of the ring to the outside
  24166. segment = thetaStart + i / thetaSegments * thetaLength;
  24167. // vertex
  24168. vertex.x = radius * Math.cos( segment );
  24169. vertex.y = radius * Math.sin( segment );
  24170. vertices.push( vertex.x, vertex.y, vertex.z );
  24171. // normal
  24172. normals.push( 0, 0, 1 );
  24173. // uv
  24174. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  24175. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  24176. uvs.push( uv.x, uv.y );
  24177. }
  24178. // increase the radius for next row of vertices
  24179. radius += radiusStep;
  24180. }
  24181. // indices
  24182. for ( j = 0; j < phiSegments; j ++ ) {
  24183. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  24184. for ( i = 0; i < thetaSegments; i ++ ) {
  24185. segment = i + thetaSegmentLevel;
  24186. var a = segment;
  24187. var b = segment + thetaSegments + 1;
  24188. var c = segment + thetaSegments + 2;
  24189. var d = segment + 1;
  24190. // faces
  24191. indices.push( a, b, d );
  24192. indices.push( b, c, d );
  24193. }
  24194. }
  24195. // build geometry
  24196. this.setIndex( indices );
  24197. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24198. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24199. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24200. }
  24201. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24202. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  24203. /**
  24204. * @author zz85 / https://github.com/zz85
  24205. * @author bhouston / http://clara.io
  24206. * @author Mugen87 / https://github.com/Mugen87
  24207. */
  24208. // LatheGeometry
  24209. function LatheGeometry( points, segments, phiStart, phiLength ) {
  24210. Geometry.call( this );
  24211. this.type = 'LatheGeometry';
  24212. this.parameters = {
  24213. points: points,
  24214. segments: segments,
  24215. phiStart: phiStart,
  24216. phiLength: phiLength
  24217. };
  24218. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  24219. this.mergeVertices();
  24220. }
  24221. LatheGeometry.prototype = Object.create( Geometry.prototype );
  24222. LatheGeometry.prototype.constructor = LatheGeometry;
  24223. // LatheBufferGeometry
  24224. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  24225. BufferGeometry.call( this );
  24226. this.type = 'LatheBufferGeometry';
  24227. this.parameters = {
  24228. points: points,
  24229. segments: segments,
  24230. phiStart: phiStart,
  24231. phiLength: phiLength
  24232. };
  24233. segments = Math.floor( segments ) || 12;
  24234. phiStart = phiStart || 0;
  24235. phiLength = phiLength || Math.PI * 2;
  24236. // clamp phiLength so it's in range of [ 0, 2PI ]
  24237. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  24238. // buffers
  24239. var indices = [];
  24240. var vertices = [];
  24241. var uvs = [];
  24242. // helper variables
  24243. var base;
  24244. var inverseSegments = 1.0 / segments;
  24245. var vertex = new Vector3();
  24246. var uv = new Vector2();
  24247. var i, j;
  24248. // generate vertices and uvs
  24249. for ( i = 0; i <= segments; i ++ ) {
  24250. var phi = phiStart + i * inverseSegments * phiLength;
  24251. var sin = Math.sin( phi );
  24252. var cos = Math.cos( phi );
  24253. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  24254. // vertex
  24255. vertex.x = points[ j ].x * sin;
  24256. vertex.y = points[ j ].y;
  24257. vertex.z = points[ j ].x * cos;
  24258. vertices.push( vertex.x, vertex.y, vertex.z );
  24259. // uv
  24260. uv.x = i / segments;
  24261. uv.y = j / ( points.length - 1 );
  24262. uvs.push( uv.x, uv.y );
  24263. }
  24264. }
  24265. // indices
  24266. for ( i = 0; i < segments; i ++ ) {
  24267. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  24268. base = j + i * points.length;
  24269. var a = base;
  24270. var b = base + points.length;
  24271. var c = base + points.length + 1;
  24272. var d = base + 1;
  24273. // faces
  24274. indices.push( a, b, d );
  24275. indices.push( b, c, d );
  24276. }
  24277. }
  24278. // build geometry
  24279. this.setIndex( indices );
  24280. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24281. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24282. // generate normals
  24283. this.computeVertexNormals();
  24284. // if the geometry is closed, we need to average the normals along the seam.
  24285. // because the corresponding vertices are identical (but still have different UVs).
  24286. if ( phiLength === Math.PI * 2 ) {
  24287. var normals = this.attributes.normal.array;
  24288. var n1 = new Vector3();
  24289. var n2 = new Vector3();
  24290. var n = new Vector3();
  24291. // this is the buffer offset for the last line of vertices
  24292. base = segments * points.length * 3;
  24293. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  24294. // select the normal of the vertex in the first line
  24295. n1.x = normals[ j + 0 ];
  24296. n1.y = normals[ j + 1 ];
  24297. n1.z = normals[ j + 2 ];
  24298. // select the normal of the vertex in the last line
  24299. n2.x = normals[ base + j + 0 ];
  24300. n2.y = normals[ base + j + 1 ];
  24301. n2.z = normals[ base + j + 2 ];
  24302. // average normals
  24303. n.addVectors( n1, n2 ).normalize();
  24304. // assign the new values to both normals
  24305. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  24306. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  24307. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  24308. }
  24309. }
  24310. }
  24311. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24312. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  24313. /**
  24314. * @author jonobr1 / http://jonobr1.com
  24315. * @author Mugen87 / https://github.com/Mugen87
  24316. */
  24317. // ShapeGeometry
  24318. function ShapeGeometry( shapes, curveSegments ) {
  24319. Geometry.call( this );
  24320. this.type = 'ShapeGeometry';
  24321. if ( typeof curveSegments === 'object' ) {
  24322. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  24323. curveSegments = curveSegments.curveSegments;
  24324. }
  24325. this.parameters = {
  24326. shapes: shapes,
  24327. curveSegments: curveSegments
  24328. };
  24329. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  24330. this.mergeVertices();
  24331. }
  24332. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  24333. ShapeGeometry.prototype.constructor = ShapeGeometry;
  24334. ShapeGeometry.prototype.toJSON = function () {
  24335. var data = Geometry.prototype.toJSON.call( this );
  24336. var shapes = this.parameters.shapes;
  24337. return toJSON$1( shapes, data );
  24338. };
  24339. // ShapeBufferGeometry
  24340. function ShapeBufferGeometry( shapes, curveSegments ) {
  24341. BufferGeometry.call( this );
  24342. this.type = 'ShapeBufferGeometry';
  24343. this.parameters = {
  24344. shapes: shapes,
  24345. curveSegments: curveSegments
  24346. };
  24347. curveSegments = curveSegments || 12;
  24348. // buffers
  24349. var indices = [];
  24350. var vertices = [];
  24351. var normals = [];
  24352. var uvs = [];
  24353. // helper variables
  24354. var groupStart = 0;
  24355. var groupCount = 0;
  24356. // allow single and array values for "shapes" parameter
  24357. if ( Array.isArray( shapes ) === false ) {
  24358. addShape( shapes );
  24359. } else {
  24360. for ( var i = 0; i < shapes.length; i ++ ) {
  24361. addShape( shapes[ i ] );
  24362. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  24363. groupStart += groupCount;
  24364. groupCount = 0;
  24365. }
  24366. }
  24367. // build geometry
  24368. this.setIndex( indices );
  24369. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24370. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24371. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24372. // helper functions
  24373. function addShape( shape ) {
  24374. var i, l, shapeHole;
  24375. var indexOffset = vertices.length / 3;
  24376. var points = shape.extractPoints( curveSegments );
  24377. var shapeVertices = points.shape;
  24378. var shapeHoles = points.holes;
  24379. // check direction of vertices
  24380. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  24381. shapeVertices = shapeVertices.reverse();
  24382. }
  24383. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  24384. shapeHole = shapeHoles[ i ];
  24385. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  24386. shapeHoles[ i ] = shapeHole.reverse();
  24387. }
  24388. }
  24389. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  24390. // join vertices of inner and outer paths to a single array
  24391. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  24392. shapeHole = shapeHoles[ i ];
  24393. shapeVertices = shapeVertices.concat( shapeHole );
  24394. }
  24395. // vertices, normals, uvs
  24396. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  24397. var vertex = shapeVertices[ i ];
  24398. vertices.push( vertex.x, vertex.y, 0 );
  24399. normals.push( 0, 0, 1 );
  24400. uvs.push( vertex.x, vertex.y ); // world uvs
  24401. }
  24402. // incides
  24403. for ( i = 0, l = faces.length; i < l; i ++ ) {
  24404. var face = faces[ i ];
  24405. var a = face[ 0 ] + indexOffset;
  24406. var b = face[ 1 ] + indexOffset;
  24407. var c = face[ 2 ] + indexOffset;
  24408. indices.push( a, b, c );
  24409. groupCount += 3;
  24410. }
  24411. }
  24412. }
  24413. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24414. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  24415. ShapeBufferGeometry.prototype.toJSON = function () {
  24416. var data = BufferGeometry.prototype.toJSON.call( this );
  24417. var shapes = this.parameters.shapes;
  24418. return toJSON$1( shapes, data );
  24419. };
  24420. //
  24421. function toJSON$1( shapes, data ) {
  24422. data.shapes = [];
  24423. if ( Array.isArray( shapes ) ) {
  24424. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24425. var shape = shapes[ i ];
  24426. data.shapes.push( shape.uuid );
  24427. }
  24428. } else {
  24429. data.shapes.push( shapes.uuid );
  24430. }
  24431. return data;
  24432. }
  24433. /**
  24434. * @author WestLangley / http://github.com/WestLangley
  24435. * @author Mugen87 / https://github.com/Mugen87
  24436. */
  24437. function EdgesGeometry( geometry, thresholdAngle ) {
  24438. BufferGeometry.call( this );
  24439. this.type = 'EdgesGeometry';
  24440. this.parameters = {
  24441. thresholdAngle: thresholdAngle
  24442. };
  24443. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  24444. // buffer
  24445. var vertices = [];
  24446. // helper variables
  24447. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  24448. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  24449. var key, keys = [ 'a', 'b', 'c' ];
  24450. // prepare source geometry
  24451. var geometry2;
  24452. if ( geometry.isBufferGeometry ) {
  24453. geometry2 = new Geometry();
  24454. geometry2.fromBufferGeometry( geometry );
  24455. } else {
  24456. geometry2 = geometry.clone();
  24457. }
  24458. geometry2.mergeVertices();
  24459. geometry2.computeFaceNormals();
  24460. var sourceVertices = geometry2.vertices;
  24461. var faces = geometry2.faces;
  24462. // now create a data structure where each entry represents an edge with its adjoining faces
  24463. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24464. var face = faces[ i ];
  24465. for ( var j = 0; j < 3; j ++ ) {
  24466. edge1 = face[ keys[ j ] ];
  24467. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  24468. edge[ 0 ] = Math.min( edge1, edge2 );
  24469. edge[ 1 ] = Math.max( edge1, edge2 );
  24470. key = edge[ 0 ] + ',' + edge[ 1 ];
  24471. if ( edges[ key ] === undefined ) {
  24472. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  24473. } else {
  24474. edges[ key ].face2 = i;
  24475. }
  24476. }
  24477. }
  24478. // generate vertices
  24479. for ( key in edges ) {
  24480. var e = edges[ key ];
  24481. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  24482. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  24483. var vertex = sourceVertices[ e.index1 ];
  24484. vertices.push( vertex.x, vertex.y, vertex.z );
  24485. vertex = sourceVertices[ e.index2 ];
  24486. vertices.push( vertex.x, vertex.y, vertex.z );
  24487. }
  24488. }
  24489. // build geometry
  24490. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24491. }
  24492. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  24493. EdgesGeometry.prototype.constructor = EdgesGeometry;
  24494. /**
  24495. * @author mrdoob / http://mrdoob.com/
  24496. * @author Mugen87 / https://github.com/Mugen87
  24497. */
  24498. // CylinderGeometry
  24499. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  24500. Geometry.call( this );
  24501. this.type = 'CylinderGeometry';
  24502. this.parameters = {
  24503. radiusTop: radiusTop,
  24504. radiusBottom: radiusBottom,
  24505. height: height,
  24506. radialSegments: radialSegments,
  24507. heightSegments: heightSegments,
  24508. openEnded: openEnded,
  24509. thetaStart: thetaStart,
  24510. thetaLength: thetaLength
  24511. };
  24512. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  24513. this.mergeVertices();
  24514. }
  24515. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  24516. CylinderGeometry.prototype.constructor = CylinderGeometry;
  24517. // CylinderBufferGeometry
  24518. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  24519. BufferGeometry.call( this );
  24520. this.type = 'CylinderBufferGeometry';
  24521. this.parameters = {
  24522. radiusTop: radiusTop,
  24523. radiusBottom: radiusBottom,
  24524. height: height,
  24525. radialSegments: radialSegments,
  24526. heightSegments: heightSegments,
  24527. openEnded: openEnded,
  24528. thetaStart: thetaStart,
  24529. thetaLength: thetaLength
  24530. };
  24531. var scope = this;
  24532. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  24533. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  24534. height = height || 1;
  24535. radialSegments = Math.floor( radialSegments ) || 8;
  24536. heightSegments = Math.floor( heightSegments ) || 1;
  24537. openEnded = openEnded !== undefined ? openEnded : false;
  24538. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  24539. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24540. // buffers
  24541. var indices = [];
  24542. var vertices = [];
  24543. var normals = [];
  24544. var uvs = [];
  24545. // helper variables
  24546. var index = 0;
  24547. var indexArray = [];
  24548. var halfHeight = height / 2;
  24549. var groupStart = 0;
  24550. // generate geometry
  24551. generateTorso();
  24552. if ( openEnded === false ) {
  24553. if ( radiusTop > 0 ) { generateCap( true ); }
  24554. if ( radiusBottom > 0 ) { generateCap( false ); }
  24555. }
  24556. // build geometry
  24557. this.setIndex( indices );
  24558. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24559. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24560. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24561. function generateTorso() {
  24562. var x, y;
  24563. var normal = new Vector3();
  24564. var vertex = new Vector3();
  24565. var groupCount = 0;
  24566. // this will be used to calculate the normal
  24567. var slope = ( radiusBottom - radiusTop ) / height;
  24568. // generate vertices, normals and uvs
  24569. for ( y = 0; y <= heightSegments; y ++ ) {
  24570. var indexRow = [];
  24571. var v = y / heightSegments;
  24572. // calculate the radius of the current row
  24573. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  24574. for ( x = 0; x <= radialSegments; x ++ ) {
  24575. var u = x / radialSegments;
  24576. var theta = u * thetaLength + thetaStart;
  24577. var sinTheta = Math.sin( theta );
  24578. var cosTheta = Math.cos( theta );
  24579. // vertex
  24580. vertex.x = radius * sinTheta;
  24581. vertex.y = - v * height + halfHeight;
  24582. vertex.z = radius * cosTheta;
  24583. vertices.push( vertex.x, vertex.y, vertex.z );
  24584. // normal
  24585. normal.set( sinTheta, slope, cosTheta ).normalize();
  24586. normals.push( normal.x, normal.y, normal.z );
  24587. // uv
  24588. uvs.push( u, 1 - v );
  24589. // save index of vertex in respective row
  24590. indexRow.push( index ++ );
  24591. }
  24592. // now save vertices of the row in our index array
  24593. indexArray.push( indexRow );
  24594. }
  24595. // generate indices
  24596. for ( x = 0; x < radialSegments; x ++ ) {
  24597. for ( y = 0; y < heightSegments; y ++ ) {
  24598. // we use the index array to access the correct indices
  24599. var a = indexArray[ y ][ x ];
  24600. var b = indexArray[ y + 1 ][ x ];
  24601. var c = indexArray[ y + 1 ][ x + 1 ];
  24602. var d = indexArray[ y ][ x + 1 ];
  24603. // faces
  24604. indices.push( a, b, d );
  24605. indices.push( b, c, d );
  24606. // update group counter
  24607. groupCount += 6;
  24608. }
  24609. }
  24610. // add a group to the geometry. this will ensure multi material support
  24611. scope.addGroup( groupStart, groupCount, 0 );
  24612. // calculate new start value for groups
  24613. groupStart += groupCount;
  24614. }
  24615. function generateCap( top ) {
  24616. var x, centerIndexStart, centerIndexEnd;
  24617. var uv = new Vector2();
  24618. var vertex = new Vector3();
  24619. var groupCount = 0;
  24620. var radius = ( top === true ) ? radiusTop : radiusBottom;
  24621. var sign = ( top === true ) ? 1 : - 1;
  24622. // save the index of the first center vertex
  24623. centerIndexStart = index;
  24624. // first we generate the center vertex data of the cap.
  24625. // because the geometry needs one set of uvs per face,
  24626. // we must generate a center vertex per face/segment
  24627. for ( x = 1; x <= radialSegments; x ++ ) {
  24628. // vertex
  24629. vertices.push( 0, halfHeight * sign, 0 );
  24630. // normal
  24631. normals.push( 0, sign, 0 );
  24632. // uv
  24633. uvs.push( 0.5, 0.5 );
  24634. // increase index
  24635. index ++;
  24636. }
  24637. // save the index of the last center vertex
  24638. centerIndexEnd = index;
  24639. // now we generate the surrounding vertices, normals and uvs
  24640. for ( x = 0; x <= radialSegments; x ++ ) {
  24641. var u = x / radialSegments;
  24642. var theta = u * thetaLength + thetaStart;
  24643. var cosTheta = Math.cos( theta );
  24644. var sinTheta = Math.sin( theta );
  24645. // vertex
  24646. vertex.x = radius * sinTheta;
  24647. vertex.y = halfHeight * sign;
  24648. vertex.z = radius * cosTheta;
  24649. vertices.push( vertex.x, vertex.y, vertex.z );
  24650. // normal
  24651. normals.push( 0, sign, 0 );
  24652. // uv
  24653. uv.x = ( cosTheta * 0.5 ) + 0.5;
  24654. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  24655. uvs.push( uv.x, uv.y );
  24656. // increase index
  24657. index ++;
  24658. }
  24659. // generate indices
  24660. for ( x = 0; x < radialSegments; x ++ ) {
  24661. var c = centerIndexStart + x;
  24662. var i = centerIndexEnd + x;
  24663. if ( top === true ) {
  24664. // face top
  24665. indices.push( i, i + 1, c );
  24666. } else {
  24667. // face bottom
  24668. indices.push( i + 1, i, c );
  24669. }
  24670. groupCount += 3;
  24671. }
  24672. // add a group to the geometry. this will ensure multi material support
  24673. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  24674. // calculate new start value for groups
  24675. groupStart += groupCount;
  24676. }
  24677. }
  24678. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24679. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  24680. /**
  24681. * @author abelnation / http://github.com/abelnation
  24682. */
  24683. // ConeGeometry
  24684. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  24685. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  24686. this.type = 'ConeGeometry';
  24687. this.parameters = {
  24688. radius: radius,
  24689. height: height,
  24690. radialSegments: radialSegments,
  24691. heightSegments: heightSegments,
  24692. openEnded: openEnded,
  24693. thetaStart: thetaStart,
  24694. thetaLength: thetaLength
  24695. };
  24696. }
  24697. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  24698. ConeGeometry.prototype.constructor = ConeGeometry;
  24699. // ConeBufferGeometry
  24700. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  24701. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  24702. this.type = 'ConeBufferGeometry';
  24703. this.parameters = {
  24704. radius: radius,
  24705. height: height,
  24706. radialSegments: radialSegments,
  24707. heightSegments: heightSegments,
  24708. openEnded: openEnded,
  24709. thetaStart: thetaStart,
  24710. thetaLength: thetaLength
  24711. };
  24712. }
  24713. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  24714. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  24715. /**
  24716. * @author benaadams / https://twitter.com/ben_a_adams
  24717. * @author Mugen87 / https://github.com/Mugen87
  24718. * @author hughes
  24719. */
  24720. // CircleGeometry
  24721. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  24722. Geometry.call( this );
  24723. this.type = 'CircleGeometry';
  24724. this.parameters = {
  24725. radius: radius,
  24726. segments: segments,
  24727. thetaStart: thetaStart,
  24728. thetaLength: thetaLength
  24729. };
  24730. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  24731. this.mergeVertices();
  24732. }
  24733. CircleGeometry.prototype = Object.create( Geometry.prototype );
  24734. CircleGeometry.prototype.constructor = CircleGeometry;
  24735. // CircleBufferGeometry
  24736. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  24737. BufferGeometry.call( this );
  24738. this.type = 'CircleBufferGeometry';
  24739. this.parameters = {
  24740. radius: radius,
  24741. segments: segments,
  24742. thetaStart: thetaStart,
  24743. thetaLength: thetaLength
  24744. };
  24745. radius = radius || 1;
  24746. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  24747. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24748. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24749. // buffers
  24750. var indices = [];
  24751. var vertices = [];
  24752. var normals = [];
  24753. var uvs = [];
  24754. // helper variables
  24755. var i, s;
  24756. var vertex = new Vector3();
  24757. var uv = new Vector2();
  24758. // center point
  24759. vertices.push( 0, 0, 0 );
  24760. normals.push( 0, 0, 1 );
  24761. uvs.push( 0.5, 0.5 );
  24762. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  24763. var segment = thetaStart + s / segments * thetaLength;
  24764. // vertex
  24765. vertex.x = radius * Math.cos( segment );
  24766. vertex.y = radius * Math.sin( segment );
  24767. vertices.push( vertex.x, vertex.y, vertex.z );
  24768. // normal
  24769. normals.push( 0, 0, 1 );
  24770. // uvs
  24771. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  24772. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  24773. uvs.push( uv.x, uv.y );
  24774. }
  24775. // indices
  24776. for ( i = 1; i <= segments; i ++ ) {
  24777. indices.push( i, i + 1, 0 );
  24778. }
  24779. // build geometry
  24780. this.setIndex( indices );
  24781. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24782. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24783. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24784. }
  24785. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24786. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  24787. var Geometries = /*#__PURE__*/Object.freeze({
  24788. WireframeGeometry: WireframeGeometry,
  24789. ParametricGeometry: ParametricGeometry,
  24790. ParametricBufferGeometry: ParametricBufferGeometry,
  24791. TetrahedronGeometry: TetrahedronGeometry,
  24792. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  24793. OctahedronGeometry: OctahedronGeometry,
  24794. OctahedronBufferGeometry: OctahedronBufferGeometry,
  24795. IcosahedronGeometry: IcosahedronGeometry,
  24796. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  24797. DodecahedronGeometry: DodecahedronGeometry,
  24798. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  24799. PolyhedronGeometry: PolyhedronGeometry,
  24800. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  24801. TubeGeometry: TubeGeometry,
  24802. TubeBufferGeometry: TubeBufferGeometry,
  24803. TorusKnotGeometry: TorusKnotGeometry,
  24804. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  24805. TorusGeometry: TorusGeometry,
  24806. TorusBufferGeometry: TorusBufferGeometry,
  24807. TextGeometry: TextGeometry,
  24808. TextBufferGeometry: TextBufferGeometry,
  24809. SphereGeometry: SphereGeometry,
  24810. SphereBufferGeometry: SphereBufferGeometry,
  24811. RingGeometry: RingGeometry,
  24812. RingBufferGeometry: RingBufferGeometry,
  24813. PlaneGeometry: PlaneGeometry,
  24814. PlaneBufferGeometry: PlaneBufferGeometry,
  24815. LatheGeometry: LatheGeometry,
  24816. LatheBufferGeometry: LatheBufferGeometry,
  24817. ShapeGeometry: ShapeGeometry,
  24818. ShapeBufferGeometry: ShapeBufferGeometry,
  24819. ExtrudeGeometry: ExtrudeGeometry,
  24820. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  24821. EdgesGeometry: EdgesGeometry,
  24822. ConeGeometry: ConeGeometry,
  24823. ConeBufferGeometry: ConeBufferGeometry,
  24824. CylinderGeometry: CylinderGeometry,
  24825. CylinderBufferGeometry: CylinderBufferGeometry,
  24826. CircleGeometry: CircleGeometry,
  24827. CircleBufferGeometry: CircleBufferGeometry,
  24828. BoxGeometry: BoxGeometry,
  24829. BoxBufferGeometry: BoxBufferGeometry
  24830. });
  24831. /**
  24832. * @author mrdoob / http://mrdoob.com/
  24833. *
  24834. * parameters = {
  24835. * color: <THREE.Color>
  24836. * }
  24837. */
  24838. function ShadowMaterial( parameters ) {
  24839. Material.call( this );
  24840. this.type = 'ShadowMaterial';
  24841. this.color = new Color( 0x000000 );
  24842. this.transparent = true;
  24843. this.setValues( parameters );
  24844. }
  24845. ShadowMaterial.prototype = Object.create( Material.prototype );
  24846. ShadowMaterial.prototype.constructor = ShadowMaterial;
  24847. ShadowMaterial.prototype.isShadowMaterial = true;
  24848. ShadowMaterial.prototype.copy = function ( source ) {
  24849. Material.prototype.copy.call( this, source );
  24850. this.color.copy( source.color );
  24851. return this;
  24852. };
  24853. /**
  24854. * @author mrdoob / http://mrdoob.com/
  24855. */
  24856. function RawShaderMaterial( parameters ) {
  24857. ShaderMaterial.call( this, parameters );
  24858. this.type = 'RawShaderMaterial';
  24859. }
  24860. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  24861. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  24862. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  24863. /**
  24864. * @author WestLangley / http://github.com/WestLangley
  24865. *
  24866. * parameters = {
  24867. * color: <hex>,
  24868. * roughness: <float>,
  24869. * metalness: <float>,
  24870. * opacity: <float>,
  24871. *
  24872. * map: new THREE.Texture( <Image> ),
  24873. *
  24874. * lightMap: new THREE.Texture( <Image> ),
  24875. * lightMapIntensity: <float>
  24876. *
  24877. * aoMap: new THREE.Texture( <Image> ),
  24878. * aoMapIntensity: <float>
  24879. *
  24880. * emissive: <hex>,
  24881. * emissiveIntensity: <float>
  24882. * emissiveMap: new THREE.Texture( <Image> ),
  24883. *
  24884. * bumpMap: new THREE.Texture( <Image> ),
  24885. * bumpScale: <float>,
  24886. *
  24887. * normalMap: new THREE.Texture( <Image> ),
  24888. * normalMapType: THREE.TangentSpaceNormalMap,
  24889. * normalScale: <Vector2>,
  24890. *
  24891. * displacementMap: new THREE.Texture( <Image> ),
  24892. * displacementScale: <float>,
  24893. * displacementBias: <float>,
  24894. *
  24895. * roughnessMap: new THREE.Texture( <Image> ),
  24896. *
  24897. * metalnessMap: new THREE.Texture( <Image> ),
  24898. *
  24899. * alphaMap: new THREE.Texture( <Image> ),
  24900. *
  24901. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  24902. * envMapIntensity: <float>
  24903. *
  24904. * refractionRatio: <float>,
  24905. *
  24906. * wireframe: <boolean>,
  24907. * wireframeLinewidth: <float>,
  24908. *
  24909. * skinning: <bool>,
  24910. * morphTargets: <bool>,
  24911. * morphNormals: <bool>
  24912. * }
  24913. */
  24914. function MeshStandardMaterial( parameters ) {
  24915. Material.call( this );
  24916. this.defines = { 'STANDARD': '' };
  24917. this.type = 'MeshStandardMaterial';
  24918. this.color = new Color( 0xffffff ); // diffuse
  24919. this.roughness = 0.5;
  24920. this.metalness = 0.5;
  24921. this.map = null;
  24922. this.lightMap = null;
  24923. this.lightMapIntensity = 1.0;
  24924. this.aoMap = null;
  24925. this.aoMapIntensity = 1.0;
  24926. this.emissive = new Color( 0x000000 );
  24927. this.emissiveIntensity = 1.0;
  24928. this.emissiveMap = null;
  24929. this.bumpMap = null;
  24930. this.bumpScale = 1;
  24931. this.normalMap = null;
  24932. this.normalMapType = TangentSpaceNormalMap;
  24933. this.normalScale = new Vector2( 1, 1 );
  24934. this.displacementMap = null;
  24935. this.displacementScale = 1;
  24936. this.displacementBias = 0;
  24937. this.roughnessMap = null;
  24938. this.metalnessMap = null;
  24939. this.alphaMap = null;
  24940. this.envMap = null;
  24941. this.envMapIntensity = 1.0;
  24942. this.refractionRatio = 0.98;
  24943. this.wireframe = false;
  24944. this.wireframeLinewidth = 1;
  24945. this.wireframeLinecap = 'round';
  24946. this.wireframeLinejoin = 'round';
  24947. this.skinning = false;
  24948. this.morphTargets = false;
  24949. this.morphNormals = false;
  24950. this.setValues( parameters );
  24951. }
  24952. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  24953. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  24954. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  24955. MeshStandardMaterial.prototype.copy = function ( source ) {
  24956. Material.prototype.copy.call( this, source );
  24957. this.defines = { 'STANDARD': '' };
  24958. this.color.copy( source.color );
  24959. this.roughness = source.roughness;
  24960. this.metalness = source.metalness;
  24961. this.map = source.map;
  24962. this.lightMap = source.lightMap;
  24963. this.lightMapIntensity = source.lightMapIntensity;
  24964. this.aoMap = source.aoMap;
  24965. this.aoMapIntensity = source.aoMapIntensity;
  24966. this.emissive.copy( source.emissive );
  24967. this.emissiveMap = source.emissiveMap;
  24968. this.emissiveIntensity = source.emissiveIntensity;
  24969. this.bumpMap = source.bumpMap;
  24970. this.bumpScale = source.bumpScale;
  24971. this.normalMap = source.normalMap;
  24972. this.normalMapType = source.normalMapType;
  24973. this.normalScale.copy( source.normalScale );
  24974. this.displacementMap = source.displacementMap;
  24975. this.displacementScale = source.displacementScale;
  24976. this.displacementBias = source.displacementBias;
  24977. this.roughnessMap = source.roughnessMap;
  24978. this.metalnessMap = source.metalnessMap;
  24979. this.alphaMap = source.alphaMap;
  24980. this.envMap = source.envMap;
  24981. this.envMapIntensity = source.envMapIntensity;
  24982. this.refractionRatio = source.refractionRatio;
  24983. this.wireframe = source.wireframe;
  24984. this.wireframeLinewidth = source.wireframeLinewidth;
  24985. this.wireframeLinecap = source.wireframeLinecap;
  24986. this.wireframeLinejoin = source.wireframeLinejoin;
  24987. this.skinning = source.skinning;
  24988. this.morphTargets = source.morphTargets;
  24989. this.morphNormals = source.morphNormals;
  24990. return this;
  24991. };
  24992. /**
  24993. * @author WestLangley / http://github.com/WestLangley
  24994. *
  24995. * parameters = {
  24996. * reflectivity: <float>
  24997. * clearcoat: <float>
  24998. * clearcoatRoughness: <float>
  24999. *
  25000. * sheen: <Color>
  25001. *
  25002. * clearcoatNormalScale: <Vector2>,
  25003. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  25004. * }
  25005. */
  25006. function MeshPhysicalMaterial( parameters ) {
  25007. MeshStandardMaterial.call( this );
  25008. this.defines = {
  25009. 'STANDARD': '',
  25010. 'PHYSICAL': ''
  25011. };
  25012. this.type = 'MeshPhysicalMaterial';
  25013. this.reflectivity = 0.5; // maps to F0 = 0.04
  25014. this.clearcoat = 0.0;
  25015. this.clearcoatRoughness = 0.0;
  25016. this.sheen = null; // null will disable sheen bsdf
  25017. this.clearcoatNormalScale = new Vector2( 1, 1 );
  25018. this.clearcoatNormalMap = null;
  25019. this.transparency = 0.0;
  25020. this.setValues( parameters );
  25021. }
  25022. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  25023. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  25024. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  25025. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  25026. MeshStandardMaterial.prototype.copy.call( this, source );
  25027. this.defines = {
  25028. 'STANDARD': '',
  25029. 'PHYSICAL': ''
  25030. };
  25031. this.reflectivity = source.reflectivity;
  25032. this.clearcoat = source.clearcoat;
  25033. this.clearcoatRoughness = source.clearcoatRoughness;
  25034. if ( source.sheen ) { this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); }
  25035. else { this.sheen = null; }
  25036. this.clearcoatNormalMap = source.clearcoatNormalMap;
  25037. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  25038. this.transparency = source.transparency;
  25039. return this;
  25040. };
  25041. /**
  25042. * @author mrdoob / http://mrdoob.com/
  25043. * @author alteredq / http://alteredqualia.com/
  25044. *
  25045. * parameters = {
  25046. * color: <hex>,
  25047. * specular: <hex>,
  25048. * shininess: <float>,
  25049. * opacity: <float>,
  25050. *
  25051. * map: new THREE.Texture( <Image> ),
  25052. *
  25053. * lightMap: new THREE.Texture( <Image> ),
  25054. * lightMapIntensity: <float>
  25055. *
  25056. * aoMap: new THREE.Texture( <Image> ),
  25057. * aoMapIntensity: <float>
  25058. *
  25059. * emissive: <hex>,
  25060. * emissiveIntensity: <float>
  25061. * emissiveMap: new THREE.Texture( <Image> ),
  25062. *
  25063. * bumpMap: new THREE.Texture( <Image> ),
  25064. * bumpScale: <float>,
  25065. *
  25066. * normalMap: new THREE.Texture( <Image> ),
  25067. * normalMapType: THREE.TangentSpaceNormalMap,
  25068. * normalScale: <Vector2>,
  25069. *
  25070. * displacementMap: new THREE.Texture( <Image> ),
  25071. * displacementScale: <float>,
  25072. * displacementBias: <float>,
  25073. *
  25074. * specularMap: new THREE.Texture( <Image> ),
  25075. *
  25076. * alphaMap: new THREE.Texture( <Image> ),
  25077. *
  25078. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25079. * combine: THREE.Multiply,
  25080. * reflectivity: <float>,
  25081. * refractionRatio: <float>,
  25082. *
  25083. * wireframe: <boolean>,
  25084. * wireframeLinewidth: <float>,
  25085. *
  25086. * skinning: <bool>,
  25087. * morphTargets: <bool>,
  25088. * morphNormals: <bool>
  25089. * }
  25090. */
  25091. function MeshPhongMaterial( parameters ) {
  25092. Material.call( this );
  25093. this.type = 'MeshPhongMaterial';
  25094. this.color = new Color( 0xffffff ); // diffuse
  25095. this.specular = new Color( 0x111111 );
  25096. this.shininess = 30;
  25097. this.map = null;
  25098. this.lightMap = null;
  25099. this.lightMapIntensity = 1.0;
  25100. this.aoMap = null;
  25101. this.aoMapIntensity = 1.0;
  25102. this.emissive = new Color( 0x000000 );
  25103. this.emissiveIntensity = 1.0;
  25104. this.emissiveMap = null;
  25105. this.bumpMap = null;
  25106. this.bumpScale = 1;
  25107. this.normalMap = null;
  25108. this.normalMapType = TangentSpaceNormalMap;
  25109. this.normalScale = new Vector2( 1, 1 );
  25110. this.displacementMap = null;
  25111. this.displacementScale = 1;
  25112. this.displacementBias = 0;
  25113. this.specularMap = null;
  25114. this.alphaMap = null;
  25115. this.envMap = null;
  25116. this.combine = MultiplyOperation;
  25117. this.reflectivity = 1;
  25118. this.refractionRatio = 0.98;
  25119. this.wireframe = false;
  25120. this.wireframeLinewidth = 1;
  25121. this.wireframeLinecap = 'round';
  25122. this.wireframeLinejoin = 'round';
  25123. this.skinning = false;
  25124. this.morphTargets = false;
  25125. this.morphNormals = false;
  25126. this.setValues( parameters );
  25127. }
  25128. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  25129. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  25130. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  25131. MeshPhongMaterial.prototype.copy = function ( source ) {
  25132. Material.prototype.copy.call( this, source );
  25133. this.color.copy( source.color );
  25134. this.specular.copy( source.specular );
  25135. this.shininess = source.shininess;
  25136. this.map = source.map;
  25137. this.lightMap = source.lightMap;
  25138. this.lightMapIntensity = source.lightMapIntensity;
  25139. this.aoMap = source.aoMap;
  25140. this.aoMapIntensity = source.aoMapIntensity;
  25141. this.emissive.copy( source.emissive );
  25142. this.emissiveMap = source.emissiveMap;
  25143. this.emissiveIntensity = source.emissiveIntensity;
  25144. this.bumpMap = source.bumpMap;
  25145. this.bumpScale = source.bumpScale;
  25146. this.normalMap = source.normalMap;
  25147. this.normalMapType = source.normalMapType;
  25148. this.normalScale.copy( source.normalScale );
  25149. this.displacementMap = source.displacementMap;
  25150. this.displacementScale = source.displacementScale;
  25151. this.displacementBias = source.displacementBias;
  25152. this.specularMap = source.specularMap;
  25153. this.alphaMap = source.alphaMap;
  25154. this.envMap = source.envMap;
  25155. this.combine = source.combine;
  25156. this.reflectivity = source.reflectivity;
  25157. this.refractionRatio = source.refractionRatio;
  25158. this.wireframe = source.wireframe;
  25159. this.wireframeLinewidth = source.wireframeLinewidth;
  25160. this.wireframeLinecap = source.wireframeLinecap;
  25161. this.wireframeLinejoin = source.wireframeLinejoin;
  25162. this.skinning = source.skinning;
  25163. this.morphTargets = source.morphTargets;
  25164. this.morphNormals = source.morphNormals;
  25165. return this;
  25166. };
  25167. /**
  25168. * @author takahirox / http://github.com/takahirox
  25169. *
  25170. * parameters = {
  25171. * gradientMap: new THREE.Texture( <Image> )
  25172. * }
  25173. */
  25174. function MeshToonMaterial( parameters ) {
  25175. MeshPhongMaterial.call( this );
  25176. this.defines = { 'TOON': '' };
  25177. this.type = 'MeshToonMaterial';
  25178. this.gradientMap = null;
  25179. this.setValues( parameters );
  25180. }
  25181. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  25182. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  25183. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  25184. MeshToonMaterial.prototype.copy = function ( source ) {
  25185. MeshPhongMaterial.prototype.copy.call( this, source );
  25186. this.gradientMap = source.gradientMap;
  25187. return this;
  25188. };
  25189. /**
  25190. * @author mrdoob / http://mrdoob.com/
  25191. * @author WestLangley / http://github.com/WestLangley
  25192. *
  25193. * parameters = {
  25194. * opacity: <float>,
  25195. *
  25196. * bumpMap: new THREE.Texture( <Image> ),
  25197. * bumpScale: <float>,
  25198. *
  25199. * normalMap: new THREE.Texture( <Image> ),
  25200. * normalMapType: THREE.TangentSpaceNormalMap,
  25201. * normalScale: <Vector2>,
  25202. *
  25203. * displacementMap: new THREE.Texture( <Image> ),
  25204. * displacementScale: <float>,
  25205. * displacementBias: <float>,
  25206. *
  25207. * wireframe: <boolean>,
  25208. * wireframeLinewidth: <float>
  25209. *
  25210. * skinning: <bool>,
  25211. * morphTargets: <bool>,
  25212. * morphNormals: <bool>
  25213. * }
  25214. */
  25215. function MeshNormalMaterial( parameters ) {
  25216. Material.call( this );
  25217. this.type = 'MeshNormalMaterial';
  25218. this.bumpMap = null;
  25219. this.bumpScale = 1;
  25220. this.normalMap = null;
  25221. this.normalMapType = TangentSpaceNormalMap;
  25222. this.normalScale = new Vector2( 1, 1 );
  25223. this.displacementMap = null;
  25224. this.displacementScale = 1;
  25225. this.displacementBias = 0;
  25226. this.wireframe = false;
  25227. this.wireframeLinewidth = 1;
  25228. this.fog = false;
  25229. this.lights = false;
  25230. this.skinning = false;
  25231. this.morphTargets = false;
  25232. this.morphNormals = false;
  25233. this.setValues( parameters );
  25234. }
  25235. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  25236. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  25237. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  25238. MeshNormalMaterial.prototype.copy = function ( source ) {
  25239. Material.prototype.copy.call( this, source );
  25240. this.bumpMap = source.bumpMap;
  25241. this.bumpScale = source.bumpScale;
  25242. this.normalMap = source.normalMap;
  25243. this.normalMapType = source.normalMapType;
  25244. this.normalScale.copy( source.normalScale );
  25245. this.displacementMap = source.displacementMap;
  25246. this.displacementScale = source.displacementScale;
  25247. this.displacementBias = source.displacementBias;
  25248. this.wireframe = source.wireframe;
  25249. this.wireframeLinewidth = source.wireframeLinewidth;
  25250. this.skinning = source.skinning;
  25251. this.morphTargets = source.morphTargets;
  25252. this.morphNormals = source.morphNormals;
  25253. return this;
  25254. };
  25255. /**
  25256. * @author mrdoob / http://mrdoob.com/
  25257. * @author alteredq / http://alteredqualia.com/
  25258. *
  25259. * parameters = {
  25260. * color: <hex>,
  25261. * opacity: <float>,
  25262. *
  25263. * map: new THREE.Texture( <Image> ),
  25264. *
  25265. * lightMap: new THREE.Texture( <Image> ),
  25266. * lightMapIntensity: <float>
  25267. *
  25268. * aoMap: new THREE.Texture( <Image> ),
  25269. * aoMapIntensity: <float>
  25270. *
  25271. * emissive: <hex>,
  25272. * emissiveIntensity: <float>
  25273. * emissiveMap: new THREE.Texture( <Image> ),
  25274. *
  25275. * specularMap: new THREE.Texture( <Image> ),
  25276. *
  25277. * alphaMap: new THREE.Texture( <Image> ),
  25278. *
  25279. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25280. * combine: THREE.Multiply,
  25281. * reflectivity: <float>,
  25282. * refractionRatio: <float>,
  25283. *
  25284. * wireframe: <boolean>,
  25285. * wireframeLinewidth: <float>,
  25286. *
  25287. * skinning: <bool>,
  25288. * morphTargets: <bool>,
  25289. * morphNormals: <bool>
  25290. * }
  25291. */
  25292. function MeshLambertMaterial( parameters ) {
  25293. Material.call( this );
  25294. this.type = 'MeshLambertMaterial';
  25295. this.color = new Color( 0xffffff ); // diffuse
  25296. this.map = null;
  25297. this.lightMap = null;
  25298. this.lightMapIntensity = 1.0;
  25299. this.aoMap = null;
  25300. this.aoMapIntensity = 1.0;
  25301. this.emissive = new Color( 0x000000 );
  25302. this.emissiveIntensity = 1.0;
  25303. this.emissiveMap = null;
  25304. this.specularMap = null;
  25305. this.alphaMap = null;
  25306. this.envMap = null;
  25307. this.combine = MultiplyOperation;
  25308. this.reflectivity = 1;
  25309. this.refractionRatio = 0.98;
  25310. this.wireframe = false;
  25311. this.wireframeLinewidth = 1;
  25312. this.wireframeLinecap = 'round';
  25313. this.wireframeLinejoin = 'round';
  25314. this.skinning = false;
  25315. this.morphTargets = false;
  25316. this.morphNormals = false;
  25317. this.setValues( parameters );
  25318. }
  25319. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  25320. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  25321. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  25322. MeshLambertMaterial.prototype.copy = function ( source ) {
  25323. Material.prototype.copy.call( this, source );
  25324. this.color.copy( source.color );
  25325. this.map = source.map;
  25326. this.lightMap = source.lightMap;
  25327. this.lightMapIntensity = source.lightMapIntensity;
  25328. this.aoMap = source.aoMap;
  25329. this.aoMapIntensity = source.aoMapIntensity;
  25330. this.emissive.copy( source.emissive );
  25331. this.emissiveMap = source.emissiveMap;
  25332. this.emissiveIntensity = source.emissiveIntensity;
  25333. this.specularMap = source.specularMap;
  25334. this.alphaMap = source.alphaMap;
  25335. this.envMap = source.envMap;
  25336. this.combine = source.combine;
  25337. this.reflectivity = source.reflectivity;
  25338. this.refractionRatio = source.refractionRatio;
  25339. this.wireframe = source.wireframe;
  25340. this.wireframeLinewidth = source.wireframeLinewidth;
  25341. this.wireframeLinecap = source.wireframeLinecap;
  25342. this.wireframeLinejoin = source.wireframeLinejoin;
  25343. this.skinning = source.skinning;
  25344. this.morphTargets = source.morphTargets;
  25345. this.morphNormals = source.morphNormals;
  25346. return this;
  25347. };
  25348. /**
  25349. * @author WestLangley / http://github.com/WestLangley
  25350. *
  25351. * parameters = {
  25352. * color: <hex>,
  25353. * opacity: <float>,
  25354. *
  25355. * matcap: new THREE.Texture( <Image> ),
  25356. *
  25357. * map: new THREE.Texture( <Image> ),
  25358. *
  25359. * bumpMap: new THREE.Texture( <Image> ),
  25360. * bumpScale: <float>,
  25361. *
  25362. * normalMap: new THREE.Texture( <Image> ),
  25363. * normalMapType: THREE.TangentSpaceNormalMap,
  25364. * normalScale: <Vector2>,
  25365. *
  25366. * displacementMap: new THREE.Texture( <Image> ),
  25367. * displacementScale: <float>,
  25368. * displacementBias: <float>,
  25369. *
  25370. * alphaMap: new THREE.Texture( <Image> ),
  25371. *
  25372. * skinning: <bool>,
  25373. * morphTargets: <bool>,
  25374. * morphNormals: <bool>
  25375. * }
  25376. */
  25377. function MeshMatcapMaterial( parameters ) {
  25378. Material.call( this );
  25379. this.defines = { 'MATCAP': '' };
  25380. this.type = 'MeshMatcapMaterial';
  25381. this.color = new Color( 0xffffff ); // diffuse
  25382. this.matcap = null;
  25383. this.map = null;
  25384. this.bumpMap = null;
  25385. this.bumpScale = 1;
  25386. this.normalMap = null;
  25387. this.normalMapType = TangentSpaceNormalMap;
  25388. this.normalScale = new Vector2( 1, 1 );
  25389. this.displacementMap = null;
  25390. this.displacementScale = 1;
  25391. this.displacementBias = 0;
  25392. this.alphaMap = null;
  25393. this.skinning = false;
  25394. this.morphTargets = false;
  25395. this.morphNormals = false;
  25396. this.lights = false;
  25397. this.setValues( parameters );
  25398. }
  25399. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  25400. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  25401. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  25402. MeshMatcapMaterial.prototype.copy = function ( source ) {
  25403. Material.prototype.copy.call( this, source );
  25404. this.defines = { 'MATCAP': '' };
  25405. this.color.copy( source.color );
  25406. this.matcap = source.matcap;
  25407. this.map = source.map;
  25408. this.bumpMap = source.bumpMap;
  25409. this.bumpScale = source.bumpScale;
  25410. this.normalMap = source.normalMap;
  25411. this.normalMapType = source.normalMapType;
  25412. this.normalScale.copy( source.normalScale );
  25413. this.displacementMap = source.displacementMap;
  25414. this.displacementScale = source.displacementScale;
  25415. this.displacementBias = source.displacementBias;
  25416. this.alphaMap = source.alphaMap;
  25417. this.skinning = source.skinning;
  25418. this.morphTargets = source.morphTargets;
  25419. this.morphNormals = source.morphNormals;
  25420. return this;
  25421. };
  25422. /**
  25423. * @author alteredq / http://alteredqualia.com/
  25424. *
  25425. * parameters = {
  25426. * color: <hex>,
  25427. * opacity: <float>,
  25428. *
  25429. * linewidth: <float>,
  25430. *
  25431. * scale: <float>,
  25432. * dashSize: <float>,
  25433. * gapSize: <float>
  25434. * }
  25435. */
  25436. function LineDashedMaterial( parameters ) {
  25437. LineBasicMaterial.call( this );
  25438. this.type = 'LineDashedMaterial';
  25439. this.scale = 1;
  25440. this.dashSize = 3;
  25441. this.gapSize = 1;
  25442. this.setValues( parameters );
  25443. }
  25444. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  25445. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  25446. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  25447. LineDashedMaterial.prototype.copy = function ( source ) {
  25448. LineBasicMaterial.prototype.copy.call( this, source );
  25449. this.scale = source.scale;
  25450. this.dashSize = source.dashSize;
  25451. this.gapSize = source.gapSize;
  25452. return this;
  25453. };
  25454. var Materials = /*#__PURE__*/Object.freeze({
  25455. ShadowMaterial: ShadowMaterial,
  25456. SpriteMaterial: SpriteMaterial,
  25457. RawShaderMaterial: RawShaderMaterial,
  25458. ShaderMaterial: ShaderMaterial,
  25459. PointsMaterial: PointsMaterial,
  25460. MeshPhysicalMaterial: MeshPhysicalMaterial,
  25461. MeshStandardMaterial: MeshStandardMaterial,
  25462. MeshPhongMaterial: MeshPhongMaterial,
  25463. MeshToonMaterial: MeshToonMaterial,
  25464. MeshNormalMaterial: MeshNormalMaterial,
  25465. MeshLambertMaterial: MeshLambertMaterial,
  25466. MeshDepthMaterial: MeshDepthMaterial,
  25467. MeshDistanceMaterial: MeshDistanceMaterial,
  25468. MeshBasicMaterial: MeshBasicMaterial,
  25469. MeshMatcapMaterial: MeshMatcapMaterial,
  25470. LineDashedMaterial: LineDashedMaterial,
  25471. LineBasicMaterial: LineBasicMaterial,
  25472. Material: Material
  25473. });
  25474. /**
  25475. * @author tschw
  25476. * @author Ben Houston / http://clara.io/
  25477. * @author David Sarno / http://lighthaus.us/
  25478. */
  25479. var AnimationUtils = {
  25480. // same as Array.prototype.slice, but also works on typed arrays
  25481. arraySlice: function ( array, from, to ) {
  25482. if ( AnimationUtils.isTypedArray( array ) ) {
  25483. // in ios9 array.subarray(from, undefined) will return empty array
  25484. // but array.subarray(from) or array.subarray(from, len) is correct
  25485. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  25486. }
  25487. return array.slice( from, to );
  25488. },
  25489. // converts an array to a specific type
  25490. convertArray: function ( array, type, forceClone ) {
  25491. if ( ! array || // let 'undefined' and 'null' pass
  25492. ! forceClone && array.constructor === type ) { return array; }
  25493. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  25494. return new type( array ); // create typed array
  25495. }
  25496. return Array.prototype.slice.call( array ); // create Array
  25497. },
  25498. isTypedArray: function ( object ) {
  25499. return ArrayBuffer.isView( object ) &&
  25500. ! ( object instanceof DataView );
  25501. },
  25502. // returns an array by which times and values can be sorted
  25503. getKeyframeOrder: function ( times ) {
  25504. function compareTime( i, j ) {
  25505. return times[ i ] - times[ j ];
  25506. }
  25507. var n = times.length;
  25508. var result = new Array( n );
  25509. for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; }
  25510. result.sort( compareTime );
  25511. return result;
  25512. },
  25513. // uses the array previously returned by 'getKeyframeOrder' to sort data
  25514. sortedArray: function ( values, stride, order ) {
  25515. var nValues = values.length;
  25516. var result = new values.constructor( nValues );
  25517. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  25518. var srcOffset = order[ i ] * stride;
  25519. for ( var j = 0; j !== stride; ++ j ) {
  25520. result[ dstOffset ++ ] = values[ srcOffset + j ];
  25521. }
  25522. }
  25523. return result;
  25524. },
  25525. // function for parsing AOS keyframe formats
  25526. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  25527. var i = 1, key = jsonKeys[ 0 ];
  25528. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  25529. key = jsonKeys[ i ++ ];
  25530. }
  25531. if ( key === undefined ) { return; } // no data
  25532. var value = key[ valuePropertyName ];
  25533. if ( value === undefined ) { return; } // no data
  25534. if ( Array.isArray( value ) ) {
  25535. do {
  25536. value = key[ valuePropertyName ];
  25537. if ( value !== undefined ) {
  25538. times.push( key.time );
  25539. values.push.apply( values, value ); // push all elements
  25540. }
  25541. key = jsonKeys[ i ++ ];
  25542. } while ( key !== undefined );
  25543. } else if ( value.toArray !== undefined ) {
  25544. // ...assume THREE.Math-ish
  25545. do {
  25546. value = key[ valuePropertyName ];
  25547. if ( value !== undefined ) {
  25548. times.push( key.time );
  25549. value.toArray( values, values.length );
  25550. }
  25551. key = jsonKeys[ i ++ ];
  25552. } while ( key !== undefined );
  25553. } else {
  25554. // otherwise push as-is
  25555. do {
  25556. value = key[ valuePropertyName ];
  25557. if ( value !== undefined ) {
  25558. times.push( key.time );
  25559. values.push( value );
  25560. }
  25561. key = jsonKeys[ i ++ ];
  25562. } while ( key !== undefined );
  25563. }
  25564. }
  25565. };
  25566. /**
  25567. * Abstract base class of interpolants over parametric samples.
  25568. *
  25569. * The parameter domain is one dimensional, typically the time or a path
  25570. * along a curve defined by the data.
  25571. *
  25572. * The sample values can have any dimensionality and derived classes may
  25573. * apply special interpretations to the data.
  25574. *
  25575. * This class provides the interval seek in a Template Method, deferring
  25576. * the actual interpolation to derived classes.
  25577. *
  25578. * Time complexity is O(1) for linear access crossing at most two points
  25579. * and O(log N) for random access, where N is the number of positions.
  25580. *
  25581. * References:
  25582. *
  25583. * http://www.oodesign.com/template-method-pattern.html
  25584. *
  25585. * @author tschw
  25586. */
  25587. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25588. this.parameterPositions = parameterPositions;
  25589. this._cachedIndex = 0;
  25590. this.resultBuffer = resultBuffer !== undefined ?
  25591. resultBuffer : new sampleValues.constructor( sampleSize );
  25592. this.sampleValues = sampleValues;
  25593. this.valueSize = sampleSize;
  25594. }
  25595. Object.assign( Interpolant.prototype, {
  25596. evaluate: function ( t ) {
  25597. var pp = this.parameterPositions,
  25598. i1 = this._cachedIndex,
  25599. t1 = pp[ i1 ],
  25600. t0 = pp[ i1 - 1 ];
  25601. validate_interval: {
  25602. seek: {
  25603. var right;
  25604. linear_scan: {
  25605. //- See http://jsperf.com/comparison-to-undefined/3
  25606. //- slower code:
  25607. //-
  25608. //- if ( t >= t1 || t1 === undefined ) {
  25609. forward_scan: if ( ! ( t < t1 ) ) {
  25610. for ( var giveUpAt = i1 + 2; ; ) {
  25611. if ( t1 === undefined ) {
  25612. if ( t < t0 ) { break forward_scan; }
  25613. // after end
  25614. i1 = pp.length;
  25615. this._cachedIndex = i1;
  25616. return this.afterEnd_( i1 - 1, t, t0 );
  25617. }
  25618. if ( i1 === giveUpAt ) { break; } // this loop
  25619. t0 = t1;
  25620. t1 = pp[ ++ i1 ];
  25621. if ( t < t1 ) {
  25622. // we have arrived at the sought interval
  25623. break seek;
  25624. }
  25625. }
  25626. // prepare binary search on the right side of the index
  25627. right = pp.length;
  25628. break linear_scan;
  25629. }
  25630. //- slower code:
  25631. //- if ( t < t0 || t0 === undefined ) {
  25632. if ( ! ( t >= t0 ) ) {
  25633. // looping?
  25634. var t1global = pp[ 1 ];
  25635. if ( t < t1global ) {
  25636. i1 = 2; // + 1, using the scan for the details
  25637. t0 = t1global;
  25638. }
  25639. // linear reverse scan
  25640. for ( var giveUpAt = i1 - 2; ; ) {
  25641. if ( t0 === undefined ) {
  25642. // before start
  25643. this._cachedIndex = 0;
  25644. return this.beforeStart_( 0, t, t1 );
  25645. }
  25646. if ( i1 === giveUpAt ) { break; } // this loop
  25647. t1 = t0;
  25648. t0 = pp[ -- i1 - 1 ];
  25649. if ( t >= t0 ) {
  25650. // we have arrived at the sought interval
  25651. break seek;
  25652. }
  25653. }
  25654. // prepare binary search on the left side of the index
  25655. right = i1;
  25656. i1 = 0;
  25657. break linear_scan;
  25658. }
  25659. // the interval is valid
  25660. break validate_interval;
  25661. } // linear scan
  25662. // binary search
  25663. while ( i1 < right ) {
  25664. var mid = ( i1 + right ) >>> 1;
  25665. if ( t < pp[ mid ] ) {
  25666. right = mid;
  25667. } else {
  25668. i1 = mid + 1;
  25669. }
  25670. }
  25671. t1 = pp[ i1 ];
  25672. t0 = pp[ i1 - 1 ];
  25673. // check boundary cases, again
  25674. if ( t0 === undefined ) {
  25675. this._cachedIndex = 0;
  25676. return this.beforeStart_( 0, t, t1 );
  25677. }
  25678. if ( t1 === undefined ) {
  25679. i1 = pp.length;
  25680. this._cachedIndex = i1;
  25681. return this.afterEnd_( i1 - 1, t0, t );
  25682. }
  25683. } // seek
  25684. this._cachedIndex = i1;
  25685. this.intervalChanged_( i1, t0, t1 );
  25686. } // validate_interval
  25687. return this.interpolate_( i1, t0, t, t1 );
  25688. },
  25689. settings: null, // optional, subclass-specific settings structure
  25690. // Note: The indirection allows central control of many interpolants.
  25691. // --- Protected interface
  25692. DefaultSettings_: {},
  25693. getSettings_: function () {
  25694. return this.settings || this.DefaultSettings_;
  25695. },
  25696. copySampleValue_: function ( index ) {
  25697. // copies a sample value to the result buffer
  25698. var result = this.resultBuffer,
  25699. values = this.sampleValues,
  25700. stride = this.valueSize,
  25701. offset = index * stride;
  25702. for ( var i = 0; i !== stride; ++ i ) {
  25703. result[ i ] = values[ offset + i ];
  25704. }
  25705. return result;
  25706. },
  25707. // Template methods for derived classes:
  25708. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  25709. throw new Error( 'call to abstract method' );
  25710. // implementations shall return this.resultBuffer
  25711. },
  25712. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  25713. // empty
  25714. }
  25715. } );
  25716. //!\ DECLARE ALIAS AFTER assign prototype !
  25717. Object.assign( Interpolant.prototype, {
  25718. //( 0, t, t0 ), returns this.resultBuffer
  25719. beforeStart_: Interpolant.prototype.copySampleValue_,
  25720. //( N-1, tN-1, t ), returns this.resultBuffer
  25721. afterEnd_: Interpolant.prototype.copySampleValue_,
  25722. } );
  25723. /**
  25724. * Fast and simple cubic spline interpolant.
  25725. *
  25726. * It was derived from a Hermitian construction setting the first derivative
  25727. * at each sample position to the linear slope between neighboring positions
  25728. * over their parameter interval.
  25729. *
  25730. * @author tschw
  25731. */
  25732. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25733. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  25734. this._weightPrev = - 0;
  25735. this._offsetPrev = - 0;
  25736. this._weightNext = - 0;
  25737. this._offsetNext = - 0;
  25738. }
  25739. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25740. constructor: CubicInterpolant,
  25741. DefaultSettings_: {
  25742. endingStart: ZeroCurvatureEnding,
  25743. endingEnd: ZeroCurvatureEnding
  25744. },
  25745. intervalChanged_: function ( i1, t0, t1 ) {
  25746. var pp = this.parameterPositions,
  25747. iPrev = i1 - 2,
  25748. iNext = i1 + 1,
  25749. tPrev = pp[ iPrev ],
  25750. tNext = pp[ iNext ];
  25751. if ( tPrev === undefined ) {
  25752. switch ( this.getSettings_().endingStart ) {
  25753. case ZeroSlopeEnding:
  25754. // f'(t0) = 0
  25755. iPrev = i1;
  25756. tPrev = 2 * t0 - t1;
  25757. break;
  25758. case WrapAroundEnding:
  25759. // use the other end of the curve
  25760. iPrev = pp.length - 2;
  25761. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  25762. break;
  25763. default: // ZeroCurvatureEnding
  25764. // f''(t0) = 0 a.k.a. Natural Spline
  25765. iPrev = i1;
  25766. tPrev = t1;
  25767. }
  25768. }
  25769. if ( tNext === undefined ) {
  25770. switch ( this.getSettings_().endingEnd ) {
  25771. case ZeroSlopeEnding:
  25772. // f'(tN) = 0
  25773. iNext = i1;
  25774. tNext = 2 * t1 - t0;
  25775. break;
  25776. case WrapAroundEnding:
  25777. // use the other end of the curve
  25778. iNext = 1;
  25779. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  25780. break;
  25781. default: // ZeroCurvatureEnding
  25782. // f''(tN) = 0, a.k.a. Natural Spline
  25783. iNext = i1 - 1;
  25784. tNext = t0;
  25785. }
  25786. }
  25787. var halfDt = ( t1 - t0 ) * 0.5,
  25788. stride = this.valueSize;
  25789. this._weightPrev = halfDt / ( t0 - tPrev );
  25790. this._weightNext = halfDt / ( tNext - t1 );
  25791. this._offsetPrev = iPrev * stride;
  25792. this._offsetNext = iNext * stride;
  25793. },
  25794. interpolate_: function ( i1, t0, t, t1 ) {
  25795. var result = this.resultBuffer,
  25796. values = this.sampleValues,
  25797. stride = this.valueSize,
  25798. o1 = i1 * stride, o0 = o1 - stride,
  25799. oP = this._offsetPrev, oN = this._offsetNext,
  25800. wP = this._weightPrev, wN = this._weightNext,
  25801. p = ( t - t0 ) / ( t1 - t0 ),
  25802. pp = p * p,
  25803. ppp = pp * p;
  25804. // evaluate polynomials
  25805. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  25806. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  25807. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  25808. var sN = wN * ppp - wN * pp;
  25809. // combine data linearly
  25810. for ( var i = 0; i !== stride; ++ i ) {
  25811. result[ i ] =
  25812. sP * values[ oP + i ] +
  25813. s0 * values[ o0 + i ] +
  25814. s1 * values[ o1 + i ] +
  25815. sN * values[ oN + i ];
  25816. }
  25817. return result;
  25818. }
  25819. } );
  25820. /**
  25821. * @author tschw
  25822. */
  25823. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25824. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  25825. }
  25826. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25827. constructor: LinearInterpolant,
  25828. interpolate_: function ( i1, t0, t, t1 ) {
  25829. var result = this.resultBuffer,
  25830. values = this.sampleValues,
  25831. stride = this.valueSize,
  25832. offset1 = i1 * stride,
  25833. offset0 = offset1 - stride,
  25834. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25835. weight0 = 1 - weight1;
  25836. for ( var i = 0; i !== stride; ++ i ) {
  25837. result[ i ] =
  25838. values[ offset0 + i ] * weight0 +
  25839. values[ offset1 + i ] * weight1;
  25840. }
  25841. return result;
  25842. }
  25843. } );
  25844. /**
  25845. *
  25846. * Interpolant that evaluates to the sample value at the position preceeding
  25847. * the parameter.
  25848. *
  25849. * @author tschw
  25850. */
  25851. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25852. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  25853. }
  25854. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  25855. constructor: DiscreteInterpolant,
  25856. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  25857. return this.copySampleValue_( i1 - 1 );
  25858. }
  25859. } );
  25860. /**
  25861. *
  25862. * A timed sequence of keyframes for a specific property.
  25863. *
  25864. *
  25865. * @author Ben Houston / http://clara.io/
  25866. * @author David Sarno / http://lighthaus.us/
  25867. * @author tschw
  25868. */
  25869. function KeyframeTrack( name, times, values, interpolation ) {
  25870. if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); }
  25871. if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); }
  25872. this.name = name;
  25873. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  25874. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  25875. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25876. }
  25877. // Static methods
  25878. Object.assign( KeyframeTrack, {
  25879. // Serialization (in static context, because of constructor invocation
  25880. // and automatic invocation of .toJSON):
  25881. toJSON: function ( track ) {
  25882. var trackType = track.constructor;
  25883. var json;
  25884. // derived classes can define a static toJSON method
  25885. if ( trackType.toJSON !== undefined ) {
  25886. json = trackType.toJSON( track );
  25887. } else {
  25888. // by default, we assume the data can be serialized as-is
  25889. json = {
  25890. 'name': track.name,
  25891. 'times': AnimationUtils.convertArray( track.times, Array ),
  25892. 'values': AnimationUtils.convertArray( track.values, Array )
  25893. };
  25894. var interpolation = track.getInterpolation();
  25895. if ( interpolation !== track.DefaultInterpolation ) {
  25896. json.interpolation = interpolation;
  25897. }
  25898. }
  25899. json.type = track.ValueTypeName; // mandatory
  25900. return json;
  25901. }
  25902. } );
  25903. Object.assign( KeyframeTrack.prototype, {
  25904. constructor: KeyframeTrack,
  25905. TimeBufferType: Float32Array,
  25906. ValueBufferType: Float32Array,
  25907. DefaultInterpolation: InterpolateLinear,
  25908. InterpolantFactoryMethodDiscrete: function ( result ) {
  25909. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25910. },
  25911. InterpolantFactoryMethodLinear: function ( result ) {
  25912. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25913. },
  25914. InterpolantFactoryMethodSmooth: function ( result ) {
  25915. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25916. },
  25917. setInterpolation: function ( interpolation ) {
  25918. var factoryMethod;
  25919. switch ( interpolation ) {
  25920. case InterpolateDiscrete:
  25921. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25922. break;
  25923. case InterpolateLinear:
  25924. factoryMethod = this.InterpolantFactoryMethodLinear;
  25925. break;
  25926. case InterpolateSmooth:
  25927. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25928. break;
  25929. }
  25930. if ( factoryMethod === undefined ) {
  25931. var message = "unsupported interpolation for " +
  25932. this.ValueTypeName + " keyframe track named " + this.name;
  25933. if ( this.createInterpolant === undefined ) {
  25934. // fall back to default, unless the default itself is messed up
  25935. if ( interpolation !== this.DefaultInterpolation ) {
  25936. this.setInterpolation( this.DefaultInterpolation );
  25937. } else {
  25938. throw new Error( message ); // fatal, in this case
  25939. }
  25940. }
  25941. console.warn( 'THREE.KeyframeTrack:', message );
  25942. return this;
  25943. }
  25944. this.createInterpolant = factoryMethod;
  25945. return this;
  25946. },
  25947. getInterpolation: function () {
  25948. switch ( this.createInterpolant ) {
  25949. case this.InterpolantFactoryMethodDiscrete:
  25950. return InterpolateDiscrete;
  25951. case this.InterpolantFactoryMethodLinear:
  25952. return InterpolateLinear;
  25953. case this.InterpolantFactoryMethodSmooth:
  25954. return InterpolateSmooth;
  25955. }
  25956. },
  25957. getValueSize: function () {
  25958. return this.values.length / this.times.length;
  25959. },
  25960. // move all keyframes either forwards or backwards in time
  25961. shift: function ( timeOffset ) {
  25962. if ( timeOffset !== 0.0 ) {
  25963. var times = this.times;
  25964. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25965. times[ i ] += timeOffset;
  25966. }
  25967. }
  25968. return this;
  25969. },
  25970. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25971. scale: function ( timeScale ) {
  25972. if ( timeScale !== 1.0 ) {
  25973. var times = this.times;
  25974. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25975. times[ i ] *= timeScale;
  25976. }
  25977. }
  25978. return this;
  25979. },
  25980. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25981. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25982. trim: function ( startTime, endTime ) {
  25983. var times = this.times,
  25984. nKeys = times.length,
  25985. from = 0,
  25986. to = nKeys - 1;
  25987. while ( from !== nKeys && times[ from ] < startTime ) {
  25988. ++ from;
  25989. }
  25990. while ( to !== - 1 && times[ to ] > endTime ) {
  25991. -- to;
  25992. }
  25993. ++ to; // inclusive -> exclusive bound
  25994. if ( from !== 0 || to !== nKeys ) {
  25995. // empty tracks are forbidden, so keep at least one keyframe
  25996. if ( from >= to ) { to = Math.max( to, 1 ), from = to - 1; }
  25997. var stride = this.getValueSize();
  25998. this.times = AnimationUtils.arraySlice( times, from, to );
  25999. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  26000. }
  26001. return this;
  26002. },
  26003. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  26004. validate: function () {
  26005. var valid = true;
  26006. var valueSize = this.getValueSize();
  26007. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  26008. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  26009. valid = false;
  26010. }
  26011. var times = this.times,
  26012. values = this.values,
  26013. nKeys = times.length;
  26014. if ( nKeys === 0 ) {
  26015. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  26016. valid = false;
  26017. }
  26018. var prevTime = null;
  26019. for ( var i = 0; i !== nKeys; i ++ ) {
  26020. var currTime = times[ i ];
  26021. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  26022. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  26023. valid = false;
  26024. break;
  26025. }
  26026. if ( prevTime !== null && prevTime > currTime ) {
  26027. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  26028. valid = false;
  26029. break;
  26030. }
  26031. prevTime = currTime;
  26032. }
  26033. if ( values !== undefined ) {
  26034. if ( AnimationUtils.isTypedArray( values ) ) {
  26035. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  26036. var value = values[ i ];
  26037. if ( isNaN( value ) ) {
  26038. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  26039. valid = false;
  26040. break;
  26041. }
  26042. }
  26043. }
  26044. }
  26045. return valid;
  26046. },
  26047. // removes equivalent sequential keys as common in morph target sequences
  26048. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  26049. optimize: function () {
  26050. var times = this.times,
  26051. values = this.values,
  26052. stride = this.getValueSize(),
  26053. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  26054. writeIndex = 1,
  26055. lastIndex = times.length - 1;
  26056. for ( var i = 1; i < lastIndex; ++ i ) {
  26057. var keep = false;
  26058. var time = times[ i ];
  26059. var timeNext = times[ i + 1 ];
  26060. // remove adjacent keyframes scheduled at the same time
  26061. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  26062. if ( ! smoothInterpolation ) {
  26063. // remove unnecessary keyframes same as their neighbors
  26064. var offset = i * stride,
  26065. offsetP = offset - stride,
  26066. offsetN = offset + stride;
  26067. for ( var j = 0; j !== stride; ++ j ) {
  26068. var value = values[ offset + j ];
  26069. if ( value !== values[ offsetP + j ] ||
  26070. value !== values[ offsetN + j ] ) {
  26071. keep = true;
  26072. break;
  26073. }
  26074. }
  26075. } else {
  26076. keep = true;
  26077. }
  26078. }
  26079. // in-place compaction
  26080. if ( keep ) {
  26081. if ( i !== writeIndex ) {
  26082. times[ writeIndex ] = times[ i ];
  26083. var readOffset = i * stride,
  26084. writeOffset = writeIndex * stride;
  26085. for ( var j = 0; j !== stride; ++ j ) {
  26086. values[ writeOffset + j ] = values[ readOffset + j ];
  26087. }
  26088. }
  26089. ++ writeIndex;
  26090. }
  26091. }
  26092. // flush last keyframe (compaction looks ahead)
  26093. if ( lastIndex > 0 ) {
  26094. times[ writeIndex ] = times[ lastIndex ];
  26095. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  26096. values[ writeOffset + j ] = values[ readOffset + j ];
  26097. }
  26098. ++ writeIndex;
  26099. }
  26100. if ( writeIndex !== times.length ) {
  26101. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  26102. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  26103. }
  26104. return this;
  26105. },
  26106. clone: function () {
  26107. var times = AnimationUtils.arraySlice( this.times, 0 );
  26108. var values = AnimationUtils.arraySlice( this.values, 0 );
  26109. var TypedKeyframeTrack = this.constructor;
  26110. var track = new TypedKeyframeTrack( this.name, times, values );
  26111. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  26112. track.createInterpolant = this.createInterpolant;
  26113. return track;
  26114. }
  26115. } );
  26116. /**
  26117. *
  26118. * A Track of Boolean keyframe values.
  26119. *
  26120. *
  26121. * @author Ben Houston / http://clara.io/
  26122. * @author David Sarno / http://lighthaus.us/
  26123. * @author tschw
  26124. */
  26125. function BooleanKeyframeTrack( name, times, values ) {
  26126. KeyframeTrack.call( this, name, times, values );
  26127. }
  26128. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26129. constructor: BooleanKeyframeTrack,
  26130. ValueTypeName: 'bool',
  26131. ValueBufferType: Array,
  26132. DefaultInterpolation: InterpolateDiscrete,
  26133. InterpolantFactoryMethodLinear: undefined,
  26134. InterpolantFactoryMethodSmooth: undefined
  26135. // Note: Actually this track could have a optimized / compressed
  26136. // representation of a single value and a custom interpolant that
  26137. // computes "firstValue ^ isOdd( index )".
  26138. } );
  26139. /**
  26140. *
  26141. * A Track of keyframe values that represent color.
  26142. *
  26143. *
  26144. * @author Ben Houston / http://clara.io/
  26145. * @author David Sarno / http://lighthaus.us/
  26146. * @author tschw
  26147. */
  26148. function ColorKeyframeTrack( name, times, values, interpolation ) {
  26149. KeyframeTrack.call( this, name, times, values, interpolation );
  26150. }
  26151. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26152. constructor: ColorKeyframeTrack,
  26153. ValueTypeName: 'color'
  26154. // ValueBufferType is inherited
  26155. // DefaultInterpolation is inherited
  26156. // Note: Very basic implementation and nothing special yet.
  26157. // However, this is the place for color space parameterization.
  26158. } );
  26159. /**
  26160. *
  26161. * A Track of numeric keyframe values.
  26162. *
  26163. * @author Ben Houston / http://clara.io/
  26164. * @author David Sarno / http://lighthaus.us/
  26165. * @author tschw
  26166. */
  26167. function NumberKeyframeTrack( name, times, values, interpolation ) {
  26168. KeyframeTrack.call( this, name, times, values, interpolation );
  26169. }
  26170. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26171. constructor: NumberKeyframeTrack,
  26172. ValueTypeName: 'number'
  26173. // ValueBufferType is inherited
  26174. // DefaultInterpolation is inherited
  26175. } );
  26176. /**
  26177. * Spherical linear unit quaternion interpolant.
  26178. *
  26179. * @author tschw
  26180. */
  26181. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26182. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26183. }
  26184. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26185. constructor: QuaternionLinearInterpolant,
  26186. interpolate_: function ( i1, t0, t, t1 ) {
  26187. var result = this.resultBuffer,
  26188. values = this.sampleValues,
  26189. stride = this.valueSize,
  26190. offset = i1 * stride,
  26191. alpha = ( t - t0 ) / ( t1 - t0 );
  26192. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  26193. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  26194. }
  26195. return result;
  26196. }
  26197. } );
  26198. /**
  26199. *
  26200. * A Track of quaternion keyframe values.
  26201. *
  26202. * @author Ben Houston / http://clara.io/
  26203. * @author David Sarno / http://lighthaus.us/
  26204. * @author tschw
  26205. */
  26206. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  26207. KeyframeTrack.call( this, name, times, values, interpolation );
  26208. }
  26209. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26210. constructor: QuaternionKeyframeTrack,
  26211. ValueTypeName: 'quaternion',
  26212. // ValueBufferType is inherited
  26213. DefaultInterpolation: InterpolateLinear,
  26214. InterpolantFactoryMethodLinear: function ( result ) {
  26215. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  26216. },
  26217. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  26218. } );
  26219. /**
  26220. *
  26221. * A Track that interpolates Strings
  26222. *
  26223. *
  26224. * @author Ben Houston / http://clara.io/
  26225. * @author David Sarno / http://lighthaus.us/
  26226. * @author tschw
  26227. */
  26228. function StringKeyframeTrack( name, times, values, interpolation ) {
  26229. KeyframeTrack.call( this, name, times, values, interpolation );
  26230. }
  26231. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26232. constructor: StringKeyframeTrack,
  26233. ValueTypeName: 'string',
  26234. ValueBufferType: Array,
  26235. DefaultInterpolation: InterpolateDiscrete,
  26236. InterpolantFactoryMethodLinear: undefined,
  26237. InterpolantFactoryMethodSmooth: undefined
  26238. } );
  26239. /**
  26240. *
  26241. * A Track of vectored keyframe values.
  26242. *
  26243. *
  26244. * @author Ben Houston / http://clara.io/
  26245. * @author David Sarno / http://lighthaus.us/
  26246. * @author tschw
  26247. */
  26248. function VectorKeyframeTrack( name, times, values, interpolation ) {
  26249. KeyframeTrack.call( this, name, times, values, interpolation );
  26250. }
  26251. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26252. constructor: VectorKeyframeTrack,
  26253. ValueTypeName: 'vector'
  26254. // ValueBufferType is inherited
  26255. // DefaultInterpolation is inherited
  26256. } );
  26257. /**
  26258. *
  26259. * Reusable set of Tracks that represent an animation.
  26260. *
  26261. * @author Ben Houston / http://clara.io/
  26262. * @author David Sarno / http://lighthaus.us/
  26263. */
  26264. function AnimationClip( name, duration, tracks ) {
  26265. this.name = name;
  26266. this.tracks = tracks;
  26267. this.duration = ( duration !== undefined ) ? duration : - 1;
  26268. this.uuid = _Math.generateUUID();
  26269. // this means it should figure out its duration by scanning the tracks
  26270. if ( this.duration < 0 ) {
  26271. this.resetDuration();
  26272. }
  26273. }
  26274. function getTrackTypeForValueTypeName( typeName ) {
  26275. switch ( typeName.toLowerCase() ) {
  26276. case 'scalar':
  26277. case 'double':
  26278. case 'float':
  26279. case 'number':
  26280. case 'integer':
  26281. return NumberKeyframeTrack;
  26282. case 'vector':
  26283. case 'vector2':
  26284. case 'vector3':
  26285. case 'vector4':
  26286. return VectorKeyframeTrack;
  26287. case 'color':
  26288. return ColorKeyframeTrack;
  26289. case 'quaternion':
  26290. return QuaternionKeyframeTrack;
  26291. case 'bool':
  26292. case 'boolean':
  26293. return BooleanKeyframeTrack;
  26294. case 'string':
  26295. return StringKeyframeTrack;
  26296. }
  26297. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  26298. }
  26299. function parseKeyframeTrack( json ) {
  26300. if ( json.type === undefined ) {
  26301. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  26302. }
  26303. var trackType = getTrackTypeForValueTypeName( json.type );
  26304. if ( json.times === undefined ) {
  26305. var times = [], values = [];
  26306. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  26307. json.times = times;
  26308. json.values = values;
  26309. }
  26310. // derived classes can define a static parse method
  26311. if ( trackType.parse !== undefined ) {
  26312. return trackType.parse( json );
  26313. } else {
  26314. // by default, we assume a constructor compatible with the base
  26315. return new trackType( json.name, json.times, json.values, json.interpolation );
  26316. }
  26317. }
  26318. Object.assign( AnimationClip, {
  26319. parse: function ( json ) {
  26320. var tracks = [],
  26321. jsonTracks = json.tracks,
  26322. frameTime = 1.0 / ( json.fps || 1.0 );
  26323. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  26324. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  26325. }
  26326. return new AnimationClip( json.name, json.duration, tracks );
  26327. },
  26328. toJSON: function ( clip ) {
  26329. var tracks = [],
  26330. clipTracks = clip.tracks;
  26331. var json = {
  26332. 'name': clip.name,
  26333. 'duration': clip.duration,
  26334. 'tracks': tracks,
  26335. 'uuid': clip.uuid
  26336. };
  26337. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  26338. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  26339. }
  26340. return json;
  26341. },
  26342. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  26343. var numMorphTargets = morphTargetSequence.length;
  26344. var tracks = [];
  26345. for ( var i = 0; i < numMorphTargets; i ++ ) {
  26346. var times = [];
  26347. var values = [];
  26348. times.push(
  26349. ( i + numMorphTargets - 1 ) % numMorphTargets,
  26350. i,
  26351. ( i + 1 ) % numMorphTargets );
  26352. values.push( 0, 1, 0 );
  26353. var order = AnimationUtils.getKeyframeOrder( times );
  26354. times = AnimationUtils.sortedArray( times, 1, order );
  26355. values = AnimationUtils.sortedArray( values, 1, order );
  26356. // if there is a key at the first frame, duplicate it as the
  26357. // last frame as well for perfect loop.
  26358. if ( ! noLoop && times[ 0 ] === 0 ) {
  26359. times.push( numMorphTargets );
  26360. values.push( values[ 0 ] );
  26361. }
  26362. tracks.push(
  26363. new NumberKeyframeTrack(
  26364. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  26365. times, values
  26366. ).scale( 1.0 / fps ) );
  26367. }
  26368. return new AnimationClip( name, - 1, tracks );
  26369. },
  26370. findByName: function ( objectOrClipArray, name ) {
  26371. var clipArray = objectOrClipArray;
  26372. if ( ! Array.isArray( objectOrClipArray ) ) {
  26373. var o = objectOrClipArray;
  26374. clipArray = o.geometry && o.geometry.animations || o.animations;
  26375. }
  26376. for ( var i = 0; i < clipArray.length; i ++ ) {
  26377. if ( clipArray[ i ].name === name ) {
  26378. return clipArray[ i ];
  26379. }
  26380. }
  26381. return null;
  26382. },
  26383. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  26384. var animationToMorphTargets = {};
  26385. // tested with https://regex101.com/ on trick sequences
  26386. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  26387. var pattern = /^([\w-]*?)([\d]+)$/;
  26388. // sort morph target names into animation groups based
  26389. // patterns like Walk_001, Walk_002, Run_001, Run_002
  26390. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  26391. var morphTarget = morphTargets[ i ];
  26392. var parts = morphTarget.name.match( pattern );
  26393. if ( parts && parts.length > 1 ) {
  26394. var name = parts[ 1 ];
  26395. var animationMorphTargets = animationToMorphTargets[ name ];
  26396. if ( ! animationMorphTargets ) {
  26397. animationToMorphTargets[ name ] = animationMorphTargets = [];
  26398. }
  26399. animationMorphTargets.push( morphTarget );
  26400. }
  26401. }
  26402. var clips = [];
  26403. for ( var name in animationToMorphTargets ) {
  26404. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  26405. }
  26406. return clips;
  26407. },
  26408. // parse the animation.hierarchy format
  26409. parseAnimation: function ( animation, bones ) {
  26410. if ( ! animation ) {
  26411. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  26412. return null;
  26413. }
  26414. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  26415. // only return track if there are actually keys.
  26416. if ( animationKeys.length !== 0 ) {
  26417. var times = [];
  26418. var values = [];
  26419. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  26420. // empty keys are filtered out, so check again
  26421. if ( times.length !== 0 ) {
  26422. destTracks.push( new trackType( trackName, times, values ) );
  26423. }
  26424. }
  26425. };
  26426. var tracks = [];
  26427. var clipName = animation.name || 'default';
  26428. // automatic length determination in AnimationClip.
  26429. var duration = animation.length || - 1;
  26430. var fps = animation.fps || 30;
  26431. var hierarchyTracks = animation.hierarchy || [];
  26432. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  26433. var animationKeys = hierarchyTracks[ h ].keys;
  26434. // skip empty tracks
  26435. if ( ! animationKeys || animationKeys.length === 0 ) { continue; }
  26436. // process morph targets
  26437. if ( animationKeys[ 0 ].morphTargets ) {
  26438. // figure out all morph targets used in this track
  26439. var morphTargetNames = {};
  26440. for ( var k = 0; k < animationKeys.length; k ++ ) {
  26441. if ( animationKeys[ k ].morphTargets ) {
  26442. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  26443. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  26444. }
  26445. }
  26446. }
  26447. // create a track for each morph target with all zero
  26448. // morphTargetInfluences except for the keys in which
  26449. // the morphTarget is named.
  26450. for ( var morphTargetName in morphTargetNames ) {
  26451. var times = [];
  26452. var values = [];
  26453. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  26454. var animationKey = animationKeys[ k ];
  26455. times.push( animationKey.time );
  26456. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  26457. }
  26458. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  26459. }
  26460. duration = morphTargetNames.length * ( fps || 1.0 );
  26461. } else {
  26462. // ...assume skeletal animation
  26463. var boneName = '.bones[' + bones[ h ].name + ']';
  26464. addNonemptyTrack(
  26465. VectorKeyframeTrack, boneName + '.position',
  26466. animationKeys, 'pos', tracks );
  26467. addNonemptyTrack(
  26468. QuaternionKeyframeTrack, boneName + '.quaternion',
  26469. animationKeys, 'rot', tracks );
  26470. addNonemptyTrack(
  26471. VectorKeyframeTrack, boneName + '.scale',
  26472. animationKeys, 'scl', tracks );
  26473. }
  26474. }
  26475. if ( tracks.length === 0 ) {
  26476. return null;
  26477. }
  26478. var clip = new AnimationClip( clipName, duration, tracks );
  26479. return clip;
  26480. }
  26481. } );
  26482. Object.assign( AnimationClip.prototype, {
  26483. resetDuration: function () {
  26484. var tracks = this.tracks, duration = 0;
  26485. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  26486. var track = this.tracks[ i ];
  26487. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  26488. }
  26489. this.duration = duration;
  26490. return this;
  26491. },
  26492. trim: function () {
  26493. for ( var i = 0; i < this.tracks.length; i ++ ) {
  26494. this.tracks[ i ].trim( 0, this.duration );
  26495. }
  26496. return this;
  26497. },
  26498. validate: function () {
  26499. var valid = true;
  26500. for ( var i = 0; i < this.tracks.length; i ++ ) {
  26501. valid = valid && this.tracks[ i ].validate();
  26502. }
  26503. return valid;
  26504. },
  26505. optimize: function () {
  26506. for ( var i = 0; i < this.tracks.length; i ++ ) {
  26507. this.tracks[ i ].optimize();
  26508. }
  26509. return this;
  26510. },
  26511. clone: function () {
  26512. var tracks = [];
  26513. for ( var i = 0; i < this.tracks.length; i ++ ) {
  26514. tracks.push( this.tracks[ i ].clone() );
  26515. }
  26516. return new AnimationClip( this.name, this.duration, tracks );
  26517. }
  26518. } );
  26519. /**
  26520. * @author mrdoob / http://mrdoob.com/
  26521. */
  26522. var Cache = {
  26523. enabled: false,
  26524. files: {},
  26525. add: function ( key, file ) {
  26526. if ( this.enabled === false ) { return; }
  26527. // console.log( 'THREE.Cache', 'Adding key:', key );
  26528. this.files[ key ] = file;
  26529. },
  26530. get: function ( key ) {
  26531. if ( this.enabled === false ) { return; }
  26532. // console.log( 'THREE.Cache', 'Checking key:', key );
  26533. return this.files[ key ];
  26534. },
  26535. remove: function ( key ) {
  26536. delete this.files[ key ];
  26537. },
  26538. clear: function () {
  26539. this.files = {};
  26540. }
  26541. };
  26542. /**
  26543. * @author mrdoob / http://mrdoob.com/
  26544. */
  26545. function LoadingManager( onLoad, onProgress, onError ) {
  26546. var scope = this;
  26547. var isLoading = false;
  26548. var itemsLoaded = 0;
  26549. var itemsTotal = 0;
  26550. var urlModifier = undefined;
  26551. var handlers = [];
  26552. // Refer to #5689 for the reason why we don't set .onStart
  26553. // in the constructor
  26554. this.onStart = undefined;
  26555. this.onLoad = onLoad;
  26556. this.onProgress = onProgress;
  26557. this.onError = onError;
  26558. this.itemStart = function ( url ) {
  26559. itemsTotal ++;
  26560. if ( isLoading === false ) {
  26561. if ( scope.onStart !== undefined ) {
  26562. scope.onStart( url, itemsLoaded, itemsTotal );
  26563. }
  26564. }
  26565. isLoading = true;
  26566. };
  26567. this.itemEnd = function ( url ) {
  26568. itemsLoaded ++;
  26569. if ( scope.onProgress !== undefined ) {
  26570. scope.onProgress( url, itemsLoaded, itemsTotal );
  26571. }
  26572. if ( itemsLoaded === itemsTotal ) {
  26573. isLoading = false;
  26574. if ( scope.onLoad !== undefined ) {
  26575. scope.onLoad();
  26576. }
  26577. }
  26578. };
  26579. this.itemError = function ( url ) {
  26580. if ( scope.onError !== undefined ) {
  26581. scope.onError( url );
  26582. }
  26583. };
  26584. this.resolveURL = function ( url ) {
  26585. if ( urlModifier ) {
  26586. return urlModifier( url );
  26587. }
  26588. return url;
  26589. };
  26590. this.setURLModifier = function ( transform ) {
  26591. urlModifier = transform;
  26592. return this;
  26593. };
  26594. this.addHandler = function ( regex, loader ) {
  26595. handlers.push( regex, loader );
  26596. return this;
  26597. };
  26598. this.removeHandler = function ( regex ) {
  26599. var index = handlers.indexOf( regex );
  26600. if ( index !== - 1 ) {
  26601. handlers.splice( index, 2 );
  26602. }
  26603. return this;
  26604. };
  26605. this.getHandler = function ( file ) {
  26606. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  26607. var regex = handlers[ i ];
  26608. var loader = handlers[ i + 1 ];
  26609. if ( regex.test( file ) ) {
  26610. return loader;
  26611. }
  26612. }
  26613. return null;
  26614. };
  26615. }
  26616. var DefaultLoadingManager = new LoadingManager();
  26617. /**
  26618. * @author alteredq / http://alteredqualia.com/
  26619. */
  26620. function Loader( manager ) {
  26621. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26622. this.crossOrigin = 'anonymous';
  26623. this.path = '';
  26624. this.resourcePath = '';
  26625. }
  26626. Object.assign( Loader.prototype, {
  26627. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  26628. parse: function ( /* data */ ) {},
  26629. setCrossOrigin: function ( crossOrigin ) {
  26630. this.crossOrigin = crossOrigin;
  26631. return this;
  26632. },
  26633. setPath: function ( path ) {
  26634. this.path = path;
  26635. return this;
  26636. },
  26637. setResourcePath: function ( resourcePath ) {
  26638. this.resourcePath = resourcePath;
  26639. return this;
  26640. }
  26641. } );
  26642. /**
  26643. * @author mrdoob / http://mrdoob.com/
  26644. */
  26645. var loading = {};
  26646. function FileLoader( manager ) {
  26647. Loader.call( this, manager );
  26648. }
  26649. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26650. constructor: FileLoader,
  26651. load: function ( url, onLoad, onProgress, onError ) {
  26652. if ( url === undefined ) { url = ''; }
  26653. if ( this.path !== undefined ) { url = this.path + url; }
  26654. url = this.manager.resolveURL( url );
  26655. var scope = this;
  26656. var cached = Cache.get( url );
  26657. if ( cached !== undefined ) {
  26658. scope.manager.itemStart( url );
  26659. setTimeout( function () {
  26660. if ( onLoad ) { onLoad( cached ); }
  26661. scope.manager.itemEnd( url );
  26662. }, 0 );
  26663. return cached;
  26664. }
  26665. // Check if request is duplicate
  26666. if ( loading[ url ] !== undefined ) {
  26667. loading[ url ].push( {
  26668. onLoad: onLoad,
  26669. onProgress: onProgress,
  26670. onError: onError
  26671. } );
  26672. return;
  26673. }
  26674. // Check for data: URI
  26675. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  26676. var dataUriRegexResult = url.match( dataUriRegex );
  26677. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  26678. if ( dataUriRegexResult ) {
  26679. var mimeType = dataUriRegexResult[ 1 ];
  26680. var isBase64 = !! dataUriRegexResult[ 2 ];
  26681. var data = dataUriRegexResult[ 3 ];
  26682. data = decodeURIComponent( data );
  26683. if ( isBase64 ) { data = atob( data ); }
  26684. try {
  26685. var response;
  26686. var responseType = ( this.responseType || '' ).toLowerCase();
  26687. switch ( responseType ) {
  26688. case 'arraybuffer':
  26689. case 'blob':
  26690. var view = new Uint8Array( data.length );
  26691. for ( var i = 0; i < data.length; i ++ ) {
  26692. view[ i ] = data.charCodeAt( i );
  26693. }
  26694. if ( responseType === 'blob' ) {
  26695. response = new Blob( [ view.buffer ], { type: mimeType } );
  26696. } else {
  26697. response = view.buffer;
  26698. }
  26699. break;
  26700. case 'document':
  26701. var parser = new DOMParser();
  26702. response = parser.parseFromString( data, mimeType );
  26703. break;
  26704. case 'json':
  26705. response = JSON.parse( data );
  26706. break;
  26707. default: // 'text' or other
  26708. response = data;
  26709. break;
  26710. }
  26711. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  26712. setTimeout( function () {
  26713. if ( onLoad ) { onLoad( response ); }
  26714. scope.manager.itemEnd( url );
  26715. }, 0 );
  26716. } catch ( error ) {
  26717. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  26718. setTimeout( function () {
  26719. if ( onError ) { onError( error ); }
  26720. scope.manager.itemError( url );
  26721. scope.manager.itemEnd( url );
  26722. }, 0 );
  26723. }
  26724. } else {
  26725. // Initialise array for duplicate requests
  26726. loading[ url ] = [];
  26727. loading[ url ].push( {
  26728. onLoad: onLoad,
  26729. onProgress: onProgress,
  26730. onError: onError
  26731. } );
  26732. var request = new XMLHttpRequest();
  26733. request.open( 'GET', url, true );
  26734. request.addEventListener( 'load', function ( event ) {
  26735. var response = this.response;
  26736. Cache.add( url, response );
  26737. var callbacks = loading[ url ];
  26738. delete loading[ url ];
  26739. if ( this.status === 200 || this.status === 0 ) {
  26740. // Some browsers return HTTP Status 0 when using non-http protocol
  26741. // e.g. 'file://' or 'data://'. Handle as success.
  26742. if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); }
  26743. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  26744. var callback = callbacks[ i ];
  26745. if ( callback.onLoad ) { callback.onLoad( response ); }
  26746. }
  26747. scope.manager.itemEnd( url );
  26748. } else {
  26749. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  26750. var callback = callbacks[ i ];
  26751. if ( callback.onError ) { callback.onError( event ); }
  26752. }
  26753. scope.manager.itemError( url );
  26754. scope.manager.itemEnd( url );
  26755. }
  26756. }, false );
  26757. request.addEventListener( 'progress', function ( event ) {
  26758. var callbacks = loading[ url ];
  26759. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  26760. var callback = callbacks[ i ];
  26761. if ( callback.onProgress ) { callback.onProgress( event ); }
  26762. }
  26763. }, false );
  26764. request.addEventListener( 'error', function ( event ) {
  26765. var callbacks = loading[ url ];
  26766. delete loading[ url ];
  26767. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  26768. var callback = callbacks[ i ];
  26769. if ( callback.onError ) { callback.onError( event ); }
  26770. }
  26771. scope.manager.itemError( url );
  26772. scope.manager.itemEnd( url );
  26773. }, false );
  26774. request.addEventListener( 'abort', function ( event ) {
  26775. var callbacks = loading[ url ];
  26776. delete loading[ url ];
  26777. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  26778. var callback = callbacks[ i ];
  26779. if ( callback.onError ) { callback.onError( event ); }
  26780. }
  26781. scope.manager.itemError( url );
  26782. scope.manager.itemEnd( url );
  26783. }, false );
  26784. if ( this.responseType !== undefined ) { request.responseType = this.responseType; }
  26785. if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; }
  26786. if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); }
  26787. for ( var header in this.requestHeader ) {
  26788. request.setRequestHeader( header, this.requestHeader[ header ] );
  26789. }
  26790. request.send( null );
  26791. }
  26792. scope.manager.itemStart( url );
  26793. return request;
  26794. },
  26795. setResponseType: function ( value ) {
  26796. this.responseType = value;
  26797. return this;
  26798. },
  26799. setWithCredentials: function ( value ) {
  26800. this.withCredentials = value;
  26801. return this;
  26802. },
  26803. setMimeType: function ( value ) {
  26804. this.mimeType = value;
  26805. return this;
  26806. },
  26807. setRequestHeader: function ( value ) {
  26808. this.requestHeader = value;
  26809. return this;
  26810. }
  26811. } );
  26812. /**
  26813. * @author bhouston / http://clara.io/
  26814. */
  26815. function AnimationLoader( manager ) {
  26816. Loader.call( this, manager );
  26817. }
  26818. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26819. constructor: AnimationLoader,
  26820. load: function ( url, onLoad, onProgress, onError ) {
  26821. var scope = this;
  26822. var loader = new FileLoader( scope.manager );
  26823. loader.setPath( scope.path );
  26824. loader.load( url, function ( text ) {
  26825. onLoad( scope.parse( JSON.parse( text ) ) );
  26826. }, onProgress, onError );
  26827. },
  26828. parse: function ( json ) {
  26829. var animations = [];
  26830. for ( var i = 0; i < json.length; i ++ ) {
  26831. var clip = AnimationClip.parse( json[ i ] );
  26832. animations.push( clip );
  26833. }
  26834. return animations;
  26835. }
  26836. } );
  26837. /**
  26838. * @author mrdoob / http://mrdoob.com/
  26839. *
  26840. * Abstract Base class to block based textures loader (dds, pvr, ...)
  26841. *
  26842. * Sub classes have to implement the parse() method which will be used in load().
  26843. */
  26844. function CompressedTextureLoader( manager ) {
  26845. Loader.call( this, manager );
  26846. }
  26847. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26848. constructor: CompressedTextureLoader,
  26849. load: function ( url, onLoad, onProgress, onError ) {
  26850. var scope = this;
  26851. var images = [];
  26852. var texture = new CompressedTexture();
  26853. texture.image = images;
  26854. var loader = new FileLoader( this.manager );
  26855. loader.setPath( this.path );
  26856. loader.setResponseType( 'arraybuffer' );
  26857. function loadTexture( i ) {
  26858. loader.load( url[ i ], function ( buffer ) {
  26859. var texDatas = scope.parse( buffer, true );
  26860. images[ i ] = {
  26861. width: texDatas.width,
  26862. height: texDatas.height,
  26863. format: texDatas.format,
  26864. mipmaps: texDatas.mipmaps
  26865. };
  26866. loaded += 1;
  26867. if ( loaded === 6 ) {
  26868. if ( texDatas.mipmapCount === 1 )
  26869. { texture.minFilter = LinearFilter; }
  26870. texture.format = texDatas.format;
  26871. texture.needsUpdate = true;
  26872. if ( onLoad ) { onLoad( texture ); }
  26873. }
  26874. }, onProgress, onError );
  26875. }
  26876. if ( Array.isArray( url ) ) {
  26877. var loaded = 0;
  26878. for ( var i = 0, il = url.length; i < il; ++ i ) {
  26879. loadTexture( i );
  26880. }
  26881. } else {
  26882. // compressed cubemap texture stored in a single DDS file
  26883. loader.load( url, function ( buffer ) {
  26884. var texDatas = scope.parse( buffer, true );
  26885. if ( texDatas.isCubemap ) {
  26886. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  26887. for ( var f = 0; f < faces; f ++ ) {
  26888. images[ f ] = { mipmaps: [] };
  26889. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  26890. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  26891. images[ f ].format = texDatas.format;
  26892. images[ f ].width = texDatas.width;
  26893. images[ f ].height = texDatas.height;
  26894. }
  26895. }
  26896. } else {
  26897. texture.image.width = texDatas.width;
  26898. texture.image.height = texDatas.height;
  26899. texture.mipmaps = texDatas.mipmaps;
  26900. }
  26901. if ( texDatas.mipmapCount === 1 ) {
  26902. texture.minFilter = LinearFilter;
  26903. }
  26904. texture.format = texDatas.format;
  26905. texture.needsUpdate = true;
  26906. if ( onLoad ) { onLoad( texture ); }
  26907. }, onProgress, onError );
  26908. }
  26909. return texture;
  26910. }
  26911. } );
  26912. /**
  26913. * @author Nikos M. / https://github.com/foo123/
  26914. *
  26915. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26916. *
  26917. * Sub classes have to implement the parse() method which will be used in load().
  26918. */
  26919. function DataTextureLoader( manager ) {
  26920. Loader.call( this, manager );
  26921. }
  26922. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26923. constructor: DataTextureLoader,
  26924. load: function ( url, onLoad, onProgress, onError ) {
  26925. var scope = this;
  26926. var texture = new DataTexture();
  26927. var loader = new FileLoader( this.manager );
  26928. loader.setResponseType( 'arraybuffer' );
  26929. loader.setPath( this.path );
  26930. loader.load( url, function ( buffer ) {
  26931. var texData = scope.parse( buffer );
  26932. if ( ! texData ) { return; }
  26933. if ( texData.image !== undefined ) {
  26934. texture.image = texData.image;
  26935. } else if ( texData.data !== undefined ) {
  26936. texture.image.width = texData.width;
  26937. texture.image.height = texData.height;
  26938. texture.image.data = texData.data;
  26939. }
  26940. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26941. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26942. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26943. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  26944. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26945. if ( texData.format !== undefined ) {
  26946. texture.format = texData.format;
  26947. }
  26948. if ( texData.type !== undefined ) {
  26949. texture.type = texData.type;
  26950. }
  26951. if ( texData.mipmaps !== undefined ) {
  26952. texture.mipmaps = texData.mipmaps;
  26953. }
  26954. if ( texData.mipmapCount === 1 ) {
  26955. texture.minFilter = LinearFilter;
  26956. }
  26957. texture.needsUpdate = true;
  26958. if ( onLoad ) { onLoad( texture, texData ); }
  26959. }, onProgress, onError );
  26960. return texture;
  26961. }
  26962. } );
  26963. /**
  26964. * @author mrdoob / http://mrdoob.com/
  26965. */
  26966. function ImageLoader( manager ) {
  26967. Loader.call( this, manager );
  26968. }
  26969. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26970. constructor: ImageLoader,
  26971. load: function ( url, onLoad, onProgress, onError ) {
  26972. if ( this.path !== undefined ) { url = this.path + url; }
  26973. url = this.manager.resolveURL( url );
  26974. var scope = this;
  26975. var cached = Cache.get( url );
  26976. if ( cached !== undefined ) {
  26977. scope.manager.itemStart( url );
  26978. setTimeout( function () {
  26979. if ( onLoad ) { onLoad( cached ); }
  26980. scope.manager.itemEnd( url );
  26981. }, 0 );
  26982. return cached;
  26983. }
  26984. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  26985. function onImageLoad() {
  26986. image.removeEventListener( 'load', onImageLoad, false );
  26987. image.removeEventListener( 'error', onImageError, false );
  26988. Cache.add( url, this );
  26989. if ( onLoad ) { onLoad( this ); }
  26990. scope.manager.itemEnd( url );
  26991. }
  26992. function onImageError( event ) {
  26993. image.removeEventListener( 'load', onImageLoad, false );
  26994. image.removeEventListener( 'error', onImageError, false );
  26995. if ( onError ) { onError( event ); }
  26996. scope.manager.itemError( url );
  26997. scope.manager.itemEnd( url );
  26998. }
  26999. image.addEventListener( 'load', onImageLoad, false );
  27000. image.addEventListener( 'error', onImageError, false );
  27001. if ( url.substr( 0, 5 ) !== 'data:' ) {
  27002. if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; }
  27003. }
  27004. scope.manager.itemStart( url );
  27005. image.src = url;
  27006. return image;
  27007. }
  27008. } );
  27009. /**
  27010. * @author mrdoob / http://mrdoob.com/
  27011. */
  27012. function CubeTextureLoader( manager ) {
  27013. Loader.call( this, manager );
  27014. }
  27015. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27016. constructor: CubeTextureLoader,
  27017. load: function ( urls, onLoad, onProgress, onError ) {
  27018. var texture = new CubeTexture();
  27019. var loader = new ImageLoader( this.manager );
  27020. loader.setCrossOrigin( this.crossOrigin );
  27021. loader.setPath( this.path );
  27022. var loaded = 0;
  27023. function loadTexture( i ) {
  27024. loader.load( urls[ i ], function ( image ) {
  27025. texture.images[ i ] = image;
  27026. loaded ++;
  27027. if ( loaded === 6 ) {
  27028. texture.needsUpdate = true;
  27029. if ( onLoad ) { onLoad( texture ); }
  27030. }
  27031. }, undefined, onError );
  27032. }
  27033. for ( var i = 0; i < urls.length; ++ i ) {
  27034. loadTexture( i );
  27035. }
  27036. return texture;
  27037. }
  27038. } );
  27039. /**
  27040. * @author mrdoob / http://mrdoob.com/
  27041. */
  27042. function TextureLoader( manager ) {
  27043. Loader.call( this, manager );
  27044. }
  27045. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27046. constructor: TextureLoader,
  27047. load: function ( url, onLoad, onProgress, onError ) {
  27048. var texture = new Texture();
  27049. var loader = new ImageLoader( this.manager );
  27050. loader.setCrossOrigin( this.crossOrigin );
  27051. loader.setPath( this.path );
  27052. loader.load( url, function ( image ) {
  27053. texture.image = image;
  27054. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  27055. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  27056. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  27057. texture.needsUpdate = true;
  27058. if ( onLoad !== undefined ) {
  27059. onLoad( texture );
  27060. }
  27061. }, onProgress, onError );
  27062. return texture;
  27063. }
  27064. } );
  27065. /**
  27066. * @author zz85 / http://www.lab4games.net/zz85/blog
  27067. * Extensible curve object
  27068. *
  27069. * Some common of curve methods:
  27070. * .getPoint( t, optionalTarget ), .getTangent( t )
  27071. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  27072. * .getPoints(), .getSpacedPoints()
  27073. * .getLength()
  27074. * .updateArcLengths()
  27075. *
  27076. * This following curves inherit from THREE.Curve:
  27077. *
  27078. * -- 2D curves --
  27079. * THREE.ArcCurve
  27080. * THREE.CubicBezierCurve
  27081. * THREE.EllipseCurve
  27082. * THREE.LineCurve
  27083. * THREE.QuadraticBezierCurve
  27084. * THREE.SplineCurve
  27085. *
  27086. * -- 3D curves --
  27087. * THREE.CatmullRomCurve3
  27088. * THREE.CubicBezierCurve3
  27089. * THREE.LineCurve3
  27090. * THREE.QuadraticBezierCurve3
  27091. *
  27092. * A series of curves can be represented as a THREE.CurvePath.
  27093. *
  27094. **/
  27095. /**************************************************************
  27096. * Abstract Curve base class
  27097. **************************************************************/
  27098. function Curve() {
  27099. this.type = 'Curve';
  27100. this.arcLengthDivisions = 200;
  27101. }
  27102. Object.assign( Curve.prototype, {
  27103. // Virtual base class method to overwrite and implement in subclasses
  27104. // - t [0 .. 1]
  27105. getPoint: function ( /* t, optionalTarget */ ) {
  27106. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  27107. return null;
  27108. },
  27109. // Get point at relative position in curve according to arc length
  27110. // - u [0 .. 1]
  27111. getPointAt: function ( u, optionalTarget ) {
  27112. var t = this.getUtoTmapping( u );
  27113. return this.getPoint( t, optionalTarget );
  27114. },
  27115. // Get sequence of points using getPoint( t )
  27116. getPoints: function ( divisions ) {
  27117. if ( divisions === undefined ) { divisions = 5; }
  27118. var points = [];
  27119. for ( var d = 0; d <= divisions; d ++ ) {
  27120. points.push( this.getPoint( d / divisions ) );
  27121. }
  27122. return points;
  27123. },
  27124. // Get sequence of points using getPointAt( u )
  27125. getSpacedPoints: function ( divisions ) {
  27126. if ( divisions === undefined ) { divisions = 5; }
  27127. var points = [];
  27128. for ( var d = 0; d <= divisions; d ++ ) {
  27129. points.push( this.getPointAt( d / divisions ) );
  27130. }
  27131. return points;
  27132. },
  27133. // Get total curve arc length
  27134. getLength: function () {
  27135. var lengths = this.getLengths();
  27136. return lengths[ lengths.length - 1 ];
  27137. },
  27138. // Get list of cumulative segment lengths
  27139. getLengths: function ( divisions ) {
  27140. if ( divisions === undefined ) { divisions = this.arcLengthDivisions; }
  27141. if ( this.cacheArcLengths &&
  27142. ( this.cacheArcLengths.length === divisions + 1 ) &&
  27143. ! this.needsUpdate ) {
  27144. return this.cacheArcLengths;
  27145. }
  27146. this.needsUpdate = false;
  27147. var cache = [];
  27148. var current, last = this.getPoint( 0 );
  27149. var p, sum = 0;
  27150. cache.push( 0 );
  27151. for ( p = 1; p <= divisions; p ++ ) {
  27152. current = this.getPoint( p / divisions );
  27153. sum += current.distanceTo( last );
  27154. cache.push( sum );
  27155. last = current;
  27156. }
  27157. this.cacheArcLengths = cache;
  27158. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  27159. },
  27160. updateArcLengths: function () {
  27161. this.needsUpdate = true;
  27162. this.getLengths();
  27163. },
  27164. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  27165. getUtoTmapping: function ( u, distance ) {
  27166. var arcLengths = this.getLengths();
  27167. var i = 0, il = arcLengths.length;
  27168. var targetArcLength; // The targeted u distance value to get
  27169. if ( distance ) {
  27170. targetArcLength = distance;
  27171. } else {
  27172. targetArcLength = u * arcLengths[ il - 1 ];
  27173. }
  27174. // binary search for the index with largest value smaller than target u distance
  27175. var low = 0, high = il - 1, comparison;
  27176. while ( low <= high ) {
  27177. 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
  27178. comparison = arcLengths[ i ] - targetArcLength;
  27179. if ( comparison < 0 ) {
  27180. low = i + 1;
  27181. } else if ( comparison > 0 ) {
  27182. high = i - 1;
  27183. } else {
  27184. high = i;
  27185. break;
  27186. // DONE
  27187. }
  27188. }
  27189. i = high;
  27190. if ( arcLengths[ i ] === targetArcLength ) {
  27191. return i / ( il - 1 );
  27192. }
  27193. // we could get finer grain at lengths, or use simple interpolation between two points
  27194. var lengthBefore = arcLengths[ i ];
  27195. var lengthAfter = arcLengths[ i + 1 ];
  27196. var segmentLength = lengthAfter - lengthBefore;
  27197. // determine where we are between the 'before' and 'after' points
  27198. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  27199. // add that fractional amount to t
  27200. var t = ( i + segmentFraction ) / ( il - 1 );
  27201. return t;
  27202. },
  27203. // Returns a unit vector tangent at t
  27204. // In case any sub curve does not implement its tangent derivation,
  27205. // 2 points a small delta apart will be used to find its gradient
  27206. // which seems to give a reasonable approximation
  27207. getTangent: function ( t ) {
  27208. var delta = 0.0001;
  27209. var t1 = t - delta;
  27210. var t2 = t + delta;
  27211. // Capping in case of danger
  27212. if ( t1 < 0 ) { t1 = 0; }
  27213. if ( t2 > 1 ) { t2 = 1; }
  27214. var pt1 = this.getPoint( t1 );
  27215. var pt2 = this.getPoint( t2 );
  27216. var vec = pt2.clone().sub( pt1 );
  27217. return vec.normalize();
  27218. },
  27219. getTangentAt: function ( u ) {
  27220. var t = this.getUtoTmapping( u );
  27221. return this.getTangent( t );
  27222. },
  27223. computeFrenetFrames: function ( segments, closed ) {
  27224. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  27225. var normal = new Vector3();
  27226. var tangents = [];
  27227. var normals = [];
  27228. var binormals = [];
  27229. var vec = new Vector3();
  27230. var mat = new Matrix4();
  27231. var i, u, theta;
  27232. // compute the tangent vectors for each segment on the curve
  27233. for ( i = 0; i <= segments; i ++ ) {
  27234. u = i / segments;
  27235. tangents[ i ] = this.getTangentAt( u );
  27236. tangents[ i ].normalize();
  27237. }
  27238. // select an initial normal vector perpendicular to the first tangent vector,
  27239. // and in the direction of the minimum tangent xyz component
  27240. normals[ 0 ] = new Vector3();
  27241. binormals[ 0 ] = new Vector3();
  27242. var min = Number.MAX_VALUE;
  27243. var tx = Math.abs( tangents[ 0 ].x );
  27244. var ty = Math.abs( tangents[ 0 ].y );
  27245. var tz = Math.abs( tangents[ 0 ].z );
  27246. if ( tx <= min ) {
  27247. min = tx;
  27248. normal.set( 1, 0, 0 );
  27249. }
  27250. if ( ty <= min ) {
  27251. min = ty;
  27252. normal.set( 0, 1, 0 );
  27253. }
  27254. if ( tz <= min ) {
  27255. normal.set( 0, 0, 1 );
  27256. }
  27257. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  27258. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  27259. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  27260. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  27261. for ( i = 1; i <= segments; i ++ ) {
  27262. normals[ i ] = normals[ i - 1 ].clone();
  27263. binormals[ i ] = binormals[ i - 1 ].clone();
  27264. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  27265. if ( vec.length() > Number.EPSILON ) {
  27266. vec.normalize();
  27267. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  27268. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  27269. }
  27270. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  27271. }
  27272. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  27273. if ( closed === true ) {
  27274. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  27275. theta /= segments;
  27276. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  27277. theta = - theta;
  27278. }
  27279. for ( i = 1; i <= segments; i ++ ) {
  27280. // twist a little...
  27281. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  27282. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  27283. }
  27284. }
  27285. return {
  27286. tangents: tangents,
  27287. normals: normals,
  27288. binormals: binormals
  27289. };
  27290. },
  27291. clone: function () {
  27292. return new this.constructor().copy( this );
  27293. },
  27294. copy: function ( source ) {
  27295. this.arcLengthDivisions = source.arcLengthDivisions;
  27296. return this;
  27297. },
  27298. toJSON: function () {
  27299. var data = {
  27300. metadata: {
  27301. version: 4.5,
  27302. type: 'Curve',
  27303. generator: 'Curve.toJSON'
  27304. }
  27305. };
  27306. data.arcLengthDivisions = this.arcLengthDivisions;
  27307. data.type = this.type;
  27308. return data;
  27309. },
  27310. fromJSON: function ( json ) {
  27311. this.arcLengthDivisions = json.arcLengthDivisions;
  27312. return this;
  27313. }
  27314. } );
  27315. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  27316. Curve.call( this );
  27317. this.type = 'EllipseCurve';
  27318. this.aX = aX || 0;
  27319. this.aY = aY || 0;
  27320. this.xRadius = xRadius || 1;
  27321. this.yRadius = yRadius || 1;
  27322. this.aStartAngle = aStartAngle || 0;
  27323. this.aEndAngle = aEndAngle || 2 * Math.PI;
  27324. this.aClockwise = aClockwise || false;
  27325. this.aRotation = aRotation || 0;
  27326. }
  27327. EllipseCurve.prototype = Object.create( Curve.prototype );
  27328. EllipseCurve.prototype.constructor = EllipseCurve;
  27329. EllipseCurve.prototype.isEllipseCurve = true;
  27330. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  27331. var point = optionalTarget || new Vector2();
  27332. var twoPi = Math.PI * 2;
  27333. var deltaAngle = this.aEndAngle - this.aStartAngle;
  27334. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  27335. // ensures that deltaAngle is 0 .. 2 PI
  27336. while ( deltaAngle < 0 ) { deltaAngle += twoPi; }
  27337. while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; }
  27338. if ( deltaAngle < Number.EPSILON ) {
  27339. if ( samePoints ) {
  27340. deltaAngle = 0;
  27341. } else {
  27342. deltaAngle = twoPi;
  27343. }
  27344. }
  27345. if ( this.aClockwise === true && ! samePoints ) {
  27346. if ( deltaAngle === twoPi ) {
  27347. deltaAngle = - twoPi;
  27348. } else {
  27349. deltaAngle = deltaAngle - twoPi;
  27350. }
  27351. }
  27352. var angle = this.aStartAngle + t * deltaAngle;
  27353. var x = this.aX + this.xRadius * Math.cos( angle );
  27354. var y = this.aY + this.yRadius * Math.sin( angle );
  27355. if ( this.aRotation !== 0 ) {
  27356. var cos = Math.cos( this.aRotation );
  27357. var sin = Math.sin( this.aRotation );
  27358. var tx = x - this.aX;
  27359. var ty = y - this.aY;
  27360. // Rotate the point about the center of the ellipse.
  27361. x = tx * cos - ty * sin + this.aX;
  27362. y = tx * sin + ty * cos + this.aY;
  27363. }
  27364. return point.set( x, y );
  27365. };
  27366. EllipseCurve.prototype.copy = function ( source ) {
  27367. Curve.prototype.copy.call( this, source );
  27368. this.aX = source.aX;
  27369. this.aY = source.aY;
  27370. this.xRadius = source.xRadius;
  27371. this.yRadius = source.yRadius;
  27372. this.aStartAngle = source.aStartAngle;
  27373. this.aEndAngle = source.aEndAngle;
  27374. this.aClockwise = source.aClockwise;
  27375. this.aRotation = source.aRotation;
  27376. return this;
  27377. };
  27378. EllipseCurve.prototype.toJSON = function () {
  27379. var data = Curve.prototype.toJSON.call( this );
  27380. data.aX = this.aX;
  27381. data.aY = this.aY;
  27382. data.xRadius = this.xRadius;
  27383. data.yRadius = this.yRadius;
  27384. data.aStartAngle = this.aStartAngle;
  27385. data.aEndAngle = this.aEndAngle;
  27386. data.aClockwise = this.aClockwise;
  27387. data.aRotation = this.aRotation;
  27388. return data;
  27389. };
  27390. EllipseCurve.prototype.fromJSON = function ( json ) {
  27391. Curve.prototype.fromJSON.call( this, json );
  27392. this.aX = json.aX;
  27393. this.aY = json.aY;
  27394. this.xRadius = json.xRadius;
  27395. this.yRadius = json.yRadius;
  27396. this.aStartAngle = json.aStartAngle;
  27397. this.aEndAngle = json.aEndAngle;
  27398. this.aClockwise = json.aClockwise;
  27399. this.aRotation = json.aRotation;
  27400. return this;
  27401. };
  27402. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  27403. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  27404. this.type = 'ArcCurve';
  27405. }
  27406. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  27407. ArcCurve.prototype.constructor = ArcCurve;
  27408. ArcCurve.prototype.isArcCurve = true;
  27409. /**
  27410. * @author zz85 https://github.com/zz85
  27411. *
  27412. * Centripetal CatmullRom Curve - which is useful for avoiding
  27413. * cusps and self-intersections in non-uniform catmull rom curves.
  27414. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  27415. *
  27416. * curve.type accepts centripetal(default), chordal and catmullrom
  27417. * curve.tension is used for catmullrom which defaults to 0.5
  27418. */
  27419. /*
  27420. Based on an optimized c++ solution in
  27421. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  27422. - http://ideone.com/NoEbVM
  27423. This CubicPoly class could be used for reusing some variables and calculations,
  27424. but for three.js curve use, it could be possible inlined and flatten into a single function call
  27425. which can be placed in CurveUtils.
  27426. */
  27427. function CubicPoly() {
  27428. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  27429. /*
  27430. * Compute coefficients for a cubic polynomial
  27431. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  27432. * such that
  27433. * p(0) = x0, p(1) = x1
  27434. * and
  27435. * p'(0) = t0, p'(1) = t1.
  27436. */
  27437. function init( x0, x1, t0, t1 ) {
  27438. c0 = x0;
  27439. c1 = t0;
  27440. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  27441. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  27442. }
  27443. return {
  27444. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  27445. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  27446. },
  27447. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  27448. // compute tangents when parameterized in [t1,t2]
  27449. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  27450. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  27451. // rescale tangents for parametrization in [0,1]
  27452. t1 *= dt1;
  27453. t2 *= dt1;
  27454. init( x1, x2, t1, t2 );
  27455. },
  27456. calc: function ( t ) {
  27457. var t2 = t * t;
  27458. var t3 = t2 * t;
  27459. return c0 + c1 * t + c2 * t2 + c3 * t3;
  27460. }
  27461. };
  27462. }
  27463. //
  27464. var tmp = new Vector3();
  27465. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  27466. function CatmullRomCurve3( points, closed, curveType, tension ) {
  27467. Curve.call( this );
  27468. this.type = 'CatmullRomCurve3';
  27469. this.points = points || [];
  27470. this.closed = closed || false;
  27471. this.curveType = curveType || 'centripetal';
  27472. this.tension = tension || 0.5;
  27473. }
  27474. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  27475. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  27476. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  27477. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  27478. var point = optionalTarget || new Vector3();
  27479. var points = this.points;
  27480. var l = points.length;
  27481. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  27482. var intPoint = Math.floor( p );
  27483. var weight = p - intPoint;
  27484. if ( this.closed ) {
  27485. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  27486. } else if ( weight === 0 && intPoint === l - 1 ) {
  27487. intPoint = l - 2;
  27488. weight = 1;
  27489. }
  27490. var p0, p1, p2, p3; // 4 points
  27491. if ( this.closed || intPoint > 0 ) {
  27492. p0 = points[ ( intPoint - 1 ) % l ];
  27493. } else {
  27494. // extrapolate first point
  27495. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  27496. p0 = tmp;
  27497. }
  27498. p1 = points[ intPoint % l ];
  27499. p2 = points[ ( intPoint + 1 ) % l ];
  27500. if ( this.closed || intPoint + 2 < l ) {
  27501. p3 = points[ ( intPoint + 2 ) % l ];
  27502. } else {
  27503. // extrapolate last point
  27504. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  27505. p3 = tmp;
  27506. }
  27507. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  27508. // init Centripetal / Chordal Catmull-Rom
  27509. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  27510. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  27511. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  27512. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  27513. // safety check for repeated points
  27514. if ( dt1 < 1e-4 ) { dt1 = 1.0; }
  27515. if ( dt0 < 1e-4 ) { dt0 = dt1; }
  27516. if ( dt2 < 1e-4 ) { dt2 = dt1; }
  27517. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  27518. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  27519. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  27520. } else if ( this.curveType === 'catmullrom' ) {
  27521. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  27522. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  27523. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  27524. }
  27525. point.set(
  27526. px.calc( weight ),
  27527. py.calc( weight ),
  27528. pz.calc( weight )
  27529. );
  27530. return point;
  27531. };
  27532. CatmullRomCurve3.prototype.copy = function ( source ) {
  27533. Curve.prototype.copy.call( this, source );
  27534. this.points = [];
  27535. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  27536. var point = source.points[ i ];
  27537. this.points.push( point.clone() );
  27538. }
  27539. this.closed = source.closed;
  27540. this.curveType = source.curveType;
  27541. this.tension = source.tension;
  27542. return this;
  27543. };
  27544. CatmullRomCurve3.prototype.toJSON = function () {
  27545. var data = Curve.prototype.toJSON.call( this );
  27546. data.points = [];
  27547. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  27548. var point = this.points[ i ];
  27549. data.points.push( point.toArray() );
  27550. }
  27551. data.closed = this.closed;
  27552. data.curveType = this.curveType;
  27553. data.tension = this.tension;
  27554. return data;
  27555. };
  27556. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  27557. Curve.prototype.fromJSON.call( this, json );
  27558. this.points = [];
  27559. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  27560. var point = json.points[ i ];
  27561. this.points.push( new Vector3().fromArray( point ) );
  27562. }
  27563. this.closed = json.closed;
  27564. this.curveType = json.curveType;
  27565. this.tension = json.tension;
  27566. return this;
  27567. };
  27568. /**
  27569. * @author zz85 / http://www.lab4games.net/zz85/blog
  27570. *
  27571. * Bezier Curves formulas obtained from
  27572. * http://en.wikipedia.org/wiki/Bézier_curve
  27573. */
  27574. function CatmullRom( t, p0, p1, p2, p3 ) {
  27575. var v0 = ( p2 - p0 ) * 0.5;
  27576. var v1 = ( p3 - p1 ) * 0.5;
  27577. var t2 = t * t;
  27578. var t3 = t * t2;
  27579. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  27580. }
  27581. //
  27582. function QuadraticBezierP0( t, p ) {
  27583. var k = 1 - t;
  27584. return k * k * p;
  27585. }
  27586. function QuadraticBezierP1( t, p ) {
  27587. return 2 * ( 1 - t ) * t * p;
  27588. }
  27589. function QuadraticBezierP2( t, p ) {
  27590. return t * t * p;
  27591. }
  27592. function QuadraticBezier( t, p0, p1, p2 ) {
  27593. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  27594. QuadraticBezierP2( t, p2 );
  27595. }
  27596. //
  27597. function CubicBezierP0( t, p ) {
  27598. var k = 1 - t;
  27599. return k * k * k * p;
  27600. }
  27601. function CubicBezierP1( t, p ) {
  27602. var k = 1 - t;
  27603. return 3 * k * k * t * p;
  27604. }
  27605. function CubicBezierP2( t, p ) {
  27606. return 3 * ( 1 - t ) * t * t * p;
  27607. }
  27608. function CubicBezierP3( t, p ) {
  27609. return t * t * t * p;
  27610. }
  27611. function CubicBezier( t, p0, p1, p2, p3 ) {
  27612. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  27613. CubicBezierP3( t, p3 );
  27614. }
  27615. function CubicBezierCurve( v0, v1, v2, v3 ) {
  27616. Curve.call( this );
  27617. this.type = 'CubicBezierCurve';
  27618. this.v0 = v0 || new Vector2();
  27619. this.v1 = v1 || new Vector2();
  27620. this.v2 = v2 || new Vector2();
  27621. this.v3 = v3 || new Vector2();
  27622. }
  27623. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  27624. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  27625. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  27626. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  27627. var point = optionalTarget || new Vector2();
  27628. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  27629. point.set(
  27630. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  27631. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  27632. );
  27633. return point;
  27634. };
  27635. CubicBezierCurve.prototype.copy = function ( source ) {
  27636. Curve.prototype.copy.call( this, source );
  27637. this.v0.copy( source.v0 );
  27638. this.v1.copy( source.v1 );
  27639. this.v2.copy( source.v2 );
  27640. this.v3.copy( source.v3 );
  27641. return this;
  27642. };
  27643. CubicBezierCurve.prototype.toJSON = function () {
  27644. var data = Curve.prototype.toJSON.call( this );
  27645. data.v0 = this.v0.toArray();
  27646. data.v1 = this.v1.toArray();
  27647. data.v2 = this.v2.toArray();
  27648. data.v3 = this.v3.toArray();
  27649. return data;
  27650. };
  27651. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  27652. Curve.prototype.fromJSON.call( this, json );
  27653. this.v0.fromArray( json.v0 );
  27654. this.v1.fromArray( json.v1 );
  27655. this.v2.fromArray( json.v2 );
  27656. this.v3.fromArray( json.v3 );
  27657. return this;
  27658. };
  27659. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  27660. Curve.call( this );
  27661. this.type = 'CubicBezierCurve3';
  27662. this.v0 = v0 || new Vector3();
  27663. this.v1 = v1 || new Vector3();
  27664. this.v2 = v2 || new Vector3();
  27665. this.v3 = v3 || new Vector3();
  27666. }
  27667. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  27668. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  27669. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  27670. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  27671. var point = optionalTarget || new Vector3();
  27672. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  27673. point.set(
  27674. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  27675. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  27676. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  27677. );
  27678. return point;
  27679. };
  27680. CubicBezierCurve3.prototype.copy = function ( source ) {
  27681. Curve.prototype.copy.call( this, source );
  27682. this.v0.copy( source.v0 );
  27683. this.v1.copy( source.v1 );
  27684. this.v2.copy( source.v2 );
  27685. this.v3.copy( source.v3 );
  27686. return this;
  27687. };
  27688. CubicBezierCurve3.prototype.toJSON = function () {
  27689. var data = Curve.prototype.toJSON.call( this );
  27690. data.v0 = this.v0.toArray();
  27691. data.v1 = this.v1.toArray();
  27692. data.v2 = this.v2.toArray();
  27693. data.v3 = this.v3.toArray();
  27694. return data;
  27695. };
  27696. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  27697. Curve.prototype.fromJSON.call( this, json );
  27698. this.v0.fromArray( json.v0 );
  27699. this.v1.fromArray( json.v1 );
  27700. this.v2.fromArray( json.v2 );
  27701. this.v3.fromArray( json.v3 );
  27702. return this;
  27703. };
  27704. function LineCurve( v1, v2 ) {
  27705. Curve.call( this );
  27706. this.type = 'LineCurve';
  27707. this.v1 = v1 || new Vector2();
  27708. this.v2 = v2 || new Vector2();
  27709. }
  27710. LineCurve.prototype = Object.create( Curve.prototype );
  27711. LineCurve.prototype.constructor = LineCurve;
  27712. LineCurve.prototype.isLineCurve = true;
  27713. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  27714. var point = optionalTarget || new Vector2();
  27715. if ( t === 1 ) {
  27716. point.copy( this.v2 );
  27717. } else {
  27718. point.copy( this.v2 ).sub( this.v1 );
  27719. point.multiplyScalar( t ).add( this.v1 );
  27720. }
  27721. return point;
  27722. };
  27723. // Line curve is linear, so we can overwrite default getPointAt
  27724. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  27725. return this.getPoint( u, optionalTarget );
  27726. };
  27727. LineCurve.prototype.getTangent = function ( /* t */ ) {
  27728. var tangent = this.v2.clone().sub( this.v1 );
  27729. return tangent.normalize();
  27730. };
  27731. LineCurve.prototype.copy = function ( source ) {
  27732. Curve.prototype.copy.call( this, source );
  27733. this.v1.copy( source.v1 );
  27734. this.v2.copy( source.v2 );
  27735. return this;
  27736. };
  27737. LineCurve.prototype.toJSON = function () {
  27738. var data = Curve.prototype.toJSON.call( this );
  27739. data.v1 = this.v1.toArray();
  27740. data.v2 = this.v2.toArray();
  27741. return data;
  27742. };
  27743. LineCurve.prototype.fromJSON = function ( json ) {
  27744. Curve.prototype.fromJSON.call( this, json );
  27745. this.v1.fromArray( json.v1 );
  27746. this.v2.fromArray( json.v2 );
  27747. return this;
  27748. };
  27749. function LineCurve3( v1, v2 ) {
  27750. Curve.call( this );
  27751. this.type = 'LineCurve3';
  27752. this.v1 = v1 || new Vector3();
  27753. this.v2 = v2 || new Vector3();
  27754. }
  27755. LineCurve3.prototype = Object.create( Curve.prototype );
  27756. LineCurve3.prototype.constructor = LineCurve3;
  27757. LineCurve3.prototype.isLineCurve3 = true;
  27758. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  27759. var point = optionalTarget || new Vector3();
  27760. if ( t === 1 ) {
  27761. point.copy( this.v2 );
  27762. } else {
  27763. point.copy( this.v2 ).sub( this.v1 );
  27764. point.multiplyScalar( t ).add( this.v1 );
  27765. }
  27766. return point;
  27767. };
  27768. // Line curve is linear, so we can overwrite default getPointAt
  27769. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  27770. return this.getPoint( u, optionalTarget );
  27771. };
  27772. LineCurve3.prototype.copy = function ( source ) {
  27773. Curve.prototype.copy.call( this, source );
  27774. this.v1.copy( source.v1 );
  27775. this.v2.copy( source.v2 );
  27776. return this;
  27777. };
  27778. LineCurve3.prototype.toJSON = function () {
  27779. var data = Curve.prototype.toJSON.call( this );
  27780. data.v1 = this.v1.toArray();
  27781. data.v2 = this.v2.toArray();
  27782. return data;
  27783. };
  27784. LineCurve3.prototype.fromJSON = function ( json ) {
  27785. Curve.prototype.fromJSON.call( this, json );
  27786. this.v1.fromArray( json.v1 );
  27787. this.v2.fromArray( json.v2 );
  27788. return this;
  27789. };
  27790. function QuadraticBezierCurve( v0, v1, v2 ) {
  27791. Curve.call( this );
  27792. this.type = 'QuadraticBezierCurve';
  27793. this.v0 = v0 || new Vector2();
  27794. this.v1 = v1 || new Vector2();
  27795. this.v2 = v2 || new Vector2();
  27796. }
  27797. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  27798. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  27799. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  27800. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  27801. var point = optionalTarget || new Vector2();
  27802. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  27803. point.set(
  27804. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  27805. QuadraticBezier( t, v0.y, v1.y, v2.y )
  27806. );
  27807. return point;
  27808. };
  27809. QuadraticBezierCurve.prototype.copy = function ( source ) {
  27810. Curve.prototype.copy.call( this, source );
  27811. this.v0.copy( source.v0 );
  27812. this.v1.copy( source.v1 );
  27813. this.v2.copy( source.v2 );
  27814. return this;
  27815. };
  27816. QuadraticBezierCurve.prototype.toJSON = function () {
  27817. var data = Curve.prototype.toJSON.call( this );
  27818. data.v0 = this.v0.toArray();
  27819. data.v1 = this.v1.toArray();
  27820. data.v2 = this.v2.toArray();
  27821. return data;
  27822. };
  27823. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  27824. Curve.prototype.fromJSON.call( this, json );
  27825. this.v0.fromArray( json.v0 );
  27826. this.v1.fromArray( json.v1 );
  27827. this.v2.fromArray( json.v2 );
  27828. return this;
  27829. };
  27830. function QuadraticBezierCurve3( v0, v1, v2 ) {
  27831. Curve.call( this );
  27832. this.type = 'QuadraticBezierCurve3';
  27833. this.v0 = v0 || new Vector3();
  27834. this.v1 = v1 || new Vector3();
  27835. this.v2 = v2 || new Vector3();
  27836. }
  27837. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  27838. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  27839. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  27840. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  27841. var point = optionalTarget || new Vector3();
  27842. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  27843. point.set(
  27844. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  27845. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  27846. QuadraticBezier( t, v0.z, v1.z, v2.z )
  27847. );
  27848. return point;
  27849. };
  27850. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  27851. Curve.prototype.copy.call( this, source );
  27852. this.v0.copy( source.v0 );
  27853. this.v1.copy( source.v1 );
  27854. this.v2.copy( source.v2 );
  27855. return this;
  27856. };
  27857. QuadraticBezierCurve3.prototype.toJSON = function () {
  27858. var data = Curve.prototype.toJSON.call( this );
  27859. data.v0 = this.v0.toArray();
  27860. data.v1 = this.v1.toArray();
  27861. data.v2 = this.v2.toArray();
  27862. return data;
  27863. };
  27864. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  27865. Curve.prototype.fromJSON.call( this, json );
  27866. this.v0.fromArray( json.v0 );
  27867. this.v1.fromArray( json.v1 );
  27868. this.v2.fromArray( json.v2 );
  27869. return this;
  27870. };
  27871. function SplineCurve( points /* array of Vector2 */ ) {
  27872. Curve.call( this );
  27873. this.type = 'SplineCurve';
  27874. this.points = points || [];
  27875. }
  27876. SplineCurve.prototype = Object.create( Curve.prototype );
  27877. SplineCurve.prototype.constructor = SplineCurve;
  27878. SplineCurve.prototype.isSplineCurve = true;
  27879. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  27880. var point = optionalTarget || new Vector2();
  27881. var points = this.points;
  27882. var p = ( points.length - 1 ) * t;
  27883. var intPoint = Math.floor( p );
  27884. var weight = p - intPoint;
  27885. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  27886. var p1 = points[ intPoint ];
  27887. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  27888. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  27889. point.set(
  27890. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  27891. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  27892. );
  27893. return point;
  27894. };
  27895. SplineCurve.prototype.copy = function ( source ) {
  27896. Curve.prototype.copy.call( this, source );
  27897. this.points = [];
  27898. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  27899. var point = source.points[ i ];
  27900. this.points.push( point.clone() );
  27901. }
  27902. return this;
  27903. };
  27904. SplineCurve.prototype.toJSON = function () {
  27905. var data = Curve.prototype.toJSON.call( this );
  27906. data.points = [];
  27907. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  27908. var point = this.points[ i ];
  27909. data.points.push( point.toArray() );
  27910. }
  27911. return data;
  27912. };
  27913. SplineCurve.prototype.fromJSON = function ( json ) {
  27914. Curve.prototype.fromJSON.call( this, json );
  27915. this.points = [];
  27916. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  27917. var point = json.points[ i ];
  27918. this.points.push( new Vector2().fromArray( point ) );
  27919. }
  27920. return this;
  27921. };
  27922. var Curves = /*#__PURE__*/Object.freeze({
  27923. ArcCurve: ArcCurve,
  27924. CatmullRomCurve3: CatmullRomCurve3,
  27925. CubicBezierCurve: CubicBezierCurve,
  27926. CubicBezierCurve3: CubicBezierCurve3,
  27927. EllipseCurve: EllipseCurve,
  27928. LineCurve: LineCurve,
  27929. LineCurve3: LineCurve3,
  27930. QuadraticBezierCurve: QuadraticBezierCurve,
  27931. QuadraticBezierCurve3: QuadraticBezierCurve3,
  27932. SplineCurve: SplineCurve
  27933. });
  27934. /**
  27935. * @author zz85 / http://www.lab4games.net/zz85/blog
  27936. *
  27937. **/
  27938. /**************************************************************
  27939. * Curved Path - a curve path is simply a array of connected
  27940. * curves, but retains the api of a curve
  27941. **************************************************************/
  27942. function CurvePath() {
  27943. Curve.call( this );
  27944. this.type = 'CurvePath';
  27945. this.curves = [];
  27946. this.autoClose = false; // Automatically closes the path
  27947. }
  27948. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  27949. constructor: CurvePath,
  27950. add: function ( curve ) {
  27951. this.curves.push( curve );
  27952. },
  27953. closePath: function () {
  27954. // Add a line curve if start and end of lines are not connected
  27955. var startPoint = this.curves[ 0 ].getPoint( 0 );
  27956. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  27957. if ( ! startPoint.equals( endPoint ) ) {
  27958. this.curves.push( new LineCurve( endPoint, startPoint ) );
  27959. }
  27960. },
  27961. // To get accurate point with reference to
  27962. // entire path distance at time t,
  27963. // following has to be done:
  27964. // 1. Length of each sub path have to be known
  27965. // 2. Locate and identify type of curve
  27966. // 3. Get t for the curve
  27967. // 4. Return curve.getPointAt(t')
  27968. getPoint: function ( t ) {
  27969. var d = t * this.getLength();
  27970. var curveLengths = this.getCurveLengths();
  27971. var i = 0;
  27972. // To think about boundaries points.
  27973. while ( i < curveLengths.length ) {
  27974. if ( curveLengths[ i ] >= d ) {
  27975. var diff = curveLengths[ i ] - d;
  27976. var curve = this.curves[ i ];
  27977. var segmentLength = curve.getLength();
  27978. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  27979. return curve.getPointAt( u );
  27980. }
  27981. i ++;
  27982. }
  27983. return null;
  27984. // loop where sum != 0, sum > d , sum+1 <d
  27985. },
  27986. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  27987. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  27988. // getPoint() depends on getLength
  27989. getLength: function () {
  27990. var lens = this.getCurveLengths();
  27991. return lens[ lens.length - 1 ];
  27992. },
  27993. // cacheLengths must be recalculated.
  27994. updateArcLengths: function () {
  27995. this.needsUpdate = true;
  27996. this.cacheLengths = null;
  27997. this.getCurveLengths();
  27998. },
  27999. // Compute lengths and cache them
  28000. // We cannot overwrite getLengths() because UtoT mapping uses it.
  28001. getCurveLengths: function () {
  28002. // We use cache values if curves and cache array are same length
  28003. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  28004. return this.cacheLengths;
  28005. }
  28006. // Get length of sub-curve
  28007. // Push sums into cached array
  28008. var lengths = [], sums = 0;
  28009. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28010. sums += this.curves[ i ].getLength();
  28011. lengths.push( sums );
  28012. }
  28013. this.cacheLengths = lengths;
  28014. return lengths;
  28015. },
  28016. getSpacedPoints: function ( divisions ) {
  28017. if ( divisions === undefined ) { divisions = 40; }
  28018. var points = [];
  28019. for ( var i = 0; i <= divisions; i ++ ) {
  28020. points.push( this.getPoint( i / divisions ) );
  28021. }
  28022. if ( this.autoClose ) {
  28023. points.push( points[ 0 ] );
  28024. }
  28025. return points;
  28026. },
  28027. getPoints: function ( divisions ) {
  28028. divisions = divisions || 12;
  28029. var points = [], last;
  28030. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  28031. var curve = curves[ i ];
  28032. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  28033. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  28034. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  28035. : divisions;
  28036. var pts = curve.getPoints( resolution );
  28037. for ( var j = 0; j < pts.length; j ++ ) {
  28038. var point = pts[ j ];
  28039. if ( last && last.equals( point ) ) { continue; } // ensures no consecutive points are duplicates
  28040. points.push( point );
  28041. last = point;
  28042. }
  28043. }
  28044. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  28045. points.push( points[ 0 ] );
  28046. }
  28047. return points;
  28048. },
  28049. copy: function ( source ) {
  28050. Curve.prototype.copy.call( this, source );
  28051. this.curves = [];
  28052. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  28053. var curve = source.curves[ i ];
  28054. this.curves.push( curve.clone() );
  28055. }
  28056. this.autoClose = source.autoClose;
  28057. return this;
  28058. },
  28059. toJSON: function () {
  28060. var data = Curve.prototype.toJSON.call( this );
  28061. data.autoClose = this.autoClose;
  28062. data.curves = [];
  28063. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28064. var curve = this.curves[ i ];
  28065. data.curves.push( curve.toJSON() );
  28066. }
  28067. return data;
  28068. },
  28069. fromJSON: function ( json ) {
  28070. Curve.prototype.fromJSON.call( this, json );
  28071. this.autoClose = json.autoClose;
  28072. this.curves = [];
  28073. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  28074. var curve = json.curves[ i ];
  28075. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  28076. }
  28077. return this;
  28078. }
  28079. } );
  28080. /**
  28081. * @author zz85 / http://www.lab4games.net/zz85/blog
  28082. * Creates free form 2d path using series of points, lines or curves.
  28083. **/
  28084. function Path( points ) {
  28085. CurvePath.call( this );
  28086. this.type = 'Path';
  28087. this.currentPoint = new Vector2();
  28088. if ( points ) {
  28089. this.setFromPoints( points );
  28090. }
  28091. }
  28092. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  28093. constructor: Path,
  28094. setFromPoints: function ( points ) {
  28095. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  28096. for ( var i = 1, l = points.length; i < l; i ++ ) {
  28097. this.lineTo( points[ i ].x, points[ i ].y );
  28098. }
  28099. },
  28100. moveTo: function ( x, y ) {
  28101. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  28102. },
  28103. lineTo: function ( x, y ) {
  28104. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  28105. this.curves.push( curve );
  28106. this.currentPoint.set( x, y );
  28107. },
  28108. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  28109. var curve = new QuadraticBezierCurve(
  28110. this.currentPoint.clone(),
  28111. new Vector2( aCPx, aCPy ),
  28112. new Vector2( aX, aY )
  28113. );
  28114. this.curves.push( curve );
  28115. this.currentPoint.set( aX, aY );
  28116. },
  28117. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28118. var curve = new CubicBezierCurve(
  28119. this.currentPoint.clone(),
  28120. new Vector2( aCP1x, aCP1y ),
  28121. new Vector2( aCP2x, aCP2y ),
  28122. new Vector2( aX, aY )
  28123. );
  28124. this.curves.push( curve );
  28125. this.currentPoint.set( aX, aY );
  28126. },
  28127. splineThru: function ( pts /*Array of Vector*/ ) {
  28128. var npts = [ this.currentPoint.clone() ].concat( pts );
  28129. var curve = new SplineCurve( npts );
  28130. this.curves.push( curve );
  28131. this.currentPoint.copy( pts[ pts.length - 1 ] );
  28132. },
  28133. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28134. var x0 = this.currentPoint.x;
  28135. var y0 = this.currentPoint.y;
  28136. this.absarc( aX + x0, aY + y0, aRadius,
  28137. aStartAngle, aEndAngle, aClockwise );
  28138. },
  28139. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28140. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28141. },
  28142. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28143. var x0 = this.currentPoint.x;
  28144. var y0 = this.currentPoint.y;
  28145. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28146. },
  28147. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28148. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28149. if ( this.curves.length > 0 ) {
  28150. // if a previous curve is present, attempt to join
  28151. var firstPoint = curve.getPoint( 0 );
  28152. if ( ! firstPoint.equals( this.currentPoint ) ) {
  28153. this.lineTo( firstPoint.x, firstPoint.y );
  28154. }
  28155. }
  28156. this.curves.push( curve );
  28157. var lastPoint = curve.getPoint( 1 );
  28158. this.currentPoint.copy( lastPoint );
  28159. },
  28160. copy: function ( source ) {
  28161. CurvePath.prototype.copy.call( this, source );
  28162. this.currentPoint.copy( source.currentPoint );
  28163. return this;
  28164. },
  28165. toJSON: function () {
  28166. var data = CurvePath.prototype.toJSON.call( this );
  28167. data.currentPoint = this.currentPoint.toArray();
  28168. return data;
  28169. },
  28170. fromJSON: function ( json ) {
  28171. CurvePath.prototype.fromJSON.call( this, json );
  28172. this.currentPoint.fromArray( json.currentPoint );
  28173. return this;
  28174. }
  28175. } );
  28176. /**
  28177. * @author zz85 / http://www.lab4games.net/zz85/blog
  28178. * Defines a 2d shape plane using paths.
  28179. **/
  28180. // STEP 1 Create a path.
  28181. // STEP 2 Turn path into shape.
  28182. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  28183. // STEP 3a - Extract points from each shape, turn to vertices
  28184. // STEP 3b - Triangulate each shape, add faces.
  28185. function Shape( points ) {
  28186. Path.call( this, points );
  28187. this.uuid = _Math.generateUUID();
  28188. this.type = 'Shape';
  28189. this.holes = [];
  28190. }
  28191. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  28192. constructor: Shape,
  28193. getPointsHoles: function ( divisions ) {
  28194. var holesPts = [];
  28195. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  28196. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  28197. }
  28198. return holesPts;
  28199. },
  28200. // get points of shape and holes (keypoints based on segments parameter)
  28201. extractPoints: function ( divisions ) {
  28202. return {
  28203. shape: this.getPoints( divisions ),
  28204. holes: this.getPointsHoles( divisions )
  28205. };
  28206. },
  28207. copy: function ( source ) {
  28208. Path.prototype.copy.call( this, source );
  28209. this.holes = [];
  28210. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  28211. var hole = source.holes[ i ];
  28212. this.holes.push( hole.clone() );
  28213. }
  28214. return this;
  28215. },
  28216. toJSON: function () {
  28217. var data = Path.prototype.toJSON.call( this );
  28218. data.uuid = this.uuid;
  28219. data.holes = [];
  28220. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  28221. var hole = this.holes[ i ];
  28222. data.holes.push( hole.toJSON() );
  28223. }
  28224. return data;
  28225. },
  28226. fromJSON: function ( json ) {
  28227. Path.prototype.fromJSON.call( this, json );
  28228. this.uuid = json.uuid;
  28229. this.holes = [];
  28230. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  28231. var hole = json.holes[ i ];
  28232. this.holes.push( new Path().fromJSON( hole ) );
  28233. }
  28234. return this;
  28235. }
  28236. } );
  28237. /**
  28238. * @author mrdoob / http://mrdoob.com/
  28239. * @author alteredq / http://alteredqualia.com/
  28240. */
  28241. function Light( color, intensity ) {
  28242. Object3D.call( this );
  28243. this.type = 'Light';
  28244. this.color = new Color( color );
  28245. this.intensity = intensity !== undefined ? intensity : 1;
  28246. this.receiveShadow = undefined;
  28247. }
  28248. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28249. constructor: Light,
  28250. isLight: true,
  28251. copy: function ( source ) {
  28252. Object3D.prototype.copy.call( this, source );
  28253. this.color.copy( source.color );
  28254. this.intensity = source.intensity;
  28255. return this;
  28256. },
  28257. toJSON: function ( meta ) {
  28258. var data = Object3D.prototype.toJSON.call( this, meta );
  28259. data.object.color = this.color.getHex();
  28260. data.object.intensity = this.intensity;
  28261. if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); }
  28262. if ( this.distance !== undefined ) { data.object.distance = this.distance; }
  28263. if ( this.angle !== undefined ) { data.object.angle = this.angle; }
  28264. if ( this.decay !== undefined ) { data.object.decay = this.decay; }
  28265. if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; }
  28266. if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); }
  28267. return data;
  28268. }
  28269. } );
  28270. /**
  28271. * @author alteredq / http://alteredqualia.com/
  28272. */
  28273. function HemisphereLight( skyColor, groundColor, intensity ) {
  28274. Light.call( this, skyColor, intensity );
  28275. this.type = 'HemisphereLight';
  28276. this.castShadow = undefined;
  28277. this.position.copy( Object3D.DefaultUp );
  28278. this.updateMatrix();
  28279. this.groundColor = new Color( groundColor );
  28280. }
  28281. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28282. constructor: HemisphereLight,
  28283. isHemisphereLight: true,
  28284. copy: function ( source ) {
  28285. Light.prototype.copy.call( this, source );
  28286. this.groundColor.copy( source.groundColor );
  28287. return this;
  28288. }
  28289. } );
  28290. /**
  28291. * @author mrdoob / http://mrdoob.com/
  28292. */
  28293. function LightShadow( camera ) {
  28294. this.camera = camera;
  28295. this.bias = 0;
  28296. this.radius = 1;
  28297. this.mapSize = new Vector2( 512, 512 );
  28298. this.map = null;
  28299. this.mapPass = null;
  28300. this.matrix = new Matrix4();
  28301. this._frustum = new Frustum();
  28302. this._frameExtents = new Vector2( 1, 1 );
  28303. this._viewportCount = 1;
  28304. this._viewports = [
  28305. new Vector4( 0, 0, 1, 1 )
  28306. ];
  28307. }
  28308. Object.assign( LightShadow.prototype, {
  28309. _projScreenMatrix: new Matrix4(),
  28310. _lightPositionWorld: new Vector3(),
  28311. _lookTarget: new Vector3(),
  28312. getViewportCount: function () {
  28313. return this._viewportCount;
  28314. },
  28315. getFrustum: function () {
  28316. return this._frustum;
  28317. },
  28318. updateMatrices: function ( light ) {
  28319. var shadowCamera = this.camera,
  28320. shadowMatrix = this.matrix,
  28321. projScreenMatrix = this._projScreenMatrix,
  28322. lookTarget = this._lookTarget,
  28323. lightPositionWorld = this._lightPositionWorld;
  28324. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  28325. shadowCamera.position.copy( lightPositionWorld );
  28326. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  28327. shadowCamera.lookAt( lookTarget );
  28328. shadowCamera.updateMatrixWorld();
  28329. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  28330. this._frustum.setFromMatrix( projScreenMatrix );
  28331. shadowMatrix.set(
  28332. 0.5, 0.0, 0.0, 0.5,
  28333. 0.0, 0.5, 0.0, 0.5,
  28334. 0.0, 0.0, 0.5, 0.5,
  28335. 0.0, 0.0, 0.0, 1.0
  28336. );
  28337. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  28338. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  28339. },
  28340. getViewport: function ( viewportIndex ) {
  28341. return this._viewports[ viewportIndex ];
  28342. },
  28343. getFrameExtents: function () {
  28344. return this._frameExtents;
  28345. },
  28346. copy: function ( source ) {
  28347. this.camera = source.camera.clone();
  28348. this.bias = source.bias;
  28349. this.radius = source.radius;
  28350. this.mapSize.copy( source.mapSize );
  28351. return this;
  28352. },
  28353. clone: function () {
  28354. return new this.constructor().copy( this );
  28355. },
  28356. toJSON: function () {
  28357. var object = {};
  28358. if ( this.bias !== 0 ) { object.bias = this.bias; }
  28359. if ( this.radius !== 1 ) { object.radius = this.radius; }
  28360. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); }
  28361. object.camera = this.camera.toJSON( false ).object;
  28362. delete object.camera.matrix;
  28363. return object;
  28364. }
  28365. } );
  28366. /**
  28367. * @author mrdoob / http://mrdoob.com/
  28368. */
  28369. function SpotLightShadow() {
  28370. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  28371. }
  28372. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  28373. constructor: SpotLightShadow,
  28374. isSpotLightShadow: true,
  28375. updateMatrices: function ( light, viewCamera, viewportIndex ) {
  28376. var camera = this.camera;
  28377. var fov = _Math.RAD2DEG * 2 * light.angle;
  28378. var aspect = this.mapSize.width / this.mapSize.height;
  28379. var far = light.distance || camera.far;
  28380. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  28381. camera.fov = fov;
  28382. camera.aspect = aspect;
  28383. camera.far = far;
  28384. camera.updateProjectionMatrix();
  28385. }
  28386. LightShadow.prototype.updateMatrices.call( this, light, viewCamera, viewportIndex );
  28387. }
  28388. } );
  28389. /**
  28390. * @author alteredq / http://alteredqualia.com/
  28391. */
  28392. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  28393. Light.call( this, color, intensity );
  28394. this.type = 'SpotLight';
  28395. this.position.copy( Object3D.DefaultUp );
  28396. this.updateMatrix();
  28397. this.target = new Object3D();
  28398. Object.defineProperty( this, 'power', {
  28399. get: function () {
  28400. // intensity = power per solid angle.
  28401. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28402. return this.intensity * Math.PI;
  28403. },
  28404. set: function ( power ) {
  28405. // intensity = power per solid angle.
  28406. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28407. this.intensity = power / Math.PI;
  28408. }
  28409. } );
  28410. this.distance = ( distance !== undefined ) ? distance : 0;
  28411. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  28412. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  28413. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  28414. this.shadow = new SpotLightShadow();
  28415. }
  28416. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28417. constructor: SpotLight,
  28418. isSpotLight: true,
  28419. copy: function ( source ) {
  28420. Light.prototype.copy.call( this, source );
  28421. this.distance = source.distance;
  28422. this.angle = source.angle;
  28423. this.penumbra = source.penumbra;
  28424. this.decay = source.decay;
  28425. this.target = source.target.clone();
  28426. this.shadow = source.shadow.clone();
  28427. return this;
  28428. }
  28429. } );
  28430. function PointLightShadow() {
  28431. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  28432. this._frameExtents = new Vector2( 4, 2 );
  28433. this._viewportCount = 6;
  28434. this._viewports = [
  28435. // These viewports map a cube-map onto a 2D texture with the
  28436. // following orientation:
  28437. //
  28438. // xzXZ
  28439. // y Y
  28440. //
  28441. // X - Positive x direction
  28442. // x - Negative x direction
  28443. // Y - Positive y direction
  28444. // y - Negative y direction
  28445. // Z - Positive z direction
  28446. // z - Negative z direction
  28447. // positive X
  28448. new Vector4( 2, 1, 1, 1 ),
  28449. // negative X
  28450. new Vector4( 0, 1, 1, 1 ),
  28451. // positive Z
  28452. new Vector4( 3, 1, 1, 1 ),
  28453. // negative Z
  28454. new Vector4( 1, 1, 1, 1 ),
  28455. // positive Y
  28456. new Vector4( 3, 0, 1, 1 ),
  28457. // negative Y
  28458. new Vector4( 1, 0, 1, 1 )
  28459. ];
  28460. this._cubeDirections = [
  28461. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  28462. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  28463. ];
  28464. this._cubeUps = [
  28465. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  28466. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  28467. ];
  28468. }
  28469. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  28470. constructor: PointLightShadow,
  28471. isPointLightShadow: true,
  28472. updateMatrices: function ( light, viewCamera, viewportIndex ) {
  28473. var camera = this.camera,
  28474. shadowMatrix = this.matrix,
  28475. lightPositionWorld = this._lightPositionWorld,
  28476. lookTarget = this._lookTarget,
  28477. projScreenMatrix = this._projScreenMatrix;
  28478. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  28479. camera.position.copy( lightPositionWorld );
  28480. lookTarget.copy( camera.position );
  28481. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  28482. camera.up.copy( this._cubeUps[ viewportIndex ] );
  28483. camera.lookAt( lookTarget );
  28484. camera.updateMatrixWorld();
  28485. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  28486. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  28487. this._frustum.setFromMatrix( projScreenMatrix );
  28488. }
  28489. } );
  28490. /**
  28491. * @author mrdoob / http://mrdoob.com/
  28492. */
  28493. function PointLight( color, intensity, distance, decay ) {
  28494. Light.call( this, color, intensity );
  28495. this.type = 'PointLight';
  28496. Object.defineProperty( this, 'power', {
  28497. get: function () {
  28498. // intensity = power per solid angle.
  28499. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28500. return this.intensity * 4 * Math.PI;
  28501. },
  28502. set: function ( power ) {
  28503. // intensity = power per solid angle.
  28504. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28505. this.intensity = power / ( 4 * Math.PI );
  28506. }
  28507. } );
  28508. this.distance = ( distance !== undefined ) ? distance : 0;
  28509. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  28510. this.shadow = new PointLightShadow();
  28511. }
  28512. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28513. constructor: PointLight,
  28514. isPointLight: true,
  28515. copy: function ( source ) {
  28516. Light.prototype.copy.call( this, source );
  28517. this.distance = source.distance;
  28518. this.decay = source.decay;
  28519. this.shadow = source.shadow.clone();
  28520. return this;
  28521. }
  28522. } );
  28523. /**
  28524. * @author alteredq / http://alteredqualia.com/
  28525. * @author arose / http://github.com/arose
  28526. */
  28527. function OrthographicCamera( left, right, top, bottom, near, far ) {
  28528. Camera.call( this );
  28529. this.type = 'OrthographicCamera';
  28530. this.zoom = 1;
  28531. this.view = null;
  28532. this.left = ( left !== undefined ) ? left : - 1;
  28533. this.right = ( right !== undefined ) ? right : 1;
  28534. this.top = ( top !== undefined ) ? top : 1;
  28535. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  28536. this.near = ( near !== undefined ) ? near : 0.1;
  28537. this.far = ( far !== undefined ) ? far : 2000;
  28538. this.updateProjectionMatrix();
  28539. }
  28540. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  28541. constructor: OrthographicCamera,
  28542. isOrthographicCamera: true,
  28543. copy: function ( source, recursive ) {
  28544. Camera.prototype.copy.call( this, source, recursive );
  28545. this.left = source.left;
  28546. this.right = source.right;
  28547. this.top = source.top;
  28548. this.bottom = source.bottom;
  28549. this.near = source.near;
  28550. this.far = source.far;
  28551. this.zoom = source.zoom;
  28552. this.view = source.view === null ? null : Object.assign( {}, source.view );
  28553. return this;
  28554. },
  28555. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  28556. if ( this.view === null ) {
  28557. this.view = {
  28558. enabled: true,
  28559. fullWidth: 1,
  28560. fullHeight: 1,
  28561. offsetX: 0,
  28562. offsetY: 0,
  28563. width: 1,
  28564. height: 1
  28565. };
  28566. }
  28567. this.view.enabled = true;
  28568. this.view.fullWidth = fullWidth;
  28569. this.view.fullHeight = fullHeight;
  28570. this.view.offsetX = x;
  28571. this.view.offsetY = y;
  28572. this.view.width = width;
  28573. this.view.height = height;
  28574. this.updateProjectionMatrix();
  28575. },
  28576. clearViewOffset: function () {
  28577. if ( this.view !== null ) {
  28578. this.view.enabled = false;
  28579. }
  28580. this.updateProjectionMatrix();
  28581. },
  28582. updateProjectionMatrix: function () {
  28583. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  28584. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  28585. var cx = ( this.right + this.left ) / 2;
  28586. var cy = ( this.top + this.bottom ) / 2;
  28587. var left = cx - dx;
  28588. var right = cx + dx;
  28589. var top = cy + dy;
  28590. var bottom = cy - dy;
  28591. if ( this.view !== null && this.view.enabled ) {
  28592. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  28593. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  28594. var scaleW = ( this.right - this.left ) / this.view.width;
  28595. var scaleH = ( this.top - this.bottom ) / this.view.height;
  28596. left += scaleW * ( this.view.offsetX / zoomW );
  28597. right = left + scaleW * ( this.view.width / zoomW );
  28598. top -= scaleH * ( this.view.offsetY / zoomH );
  28599. bottom = top - scaleH * ( this.view.height / zoomH );
  28600. }
  28601. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  28602. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  28603. },
  28604. toJSON: function ( meta ) {
  28605. var data = Object3D.prototype.toJSON.call( this, meta );
  28606. data.object.zoom = this.zoom;
  28607. data.object.left = this.left;
  28608. data.object.right = this.right;
  28609. data.object.top = this.top;
  28610. data.object.bottom = this.bottom;
  28611. data.object.near = this.near;
  28612. data.object.far = this.far;
  28613. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  28614. return data;
  28615. }
  28616. } );
  28617. /**
  28618. * @author mrdoob / http://mrdoob.com/
  28619. */
  28620. function DirectionalLightShadow() {
  28621. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  28622. }
  28623. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  28624. constructor: DirectionalLightShadow,
  28625. isDirectionalLightShadow: true,
  28626. updateMatrices: function ( light, viewCamera, viewportIndex ) {
  28627. LightShadow.prototype.updateMatrices.call( this, light, viewCamera, viewportIndex );
  28628. }
  28629. } );
  28630. /**
  28631. * @author mrdoob / http://mrdoob.com/
  28632. * @author alteredq / http://alteredqualia.com/
  28633. */
  28634. function DirectionalLight( color, intensity ) {
  28635. Light.call( this, color, intensity );
  28636. this.type = 'DirectionalLight';
  28637. this.position.copy( Object3D.DefaultUp );
  28638. this.updateMatrix();
  28639. this.target = new Object3D();
  28640. this.shadow = new DirectionalLightShadow();
  28641. }
  28642. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28643. constructor: DirectionalLight,
  28644. isDirectionalLight: true,
  28645. copy: function ( source ) {
  28646. Light.prototype.copy.call( this, source );
  28647. this.target = source.target.clone();
  28648. this.shadow = source.shadow.clone();
  28649. return this;
  28650. }
  28651. } );
  28652. /**
  28653. * @author mrdoob / http://mrdoob.com/
  28654. */
  28655. function AmbientLight( color, intensity ) {
  28656. Light.call( this, color, intensity );
  28657. this.type = 'AmbientLight';
  28658. this.castShadow = undefined;
  28659. }
  28660. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28661. constructor: AmbientLight,
  28662. isAmbientLight: true
  28663. } );
  28664. /**
  28665. * @author abelnation / http://github.com/abelnation
  28666. */
  28667. function RectAreaLight( color, intensity, width, height ) {
  28668. Light.call( this, color, intensity );
  28669. this.type = 'RectAreaLight';
  28670. this.width = ( width !== undefined ) ? width : 10;
  28671. this.height = ( height !== undefined ) ? height : 10;
  28672. }
  28673. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28674. constructor: RectAreaLight,
  28675. isRectAreaLight: true,
  28676. copy: function ( source ) {
  28677. Light.prototype.copy.call( this, source );
  28678. this.width = source.width;
  28679. this.height = source.height;
  28680. return this;
  28681. },
  28682. toJSON: function ( meta ) {
  28683. var data = Light.prototype.toJSON.call( this, meta );
  28684. data.object.width = this.width;
  28685. data.object.height = this.height;
  28686. return data;
  28687. }
  28688. } );
  28689. /**
  28690. * @author mrdoob / http://mrdoob.com/
  28691. */
  28692. function MaterialLoader( manager ) {
  28693. Loader.call( this, manager );
  28694. this.textures = {};
  28695. }
  28696. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  28697. constructor: MaterialLoader,
  28698. load: function ( url, onLoad, onProgress, onError ) {
  28699. var scope = this;
  28700. var loader = new FileLoader( scope.manager );
  28701. loader.setPath( scope.path );
  28702. loader.load( url, function ( text ) {
  28703. onLoad( scope.parse( JSON.parse( text ) ) );
  28704. }, onProgress, onError );
  28705. },
  28706. parse: function ( json ) {
  28707. var textures = this.textures;
  28708. function getTexture( name ) {
  28709. if ( textures[ name ] === undefined ) {
  28710. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  28711. }
  28712. return textures[ name ];
  28713. }
  28714. var material = new Materials[ json.type ]();
  28715. if ( json.uuid !== undefined ) { material.uuid = json.uuid; }
  28716. if ( json.name !== undefined ) { material.name = json.name; }
  28717. if ( json.color !== undefined ) { material.color.setHex( json.color ); }
  28718. if ( json.roughness !== undefined ) { material.roughness = json.roughness; }
  28719. if ( json.metalness !== undefined ) { material.metalness = json.metalness; }
  28720. if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); }
  28721. if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); }
  28722. if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); }
  28723. if ( json.shininess !== undefined ) { material.shininess = json.shininess; }
  28724. if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; }
  28725. if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; }
  28726. if ( json.vertexColors !== undefined ) { material.vertexColors = json.vertexColors; }
  28727. if ( json.fog !== undefined ) { material.fog = json.fog; }
  28728. if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; }
  28729. if ( json.blending !== undefined ) { material.blending = json.blending; }
  28730. if ( json.combine !== undefined ) { material.combine = json.combine; }
  28731. if ( json.side !== undefined ) { material.side = json.side; }
  28732. if ( json.opacity !== undefined ) { material.opacity = json.opacity; }
  28733. if ( json.transparent !== undefined ) { material.transparent = json.transparent; }
  28734. if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; }
  28735. if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; }
  28736. if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; }
  28737. if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; }
  28738. if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; }
  28739. if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; }
  28740. if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; }
  28741. if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; }
  28742. if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; }
  28743. if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; }
  28744. if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; }
  28745. if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; }
  28746. if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; }
  28747. if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; }
  28748. if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; }
  28749. if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; }
  28750. if ( json.rotation !== undefined ) { material.rotation = json.rotation; }
  28751. if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; }
  28752. if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; }
  28753. if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; }
  28754. if ( json.scale !== undefined ) { material.scale = json.scale; }
  28755. if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; }
  28756. if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; }
  28757. if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; }
  28758. if ( json.skinning !== undefined ) { material.skinning = json.skinning; }
  28759. if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; }
  28760. if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; }
  28761. if ( json.dithering !== undefined ) { material.dithering = json.dithering; }
  28762. if ( json.visible !== undefined ) { material.visible = json.visible; }
  28763. if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; }
  28764. if ( json.userData !== undefined ) { material.userData = json.userData; }
  28765. // Shader Material
  28766. if ( json.uniforms !== undefined ) {
  28767. for ( var name in json.uniforms ) {
  28768. var uniform = json.uniforms[ name ];
  28769. material.uniforms[ name ] = {};
  28770. switch ( uniform.type ) {
  28771. case 't':
  28772. material.uniforms[ name ].value = getTexture( uniform.value );
  28773. break;
  28774. case 'c':
  28775. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  28776. break;
  28777. case 'v2':
  28778. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  28779. break;
  28780. case 'v3':
  28781. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  28782. break;
  28783. case 'v4':
  28784. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  28785. break;
  28786. case 'm3':
  28787. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  28788. case 'm4':
  28789. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  28790. break;
  28791. default:
  28792. material.uniforms[ name ].value = uniform.value;
  28793. }
  28794. }
  28795. }
  28796. if ( json.defines !== undefined ) { material.defines = json.defines; }
  28797. if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; }
  28798. if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; }
  28799. if ( json.extensions !== undefined ) {
  28800. for ( var key in json.extensions ) {
  28801. material.extensions[ key ] = json.extensions[ key ];
  28802. }
  28803. }
  28804. // Deprecated
  28805. if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading
  28806. // for PointsMaterial
  28807. if ( json.size !== undefined ) { material.size = json.size; }
  28808. if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; }
  28809. // maps
  28810. if ( json.map !== undefined ) { material.map = getTexture( json.map ); }
  28811. if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); }
  28812. if ( json.alphaMap !== undefined ) {
  28813. material.alphaMap = getTexture( json.alphaMap );
  28814. material.transparent = true;
  28815. }
  28816. if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); }
  28817. if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; }
  28818. if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); }
  28819. if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; }
  28820. if ( json.normalScale !== undefined ) {
  28821. var normalScale = json.normalScale;
  28822. if ( Array.isArray( normalScale ) === false ) {
  28823. // Blender exporter used to export a scalar. See #7459
  28824. normalScale = [ normalScale, normalScale ];
  28825. }
  28826. material.normalScale = new Vector2().fromArray( normalScale );
  28827. }
  28828. if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); }
  28829. if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; }
  28830. if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; }
  28831. if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); }
  28832. if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); }
  28833. if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); }
  28834. if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; }
  28835. if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); }
  28836. if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); }
  28837. if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; }
  28838. if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; }
  28839. if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; }
  28840. if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); }
  28841. if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; }
  28842. if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); }
  28843. if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; }
  28844. if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); }
  28845. if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); }
  28846. if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); }
  28847. return material;
  28848. },
  28849. setTextures: function ( value ) {
  28850. this.textures = value;
  28851. return this;
  28852. }
  28853. } );
  28854. /**
  28855. * @author Don McCurdy / https://www.donmccurdy.com
  28856. */
  28857. var LoaderUtils = {
  28858. decodeText: function ( array ) {
  28859. if ( typeof TextDecoder !== 'undefined' ) {
  28860. return new TextDecoder().decode( array );
  28861. }
  28862. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  28863. // throws a "maximum call stack size exceeded" error for large arrays.
  28864. var s = '';
  28865. for ( var i = 0, il = array.length; i < il; i ++ ) {
  28866. // Implicitly assumes little-endian.
  28867. s += String.fromCharCode( array[ i ] );
  28868. }
  28869. try {
  28870. // merges multi-byte utf-8 characters.
  28871. return decodeURIComponent( escape( s ) );
  28872. } catch ( e ) { // see #16358
  28873. return s;
  28874. }
  28875. },
  28876. extractUrlBase: function ( url ) {
  28877. var index = url.lastIndexOf( '/' );
  28878. if ( index === - 1 ) { return './'; }
  28879. return url.substr( 0, index + 1 );
  28880. }
  28881. };
  28882. /**
  28883. * @author benaadams / https://twitter.com/ben_a_adams
  28884. */
  28885. function InstancedBufferGeometry() {
  28886. BufferGeometry.call( this );
  28887. this.type = 'InstancedBufferGeometry';
  28888. this.maxInstancedCount = undefined;
  28889. }
  28890. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  28891. constructor: InstancedBufferGeometry,
  28892. isInstancedBufferGeometry: true,
  28893. copy: function ( source ) {
  28894. BufferGeometry.prototype.copy.call( this, source );
  28895. this.maxInstancedCount = source.maxInstancedCount;
  28896. return this;
  28897. },
  28898. clone: function () {
  28899. return new this.constructor().copy( this );
  28900. },
  28901. toJSON: function () {
  28902. var data = BufferGeometry.prototype.toJSON.call( this );
  28903. data.maxInstancedCount = this.maxInstancedCount;
  28904. data.isInstancedBufferGeometry = true;
  28905. return data;
  28906. }
  28907. } );
  28908. /**
  28909. * @author benaadams / https://twitter.com/ben_a_adams
  28910. */
  28911. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  28912. if ( typeof ( normalized ) === 'number' ) {
  28913. meshPerAttribute = normalized;
  28914. normalized = false;
  28915. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  28916. }
  28917. BufferAttribute.call( this, array, itemSize, normalized );
  28918. this.meshPerAttribute = meshPerAttribute || 1;
  28919. }
  28920. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  28921. constructor: InstancedBufferAttribute,
  28922. isInstancedBufferAttribute: true,
  28923. copy: function ( source ) {
  28924. BufferAttribute.prototype.copy.call( this, source );
  28925. this.meshPerAttribute = source.meshPerAttribute;
  28926. return this;
  28927. },
  28928. toJSON: function () {
  28929. var data = BufferAttribute.prototype.toJSON.call( this );
  28930. data.meshPerAttribute = this.meshPerAttribute;
  28931. data.isInstancedBufferAttribute = true;
  28932. return data;
  28933. }
  28934. } );
  28935. /**
  28936. * @author mrdoob / http://mrdoob.com/
  28937. */
  28938. function BufferGeometryLoader( manager ) {
  28939. Loader.call( this, manager );
  28940. }
  28941. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  28942. constructor: BufferGeometryLoader,
  28943. load: function ( url, onLoad, onProgress, onError ) {
  28944. var scope = this;
  28945. var loader = new FileLoader( scope.manager );
  28946. loader.setPath( scope.path );
  28947. loader.load( url, function ( text ) {
  28948. onLoad( scope.parse( JSON.parse( text ) ) );
  28949. }, onProgress, onError );
  28950. },
  28951. parse: function ( json ) {
  28952. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  28953. var index = json.data.index;
  28954. if ( index !== undefined ) {
  28955. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  28956. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  28957. }
  28958. var attributes = json.data.attributes;
  28959. for ( var key in attributes ) {
  28960. var attribute = attributes[ key ];
  28961. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  28962. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  28963. var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  28964. if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
  28965. geometry.addAttribute( key, bufferAttribute );
  28966. }
  28967. var morphAttributes = json.data.morphAttributes;
  28968. if ( morphAttributes ) {
  28969. for ( var key in morphAttributes ) {
  28970. var attributeArray = morphAttributes[ key ];
  28971. var array = [];
  28972. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  28973. var attribute = attributeArray[ i ];
  28974. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  28975. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  28976. if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
  28977. array.push( bufferAttribute );
  28978. }
  28979. geometry.morphAttributes[ key ] = array;
  28980. }
  28981. }
  28982. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  28983. if ( groups !== undefined ) {
  28984. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  28985. var group = groups[ i ];
  28986. geometry.addGroup( group.start, group.count, group.materialIndex );
  28987. }
  28988. }
  28989. var boundingSphere = json.data.boundingSphere;
  28990. if ( boundingSphere !== undefined ) {
  28991. var center = new Vector3();
  28992. if ( boundingSphere.center !== undefined ) {
  28993. center.fromArray( boundingSphere.center );
  28994. }
  28995. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  28996. }
  28997. if ( json.name ) { geometry.name = json.name; }
  28998. if ( json.userData ) { geometry.userData = json.userData; }
  28999. return geometry;
  29000. }
  29001. } );
  29002. var TYPED_ARRAYS = {
  29003. Int8Array: Int8Array,
  29004. Uint8Array: Uint8Array,
  29005. // Workaround for IE11 pre KB2929437. See #11440
  29006. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  29007. Int16Array: Int16Array,
  29008. Uint16Array: Uint16Array,
  29009. Int32Array: Int32Array,
  29010. Uint32Array: Uint32Array,
  29011. Float32Array: Float32Array,
  29012. Float64Array: Float64Array
  29013. };
  29014. /**
  29015. * @author mrdoob / http://mrdoob.com/
  29016. */
  29017. function ObjectLoader( manager ) {
  29018. Loader.call( this, manager );
  29019. }
  29020. ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29021. constructor: ObjectLoader,
  29022. load: function ( url, onLoad, onProgress, onError ) {
  29023. var scope = this;
  29024. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  29025. this.resourcePath = this.resourcePath || path;
  29026. var loader = new FileLoader( scope.manager );
  29027. loader.setPath( this.path );
  29028. loader.load( url, function ( text ) {
  29029. var json = null;
  29030. try {
  29031. json = JSON.parse( text );
  29032. } catch ( error ) {
  29033. if ( onError !== undefined ) { onError( error ); }
  29034. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  29035. return;
  29036. }
  29037. var metadata = json.metadata;
  29038. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  29039. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  29040. return;
  29041. }
  29042. scope.parse( json, onLoad );
  29043. }, onProgress, onError );
  29044. },
  29045. parse: function ( json, onLoad ) {
  29046. var shapes = this.parseShape( json.shapes );
  29047. var geometries = this.parseGeometries( json.geometries, shapes );
  29048. var images = this.parseImages( json.images, function () {
  29049. if ( onLoad !== undefined ) { onLoad( object ); }
  29050. } );
  29051. var textures = this.parseTextures( json.textures, images );
  29052. var materials = this.parseMaterials( json.materials, textures );
  29053. var object = this.parseObject( json.object, geometries, materials );
  29054. if ( json.animations ) {
  29055. object.animations = this.parseAnimations( json.animations );
  29056. }
  29057. if ( json.images === undefined || json.images.length === 0 ) {
  29058. if ( onLoad !== undefined ) { onLoad( object ); }
  29059. }
  29060. return object;
  29061. },
  29062. parseShape: function ( json ) {
  29063. var shapes = {};
  29064. if ( json !== undefined ) {
  29065. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29066. var shape = new Shape().fromJSON( json[ i ] );
  29067. shapes[ shape.uuid ] = shape;
  29068. }
  29069. }
  29070. return shapes;
  29071. },
  29072. parseGeometries: function ( json, shapes ) {
  29073. var geometries = {};
  29074. if ( json !== undefined ) {
  29075. var bufferGeometryLoader = new BufferGeometryLoader();
  29076. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29077. var geometry;
  29078. var data = json[ i ];
  29079. switch ( data.type ) {
  29080. case 'PlaneGeometry':
  29081. case 'PlaneBufferGeometry':
  29082. geometry = new Geometries[ data.type ](
  29083. data.width,
  29084. data.height,
  29085. data.widthSegments,
  29086. data.heightSegments
  29087. );
  29088. break;
  29089. case 'BoxGeometry':
  29090. case 'BoxBufferGeometry':
  29091. case 'CubeGeometry': // backwards compatible
  29092. geometry = new Geometries[ data.type ](
  29093. data.width,
  29094. data.height,
  29095. data.depth,
  29096. data.widthSegments,
  29097. data.heightSegments,
  29098. data.depthSegments
  29099. );
  29100. break;
  29101. case 'CircleGeometry':
  29102. case 'CircleBufferGeometry':
  29103. geometry = new Geometries[ data.type ](
  29104. data.radius,
  29105. data.segments,
  29106. data.thetaStart,
  29107. data.thetaLength
  29108. );
  29109. break;
  29110. case 'CylinderGeometry':
  29111. case 'CylinderBufferGeometry':
  29112. geometry = new Geometries[ data.type ](
  29113. data.radiusTop,
  29114. data.radiusBottom,
  29115. data.height,
  29116. data.radialSegments,
  29117. data.heightSegments,
  29118. data.openEnded,
  29119. data.thetaStart,
  29120. data.thetaLength
  29121. );
  29122. break;
  29123. case 'ConeGeometry':
  29124. case 'ConeBufferGeometry':
  29125. geometry = new Geometries[ data.type ](
  29126. data.radius,
  29127. data.height,
  29128. data.radialSegments,
  29129. data.heightSegments,
  29130. data.openEnded,
  29131. data.thetaStart,
  29132. data.thetaLength
  29133. );
  29134. break;
  29135. case 'SphereGeometry':
  29136. case 'SphereBufferGeometry':
  29137. geometry = new Geometries[ data.type ](
  29138. data.radius,
  29139. data.widthSegments,
  29140. data.heightSegments,
  29141. data.phiStart,
  29142. data.phiLength,
  29143. data.thetaStart,
  29144. data.thetaLength
  29145. );
  29146. break;
  29147. case 'DodecahedronGeometry':
  29148. case 'DodecahedronBufferGeometry':
  29149. case 'IcosahedronGeometry':
  29150. case 'IcosahedronBufferGeometry':
  29151. case 'OctahedronGeometry':
  29152. case 'OctahedronBufferGeometry':
  29153. case 'TetrahedronGeometry':
  29154. case 'TetrahedronBufferGeometry':
  29155. geometry = new Geometries[ data.type ](
  29156. data.radius,
  29157. data.detail
  29158. );
  29159. break;
  29160. case 'RingGeometry':
  29161. case 'RingBufferGeometry':
  29162. geometry = new Geometries[ data.type ](
  29163. data.innerRadius,
  29164. data.outerRadius,
  29165. data.thetaSegments,
  29166. data.phiSegments,
  29167. data.thetaStart,
  29168. data.thetaLength
  29169. );
  29170. break;
  29171. case 'TorusGeometry':
  29172. case 'TorusBufferGeometry':
  29173. geometry = new Geometries[ data.type ](
  29174. data.radius,
  29175. data.tube,
  29176. data.radialSegments,
  29177. data.tubularSegments,
  29178. data.arc
  29179. );
  29180. break;
  29181. case 'TorusKnotGeometry':
  29182. case 'TorusKnotBufferGeometry':
  29183. geometry = new Geometries[ data.type ](
  29184. data.radius,
  29185. data.tube,
  29186. data.tubularSegments,
  29187. data.radialSegments,
  29188. data.p,
  29189. data.q
  29190. );
  29191. break;
  29192. case 'TubeGeometry':
  29193. case 'TubeBufferGeometry':
  29194. // This only works for built-in curves (e.g. CatmullRomCurve3).
  29195. // User defined curves or instances of CurvePath will not be deserialized.
  29196. geometry = new Geometries[ data.type ](
  29197. new Curves[ data.path.type ]().fromJSON( data.path ),
  29198. data.tubularSegments,
  29199. data.radius,
  29200. data.radialSegments,
  29201. data.closed
  29202. );
  29203. break;
  29204. case 'LatheGeometry':
  29205. case 'LatheBufferGeometry':
  29206. geometry = new Geometries[ data.type ](
  29207. data.points,
  29208. data.segments,
  29209. data.phiStart,
  29210. data.phiLength
  29211. );
  29212. break;
  29213. case 'PolyhedronGeometry':
  29214. case 'PolyhedronBufferGeometry':
  29215. geometry = new Geometries[ data.type ](
  29216. data.vertices,
  29217. data.indices,
  29218. data.radius,
  29219. data.details
  29220. );
  29221. break;
  29222. case 'ShapeGeometry':
  29223. case 'ShapeBufferGeometry':
  29224. var geometryShapes = [];
  29225. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  29226. var shape = shapes[ data.shapes[ j ] ];
  29227. geometryShapes.push( shape );
  29228. }
  29229. geometry = new Geometries[ data.type ](
  29230. geometryShapes,
  29231. data.curveSegments
  29232. );
  29233. break;
  29234. case 'ExtrudeGeometry':
  29235. case 'ExtrudeBufferGeometry':
  29236. var geometryShapes = [];
  29237. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  29238. var shape = shapes[ data.shapes[ j ] ];
  29239. geometryShapes.push( shape );
  29240. }
  29241. var extrudePath = data.options.extrudePath;
  29242. if ( extrudePath !== undefined ) {
  29243. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  29244. }
  29245. geometry = new Geometries[ data.type ](
  29246. geometryShapes,
  29247. data.options
  29248. );
  29249. break;
  29250. case 'BufferGeometry':
  29251. case 'InstancedBufferGeometry':
  29252. geometry = bufferGeometryLoader.parse( data );
  29253. break;
  29254. case 'Geometry':
  29255. if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) {
  29256. var geometryLoader = new THREE.LegacyJSONLoader();
  29257. geometry = geometryLoader.parse( data, this.resourcePath ).geometry;
  29258. } else {
  29259. console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' );
  29260. }
  29261. break;
  29262. default:
  29263. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  29264. continue;
  29265. }
  29266. geometry.uuid = data.uuid;
  29267. if ( data.name !== undefined ) { geometry.name = data.name; }
  29268. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; }
  29269. geometries[ data.uuid ] = geometry;
  29270. }
  29271. }
  29272. return geometries;
  29273. },
  29274. parseMaterials: function ( json, textures ) {
  29275. var cache = {}; // MultiMaterial
  29276. var materials = {};
  29277. if ( json !== undefined ) {
  29278. var loader = new MaterialLoader();
  29279. loader.setTextures( textures );
  29280. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29281. var data = json[ i ];
  29282. if ( data.type === 'MultiMaterial' ) {
  29283. // Deprecated
  29284. var array = [];
  29285. for ( var j = 0; j < data.materials.length; j ++ ) {
  29286. var material = data.materials[ j ];
  29287. if ( cache[ material.uuid ] === undefined ) {
  29288. cache[ material.uuid ] = loader.parse( material );
  29289. }
  29290. array.push( cache[ material.uuid ] );
  29291. }
  29292. materials[ data.uuid ] = array;
  29293. } else {
  29294. if ( cache[ data.uuid ] === undefined ) {
  29295. cache[ data.uuid ] = loader.parse( data );
  29296. }
  29297. materials[ data.uuid ] = cache[ data.uuid ];
  29298. }
  29299. }
  29300. }
  29301. return materials;
  29302. },
  29303. parseAnimations: function ( json ) {
  29304. var animations = [];
  29305. for ( var i = 0; i < json.length; i ++ ) {
  29306. var data = json[ i ];
  29307. var clip = AnimationClip.parse( data );
  29308. if ( data.uuid !== undefined ) { clip.uuid = data.uuid; }
  29309. animations.push( clip );
  29310. }
  29311. return animations;
  29312. },
  29313. parseImages: function ( json, onLoad ) {
  29314. var scope = this;
  29315. var images = {};
  29316. function loadImage( url ) {
  29317. scope.manager.itemStart( url );
  29318. return loader.load( url, function () {
  29319. scope.manager.itemEnd( url );
  29320. }, undefined, function () {
  29321. scope.manager.itemError( url );
  29322. scope.manager.itemEnd( url );
  29323. } );
  29324. }
  29325. if ( json !== undefined && json.length > 0 ) {
  29326. var manager = new LoadingManager( onLoad );
  29327. var loader = new ImageLoader( manager );
  29328. loader.setCrossOrigin( this.crossOrigin );
  29329. for ( var i = 0, il = json.length; i < il; i ++ ) {
  29330. var image = json[ i ];
  29331. var url = image.url;
  29332. if ( Array.isArray( url ) ) {
  29333. // load array of images e.g CubeTexture
  29334. images[ image.uuid ] = [];
  29335. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  29336. var currentUrl = url[ j ];
  29337. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  29338. images[ image.uuid ].push( loadImage( path ) );
  29339. }
  29340. } else {
  29341. // load single image
  29342. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  29343. images[ image.uuid ] = loadImage( path );
  29344. }
  29345. }
  29346. }
  29347. return images;
  29348. },
  29349. parseTextures: function ( json, images ) {
  29350. function parseConstant( value, type ) {
  29351. if ( typeof value === 'number' ) { return value; }
  29352. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  29353. return type[ value ];
  29354. }
  29355. var textures = {};
  29356. if ( json !== undefined ) {
  29357. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29358. var data = json[ i ];
  29359. if ( data.image === undefined ) {
  29360. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  29361. }
  29362. if ( images[ data.image ] === undefined ) {
  29363. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  29364. }
  29365. var texture;
  29366. if ( Array.isArray( images[ data.image ] ) ) {
  29367. texture = new CubeTexture( images[ data.image ] );
  29368. } else {
  29369. texture = new Texture( images[ data.image ] );
  29370. }
  29371. texture.needsUpdate = true;
  29372. texture.uuid = data.uuid;
  29373. if ( data.name !== undefined ) { texture.name = data.name; }
  29374. if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); }
  29375. if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); }
  29376. if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); }
  29377. if ( data.center !== undefined ) { texture.center.fromArray( data.center ); }
  29378. if ( data.rotation !== undefined ) { texture.rotation = data.rotation; }
  29379. if ( data.wrap !== undefined ) {
  29380. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  29381. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  29382. }
  29383. if ( data.format !== undefined ) { texture.format = data.format; }
  29384. if ( data.type !== undefined ) { texture.type = data.type; }
  29385. if ( data.encoding !== undefined ) { texture.encoding = data.encoding; }
  29386. if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); }
  29387. if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); }
  29388. if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; }
  29389. if ( data.flipY !== undefined ) { texture.flipY = data.flipY; }
  29390. if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; }
  29391. if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; }
  29392. textures[ data.uuid ] = texture;
  29393. }
  29394. }
  29395. return textures;
  29396. },
  29397. parseObject: function ( data, geometries, materials ) {
  29398. var object;
  29399. function getGeometry( name ) {
  29400. if ( geometries[ name ] === undefined ) {
  29401. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  29402. }
  29403. return geometries[ name ];
  29404. }
  29405. function getMaterial( name ) {
  29406. if ( name === undefined ) { return undefined; }
  29407. if ( Array.isArray( name ) ) {
  29408. var array = [];
  29409. for ( var i = 0, l = name.length; i < l; i ++ ) {
  29410. var uuid = name[ i ];
  29411. if ( materials[ uuid ] === undefined ) {
  29412. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  29413. }
  29414. array.push( materials[ uuid ] );
  29415. }
  29416. return array;
  29417. }
  29418. if ( materials[ name ] === undefined ) {
  29419. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  29420. }
  29421. return materials[ name ];
  29422. }
  29423. switch ( data.type ) {
  29424. case 'Scene':
  29425. object = new Scene();
  29426. if ( data.background !== undefined ) {
  29427. if ( Number.isInteger( data.background ) ) {
  29428. object.background = new Color( data.background );
  29429. }
  29430. }
  29431. if ( data.fog !== undefined ) {
  29432. if ( data.fog.type === 'Fog' ) {
  29433. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  29434. } else if ( data.fog.type === 'FogExp2' ) {
  29435. object.fog = new FogExp2( data.fog.color, data.fog.density );
  29436. }
  29437. }
  29438. break;
  29439. case 'PerspectiveCamera':
  29440. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  29441. if ( data.focus !== undefined ) { object.focus = data.focus; }
  29442. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  29443. if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; }
  29444. if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; }
  29445. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  29446. break;
  29447. case 'OrthographicCamera':
  29448. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  29449. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  29450. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  29451. break;
  29452. case 'AmbientLight':
  29453. object = new AmbientLight( data.color, data.intensity );
  29454. break;
  29455. case 'DirectionalLight':
  29456. object = new DirectionalLight( data.color, data.intensity );
  29457. break;
  29458. case 'PointLight':
  29459. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  29460. break;
  29461. case 'RectAreaLight':
  29462. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  29463. break;
  29464. case 'SpotLight':
  29465. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  29466. break;
  29467. case 'HemisphereLight':
  29468. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  29469. break;
  29470. case 'SkinnedMesh':
  29471. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  29472. case 'Mesh':
  29473. var geometry = getGeometry( data.geometry );
  29474. var material = getMaterial( data.material );
  29475. if ( geometry.bones && geometry.bones.length > 0 ) {
  29476. object = new SkinnedMesh( geometry, material );
  29477. } else {
  29478. object = new Mesh( geometry, material );
  29479. }
  29480. if ( data.drawMode !== undefined ) { object.setDrawMode( data.drawMode ); }
  29481. break;
  29482. case 'LOD':
  29483. object = new LOD();
  29484. break;
  29485. case 'Line':
  29486. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  29487. break;
  29488. case 'LineLoop':
  29489. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  29490. break;
  29491. case 'LineSegments':
  29492. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  29493. break;
  29494. case 'PointCloud':
  29495. case 'Points':
  29496. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  29497. break;
  29498. case 'Sprite':
  29499. object = new Sprite( getMaterial( data.material ) );
  29500. break;
  29501. case 'Group':
  29502. object = new Group();
  29503. break;
  29504. default:
  29505. object = new Object3D();
  29506. }
  29507. object.uuid = data.uuid;
  29508. if ( data.name !== undefined ) { object.name = data.name; }
  29509. if ( data.matrix !== undefined ) {
  29510. object.matrix.fromArray( data.matrix );
  29511. if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; }
  29512. if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); }
  29513. } else {
  29514. if ( data.position !== undefined ) { object.position.fromArray( data.position ); }
  29515. if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); }
  29516. if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); }
  29517. if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); }
  29518. }
  29519. if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; }
  29520. if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; }
  29521. if ( data.shadow ) {
  29522. if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; }
  29523. if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; }
  29524. if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); }
  29525. if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); }
  29526. }
  29527. if ( data.visible !== undefined ) { object.visible = data.visible; }
  29528. if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; }
  29529. if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; }
  29530. if ( data.userData !== undefined ) { object.userData = data.userData; }
  29531. if ( data.layers !== undefined ) { object.layers.mask = data.layers; }
  29532. if ( data.children !== undefined ) {
  29533. var children = data.children;
  29534. for ( var i = 0; i < children.length; i ++ ) {
  29535. object.add( this.parseObject( children[ i ], geometries, materials ) );
  29536. }
  29537. }
  29538. if ( data.type === 'LOD' ) {
  29539. var levels = data.levels;
  29540. for ( var l = 0; l < levels.length; l ++ ) {
  29541. var level = levels[ l ];
  29542. var child = object.getObjectByProperty( 'uuid', level.object );
  29543. if ( child !== undefined ) {
  29544. object.addLevel( child, level.distance );
  29545. }
  29546. }
  29547. }
  29548. return object;
  29549. }
  29550. } );
  29551. var TEXTURE_MAPPING = {
  29552. UVMapping: UVMapping,
  29553. CubeReflectionMapping: CubeReflectionMapping,
  29554. CubeRefractionMapping: CubeRefractionMapping,
  29555. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  29556. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  29557. SphericalReflectionMapping: SphericalReflectionMapping,
  29558. CubeUVReflectionMapping: CubeUVReflectionMapping,
  29559. CubeUVRefractionMapping: CubeUVRefractionMapping
  29560. };
  29561. var TEXTURE_WRAPPING = {
  29562. RepeatWrapping: RepeatWrapping,
  29563. ClampToEdgeWrapping: ClampToEdgeWrapping,
  29564. MirroredRepeatWrapping: MirroredRepeatWrapping
  29565. };
  29566. var TEXTURE_FILTER = {
  29567. NearestFilter: NearestFilter,
  29568. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  29569. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  29570. LinearFilter: LinearFilter,
  29571. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  29572. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  29573. };
  29574. /**
  29575. * @author thespite / http://clicktorelease.com/
  29576. */
  29577. function ImageBitmapLoader( manager ) {
  29578. if ( typeof createImageBitmap === 'undefined' ) {
  29579. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  29580. }
  29581. if ( typeof fetch === 'undefined' ) {
  29582. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  29583. }
  29584. Loader.call( this, manager );
  29585. this.options = undefined;
  29586. }
  29587. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29588. constructor: ImageBitmapLoader,
  29589. setOptions: function setOptions( options ) {
  29590. this.options = options;
  29591. return this;
  29592. },
  29593. load: function ( url, onLoad, onProgress, onError ) {
  29594. if ( url === undefined ) { url = ''; }
  29595. if ( this.path !== undefined ) { url = this.path + url; }
  29596. url = this.manager.resolveURL( url );
  29597. var scope = this;
  29598. var cached = Cache.get( url );
  29599. if ( cached !== undefined ) {
  29600. scope.manager.itemStart( url );
  29601. setTimeout( function () {
  29602. if ( onLoad ) { onLoad( cached ); }
  29603. scope.manager.itemEnd( url );
  29604. }, 0 );
  29605. return cached;
  29606. }
  29607. fetch( url ).then( function ( res ) {
  29608. return res.blob();
  29609. } ).then( function ( blob ) {
  29610. if ( scope.options === undefined ) {
  29611. // Workaround for FireFox. It causes an error if you pass options.
  29612. return createImageBitmap( blob );
  29613. } else {
  29614. return createImageBitmap( blob, scope.options );
  29615. }
  29616. } ).then( function ( imageBitmap ) {
  29617. Cache.add( url, imageBitmap );
  29618. if ( onLoad ) { onLoad( imageBitmap ); }
  29619. scope.manager.itemEnd( url );
  29620. } ).catch( function ( e ) {
  29621. if ( onError ) { onError( e ); }
  29622. scope.manager.itemError( url );
  29623. scope.manager.itemEnd( url );
  29624. } );
  29625. scope.manager.itemStart( url );
  29626. }
  29627. } );
  29628. /**
  29629. * @author zz85 / http://www.lab4games.net/zz85/blog
  29630. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  29631. **/
  29632. function ShapePath() {
  29633. this.type = 'ShapePath';
  29634. this.color = new Color();
  29635. this.subPaths = [];
  29636. this.currentPath = null;
  29637. }
  29638. Object.assign( ShapePath.prototype, {
  29639. moveTo: function ( x, y ) {
  29640. this.currentPath = new Path();
  29641. this.subPaths.push( this.currentPath );
  29642. this.currentPath.moveTo( x, y );
  29643. },
  29644. lineTo: function ( x, y ) {
  29645. this.currentPath.lineTo( x, y );
  29646. },
  29647. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  29648. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29649. },
  29650. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29651. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29652. },
  29653. splineThru: function ( pts ) {
  29654. this.currentPath.splineThru( pts );
  29655. },
  29656. toShapes: function ( isCCW, noHoles ) {
  29657. function toShapesNoHoles( inSubpaths ) {
  29658. var shapes = [];
  29659. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29660. var tmpPath = inSubpaths[ i ];
  29661. var tmpShape = new Shape();
  29662. tmpShape.curves = tmpPath.curves;
  29663. shapes.push( tmpShape );
  29664. }
  29665. return shapes;
  29666. }
  29667. function isPointInsidePolygon( inPt, inPolygon ) {
  29668. var polyLen = inPolygon.length;
  29669. // inPt on polygon contour => immediate success or
  29670. // toggling of inside/outside at every single! intersection point of an edge
  29671. // with the horizontal line through inPt, left of inPt
  29672. // not counting lowerY endpoints of edges and whole edges on that line
  29673. var inside = false;
  29674. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29675. var edgeLowPt = inPolygon[ p ];
  29676. var edgeHighPt = inPolygon[ q ];
  29677. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  29678. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  29679. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29680. // not parallel
  29681. if ( edgeDy < 0 ) {
  29682. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29683. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29684. }
  29685. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) { continue; }
  29686. if ( inPt.y === edgeLowPt.y ) {
  29687. if ( inPt.x === edgeLowPt.x ) { return true; } // inPt is on contour ?
  29688. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29689. } else {
  29690. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29691. if ( perpEdge === 0 ) { return true; } // inPt is on contour ?
  29692. if ( perpEdge < 0 ) { continue; }
  29693. inside = ! inside; // true intersection left of inPt
  29694. }
  29695. } else {
  29696. // parallel or collinear
  29697. if ( inPt.y !== edgeLowPt.y ) { continue; } // parallel
  29698. // edge lies on the same horizontal line as inPt
  29699. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29700. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) { return true; } // inPt: Point on contour !
  29701. // continue;
  29702. }
  29703. }
  29704. return inside;
  29705. }
  29706. var isClockWise = ShapeUtils.isClockWise;
  29707. var subPaths = this.subPaths;
  29708. if ( subPaths.length === 0 ) { return []; }
  29709. if ( noHoles === true ) { return toShapesNoHoles( subPaths ); }
  29710. var solid, tmpPath, tmpShape, shapes = [];
  29711. if ( subPaths.length === 1 ) {
  29712. tmpPath = subPaths[ 0 ];
  29713. tmpShape = new Shape();
  29714. tmpShape.curves = tmpPath.curves;
  29715. shapes.push( tmpShape );
  29716. return shapes;
  29717. }
  29718. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29719. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29720. // console.log("Holes first", holesFirst);
  29721. var betterShapeHoles = [];
  29722. var newShapes = [];
  29723. var newShapeHoles = [];
  29724. var mainIdx = 0;
  29725. var tmpPoints;
  29726. newShapes[ mainIdx ] = undefined;
  29727. newShapeHoles[ mainIdx ] = [];
  29728. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  29729. tmpPath = subPaths[ i ];
  29730. tmpPoints = tmpPath.getPoints();
  29731. solid = isClockWise( tmpPoints );
  29732. solid = isCCW ? ! solid : solid;
  29733. if ( solid ) {
  29734. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) { mainIdx ++; }
  29735. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29736. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29737. if ( holesFirst ) { mainIdx ++; }
  29738. newShapeHoles[ mainIdx ] = [];
  29739. //console.log('cw', i);
  29740. } else {
  29741. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29742. //console.log('ccw', i);
  29743. }
  29744. }
  29745. // only Holes? -> probably all Shapes with wrong orientation
  29746. if ( ! newShapes[ 0 ] ) { return toShapesNoHoles( subPaths ); }
  29747. if ( newShapes.length > 1 ) {
  29748. var ambiguous = false;
  29749. var toChange = [];
  29750. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29751. betterShapeHoles[ sIdx ] = [];
  29752. }
  29753. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29754. var sho = newShapeHoles[ sIdx ];
  29755. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29756. var ho = sho[ hIdx ];
  29757. var hole_unassigned = true;
  29758. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29759. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29760. if ( sIdx !== s2Idx ) { toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); }
  29761. if ( hole_unassigned ) {
  29762. hole_unassigned = false;
  29763. betterShapeHoles[ s2Idx ].push( ho );
  29764. } else {
  29765. ambiguous = true;
  29766. }
  29767. }
  29768. }
  29769. if ( hole_unassigned ) {
  29770. betterShapeHoles[ sIdx ].push( ho );
  29771. }
  29772. }
  29773. }
  29774. // console.log("ambiguous: ", ambiguous);
  29775. if ( toChange.length > 0 ) {
  29776. // console.log("to change: ", toChange);
  29777. if ( ! ambiguous ) { newShapeHoles = betterShapeHoles; }
  29778. }
  29779. }
  29780. var tmpHoles;
  29781. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  29782. tmpShape = newShapes[ i ].s;
  29783. shapes.push( tmpShape );
  29784. tmpHoles = newShapeHoles[ i ];
  29785. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29786. tmpShape.holes.push( tmpHoles[ j ].h );
  29787. }
  29788. }
  29789. //console.log("shape", shapes);
  29790. return shapes;
  29791. }
  29792. } );
  29793. /**
  29794. * @author zz85 / http://www.lab4games.net/zz85/blog
  29795. * @author mrdoob / http://mrdoob.com/
  29796. */
  29797. function Font( data ) {
  29798. this.type = 'Font';
  29799. this.data = data;
  29800. }
  29801. Object.assign( Font.prototype, {
  29802. isFont: true,
  29803. generateShapes: function ( text, size ) {
  29804. if ( size === undefined ) { size = 100; }
  29805. var shapes = [];
  29806. var paths = createPaths( text, size, this.data );
  29807. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  29808. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  29809. }
  29810. return shapes;
  29811. }
  29812. } );
  29813. function createPaths( text, size, data ) {
  29814. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
  29815. var scale = size / data.resolution;
  29816. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  29817. var paths = [];
  29818. var offsetX = 0, offsetY = 0;
  29819. for ( var i = 0; i < chars.length; i ++ ) {
  29820. var char = chars[ i ];
  29821. if ( char === '\n' ) {
  29822. offsetX = 0;
  29823. offsetY -= line_height;
  29824. } else {
  29825. var ret = createPath( char, scale, offsetX, offsetY, data );
  29826. offsetX += ret.offsetX;
  29827. paths.push( ret.path );
  29828. }
  29829. }
  29830. return paths;
  29831. }
  29832. function createPath( char, scale, offsetX, offsetY, data ) {
  29833. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  29834. if ( ! glyph ) {
  29835. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  29836. return;
  29837. }
  29838. var path = new ShapePath();
  29839. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  29840. if ( glyph.o ) {
  29841. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  29842. for ( var i = 0, l = outline.length; i < l; ) {
  29843. var action = outline[ i ++ ];
  29844. switch ( action ) {
  29845. case 'm': // moveTo
  29846. x = outline[ i ++ ] * scale + offsetX;
  29847. y = outline[ i ++ ] * scale + offsetY;
  29848. path.moveTo( x, y );
  29849. break;
  29850. case 'l': // lineTo
  29851. x = outline[ i ++ ] * scale + offsetX;
  29852. y = outline[ i ++ ] * scale + offsetY;
  29853. path.lineTo( x, y );
  29854. break;
  29855. case 'q': // quadraticCurveTo
  29856. cpx = outline[ i ++ ] * scale + offsetX;
  29857. cpy = outline[ i ++ ] * scale + offsetY;
  29858. cpx1 = outline[ i ++ ] * scale + offsetX;
  29859. cpy1 = outline[ i ++ ] * scale + offsetY;
  29860. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  29861. break;
  29862. case 'b': // bezierCurveTo
  29863. cpx = outline[ i ++ ] * scale + offsetX;
  29864. cpy = outline[ i ++ ] * scale + offsetY;
  29865. cpx1 = outline[ i ++ ] * scale + offsetX;
  29866. cpy1 = outline[ i ++ ] * scale + offsetY;
  29867. cpx2 = outline[ i ++ ] * scale + offsetX;
  29868. cpy2 = outline[ i ++ ] * scale + offsetY;
  29869. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  29870. break;
  29871. }
  29872. }
  29873. }
  29874. return { offsetX: glyph.ha * scale, path: path };
  29875. }
  29876. /**
  29877. * @author mrdoob / http://mrdoob.com/
  29878. */
  29879. function FontLoader( manager ) {
  29880. Loader.call( this, manager );
  29881. }
  29882. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29883. constructor: FontLoader,
  29884. load: function ( url, onLoad, onProgress, onError ) {
  29885. var scope = this;
  29886. var loader = new FileLoader( this.manager );
  29887. loader.setPath( this.path );
  29888. loader.load( url, function ( text ) {
  29889. var json;
  29890. try {
  29891. json = JSON.parse( text );
  29892. } catch ( e ) {
  29893. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  29894. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  29895. }
  29896. var font = scope.parse( json );
  29897. if ( onLoad ) { onLoad( font ); }
  29898. }, onProgress, onError );
  29899. },
  29900. parse: function ( json ) {
  29901. return new Font( json );
  29902. }
  29903. } );
  29904. /**
  29905. * @author mrdoob / http://mrdoob.com/
  29906. */
  29907. var _context;
  29908. var AudioContext = {
  29909. getContext: function () {
  29910. if ( _context === undefined ) {
  29911. _context = new ( window.AudioContext || window.webkitAudioContext )();
  29912. }
  29913. return _context;
  29914. },
  29915. setContext: function ( value ) {
  29916. _context = value;
  29917. }
  29918. };
  29919. /**
  29920. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  29921. */
  29922. function AudioLoader( manager ) {
  29923. Loader.call( this, manager );
  29924. }
  29925. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29926. constructor: AudioLoader,
  29927. load: function ( url, onLoad, onProgress, onError ) {
  29928. var loader = new FileLoader( this.manager );
  29929. loader.setResponseType( 'arraybuffer' );
  29930. loader.setPath( this.path );
  29931. loader.load( url, function ( buffer ) {
  29932. // Create a copy of the buffer. The `decodeAudioData` method
  29933. // detaches the buffer when complete, preventing reuse.
  29934. var bufferCopy = buffer.slice( 0 );
  29935. var context = AudioContext.getContext();
  29936. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  29937. onLoad( audioBuffer );
  29938. } );
  29939. }, onProgress, onError );
  29940. }
  29941. } );
  29942. /**
  29943. * @author bhouston / http://clara.io
  29944. * @author WestLangley / http://github.com/WestLangley
  29945. *
  29946. * Primary reference:
  29947. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29948. *
  29949. * Secondary reference:
  29950. * https://www.ppsloan.org/publications/StupidSH36.pdf
  29951. */
  29952. // 3-band SH defined by 9 coefficients
  29953. function SphericalHarmonics3() {
  29954. this.coefficients = [];
  29955. for ( var i = 0; i < 9; i ++ ) {
  29956. this.coefficients.push( new Vector3() );
  29957. }
  29958. }
  29959. Object.assign( SphericalHarmonics3.prototype, {
  29960. isSphericalHarmonics3: true,
  29961. set: function ( coefficients ) {
  29962. for ( var i = 0; i < 9; i ++ ) {
  29963. this.coefficients[ i ].copy( coefficients[ i ] );
  29964. }
  29965. return this;
  29966. },
  29967. zero: function () {
  29968. for ( var i = 0; i < 9; i ++ ) {
  29969. this.coefficients[ i ].set( 0, 0, 0 );
  29970. }
  29971. return this;
  29972. },
  29973. // get the radiance in the direction of the normal
  29974. // target is a Vector3
  29975. getAt: function ( normal, target ) {
  29976. // normal is assumed to be unit length
  29977. var x = normal.x, y = normal.y, z = normal.z;
  29978. var coeff = this.coefficients;
  29979. // band 0
  29980. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  29981. // band 1
  29982. target.addScale( coeff[ 1 ], 0.488603 * y );
  29983. target.addScale( coeff[ 2 ], 0.488603 * z );
  29984. target.addScale( coeff[ 3 ], 0.488603 * x );
  29985. // band 2
  29986. target.addScale( coeff[ 4 ], 1.092548 * ( x * y ) );
  29987. target.addScale( coeff[ 5 ], 1.092548 * ( y * z ) );
  29988. target.addScale( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  29989. target.addScale( coeff[ 7 ], 1.092548 * ( x * z ) );
  29990. target.addScale( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  29991. return target;
  29992. },
  29993. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  29994. // target is a Vector3
  29995. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29996. getIrradianceAt: function ( normal, target ) {
  29997. // normal is assumed to be unit length
  29998. var x = normal.x, y = normal.y, z = normal.z;
  29999. var coeff = this.coefficients;
  30000. // band 0
  30001. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  30002. // band 1
  30003. target.addScale( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  30004. target.addScale( coeff[ 2 ], 2.0 * 0.511664 * z );
  30005. target.addScale( coeff[ 3 ], 2.0 * 0.511664 * x );
  30006. // band 2
  30007. target.addScale( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  30008. target.addScale( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  30009. target.addScale( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  30010. target.addScale( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  30011. target.addScale( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  30012. return target;
  30013. },
  30014. add: function ( sh ) {
  30015. for ( var i = 0; i < 9; i ++ ) {
  30016. this.coefficients[ i ].add( sh.coefficients[ i ] );
  30017. }
  30018. return this;
  30019. },
  30020. scale: function ( s ) {
  30021. for ( var i = 0; i < 9; i ++ ) {
  30022. this.coefficients[ i ].multiplyScalar( s );
  30023. }
  30024. return this;
  30025. },
  30026. lerp: function ( sh, alpha ) {
  30027. for ( var i = 0; i < 9; i ++ ) {
  30028. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  30029. }
  30030. return this;
  30031. },
  30032. equals: function ( sh ) {
  30033. for ( var i = 0; i < 9; i ++ ) {
  30034. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  30035. return false;
  30036. }
  30037. }
  30038. return true;
  30039. },
  30040. copy: function ( sh ) {
  30041. return this.set( sh.coefficients );
  30042. },
  30043. clone: function () {
  30044. return new this.constructor().copy( this );
  30045. },
  30046. fromArray: function ( array, offset ) {
  30047. if ( offset === undefined ) { offset = 0; }
  30048. var coefficients = this.coefficients;
  30049. for ( var i = 0; i < 9; i ++ ) {
  30050. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  30051. }
  30052. return this;
  30053. },
  30054. toArray: function ( array, offset ) {
  30055. if ( array === undefined ) { array = []; }
  30056. if ( offset === undefined ) { offset = 0; }
  30057. var coefficients = this.coefficients;
  30058. for ( var i = 0; i < 9; i ++ ) {
  30059. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  30060. }
  30061. return array;
  30062. }
  30063. } );
  30064. Object.assign( SphericalHarmonics3, {
  30065. // evaluate the basis functions
  30066. // shBasis is an Array[ 9 ]
  30067. getBasisAt: function ( normal, shBasis ) {
  30068. // normal is assumed to be unit length
  30069. var x = normal.x, y = normal.y, z = normal.z;
  30070. // band 0
  30071. shBasis[ 0 ] = 0.282095;
  30072. // band 1
  30073. shBasis[ 1 ] = 0.488603 * y;
  30074. shBasis[ 2 ] = 0.488603 * z;
  30075. shBasis[ 3 ] = 0.488603 * x;
  30076. // band 2
  30077. shBasis[ 4 ] = 1.092548 * x * y;
  30078. shBasis[ 5 ] = 1.092548 * y * z;
  30079. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  30080. shBasis[ 7 ] = 1.092548 * x * z;
  30081. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  30082. }
  30083. } );
  30084. /**
  30085. * @author WestLangley / http://github.com/WestLangley
  30086. *
  30087. * A LightProbe is a source of indirect-diffuse light
  30088. */
  30089. function LightProbe( sh, intensity ) {
  30090. Light.call( this, undefined, intensity );
  30091. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  30092. }
  30093. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  30094. constructor: LightProbe,
  30095. isLightProbe: true,
  30096. copy: function ( source ) {
  30097. Light.prototype.copy.call( this, source );
  30098. this.sh.copy( source.sh );
  30099. this.intensity = source.intensity;
  30100. return this;
  30101. },
  30102. toJSON: function ( meta ) {
  30103. var data = Light.prototype.toJSON.call( this, meta );
  30104. // data.sh = this.sh.toArray(); // todo
  30105. return data;
  30106. }
  30107. } );
  30108. /**
  30109. * @author WestLangley / http://github.com/WestLangley
  30110. */
  30111. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  30112. LightProbe.call( this, undefined, intensity );
  30113. var color1 = new Color().set( skyColor );
  30114. var color2 = new Color().set( groundColor );
  30115. var sky = new Vector3( color1.r, color1.g, color1.b );
  30116. var ground = new Vector3( color2.r, color2.g, color2.b );
  30117. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30118. var c0 = Math.sqrt( Math.PI );
  30119. var c1 = c0 * Math.sqrt( 0.75 );
  30120. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  30121. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  30122. }
  30123. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30124. constructor: HemisphereLightProbe,
  30125. isHemisphereLightProbe: true,
  30126. copy: function ( source ) { // modifying colors not currently supported
  30127. LightProbe.prototype.copy.call( this, source );
  30128. return this;
  30129. },
  30130. toJSON: function ( meta ) {
  30131. var data = LightProbe.prototype.toJSON.call( this, meta );
  30132. // data.sh = this.sh.toArray(); // todo
  30133. return data;
  30134. }
  30135. } );
  30136. /**
  30137. * @author WestLangley / http://github.com/WestLangley
  30138. */
  30139. function AmbientLightProbe( color, intensity ) {
  30140. LightProbe.call( this, undefined, intensity );
  30141. var color1 = new Color().set( color );
  30142. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30143. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  30144. }
  30145. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30146. constructor: AmbientLightProbe,
  30147. isAmbientLightProbe: true,
  30148. copy: function ( source ) { // modifying color not currently supported
  30149. LightProbe.prototype.copy.call( this, source );
  30150. return this;
  30151. },
  30152. toJSON: function ( meta ) {
  30153. var data = LightProbe.prototype.toJSON.call( this, meta );
  30154. // data.sh = this.sh.toArray(); // todo
  30155. return data;
  30156. }
  30157. } );
  30158. var _eyeRight = new Matrix4();
  30159. var _eyeLeft = new Matrix4();
  30160. /**
  30161. * @author mrdoob / http://mrdoob.com/
  30162. */
  30163. function StereoCamera() {
  30164. this.type = 'StereoCamera';
  30165. this.aspect = 1;
  30166. this.eyeSep = 0.064;
  30167. this.cameraL = new PerspectiveCamera();
  30168. this.cameraL.layers.enable( 1 );
  30169. this.cameraL.matrixAutoUpdate = false;
  30170. this.cameraR = new PerspectiveCamera();
  30171. this.cameraR.layers.enable( 2 );
  30172. this.cameraR.matrixAutoUpdate = false;
  30173. this._cache = {
  30174. focus: null,
  30175. fov: null,
  30176. aspect: null,
  30177. near: null,
  30178. far: null,
  30179. zoom: null,
  30180. eyeSep: null
  30181. };
  30182. }
  30183. Object.assign( StereoCamera.prototype, {
  30184. update: function ( camera ) {
  30185. var cache = this._cache;
  30186. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  30187. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  30188. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  30189. if ( needsUpdate ) {
  30190. cache.focus = camera.focus;
  30191. cache.fov = camera.fov;
  30192. cache.aspect = camera.aspect * this.aspect;
  30193. cache.near = camera.near;
  30194. cache.far = camera.far;
  30195. cache.zoom = camera.zoom;
  30196. cache.eyeSep = this.eyeSep;
  30197. // Off-axis stereoscopic effect based on
  30198. // http://paulbourke.net/stereographics/stereorender/
  30199. var projectionMatrix = camera.projectionMatrix.clone();
  30200. var eyeSepHalf = cache.eyeSep / 2;
  30201. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  30202. var ymax = ( cache.near * Math.tan( _Math.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  30203. var xmin, xmax;
  30204. // translate xOffset
  30205. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  30206. _eyeRight.elements[ 12 ] = eyeSepHalf;
  30207. // for left eye
  30208. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  30209. xmax = ymax * cache.aspect + eyeSepOnProjection;
  30210. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  30211. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  30212. this.cameraL.projectionMatrix.copy( projectionMatrix );
  30213. // for right eye
  30214. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  30215. xmax = ymax * cache.aspect - eyeSepOnProjection;
  30216. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  30217. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  30218. this.cameraR.projectionMatrix.copy( projectionMatrix );
  30219. }
  30220. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  30221. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  30222. }
  30223. } );
  30224. /**
  30225. * @author alteredq / http://alteredqualia.com/
  30226. */
  30227. function Clock( autoStart ) {
  30228. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  30229. this.startTime = 0;
  30230. this.oldTime = 0;
  30231. this.elapsedTime = 0;
  30232. this.running = false;
  30233. }
  30234. Object.assign( Clock.prototype, {
  30235. start: function () {
  30236. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  30237. this.oldTime = this.startTime;
  30238. this.elapsedTime = 0;
  30239. this.running = true;
  30240. },
  30241. stop: function () {
  30242. this.getElapsedTime();
  30243. this.running = false;
  30244. this.autoStart = false;
  30245. },
  30246. getElapsedTime: function () {
  30247. this.getDelta();
  30248. return this.elapsedTime;
  30249. },
  30250. getDelta: function () {
  30251. var diff = 0;
  30252. if ( this.autoStart && ! this.running ) {
  30253. this.start();
  30254. return 0;
  30255. }
  30256. if ( this.running ) {
  30257. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  30258. diff = ( newTime - this.oldTime ) / 1000;
  30259. this.oldTime = newTime;
  30260. this.elapsedTime += diff;
  30261. }
  30262. return diff;
  30263. }
  30264. } );
  30265. /**
  30266. * @author mrdoob / http://mrdoob.com/
  30267. */
  30268. var _position$2 = new Vector3();
  30269. var _quaternion$3 = new Quaternion();
  30270. var _scale$1 = new Vector3();
  30271. var _orientation = new Vector3();
  30272. function AudioListener() {
  30273. Object3D.call( this );
  30274. this.type = 'AudioListener';
  30275. this.context = AudioContext.getContext();
  30276. this.gain = this.context.createGain();
  30277. this.gain.connect( this.context.destination );
  30278. this.filter = null;
  30279. this.timeDelta = 0;
  30280. // private
  30281. this._clock = new Clock();
  30282. }
  30283. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  30284. constructor: AudioListener,
  30285. getInput: function () {
  30286. return this.gain;
  30287. },
  30288. removeFilter: function ( ) {
  30289. if ( this.filter !== null ) {
  30290. this.gain.disconnect( this.filter );
  30291. this.filter.disconnect( this.context.destination );
  30292. this.gain.connect( this.context.destination );
  30293. this.filter = null;
  30294. }
  30295. return this;
  30296. },
  30297. getFilter: function () {
  30298. return this.filter;
  30299. },
  30300. setFilter: function ( value ) {
  30301. if ( this.filter !== null ) {
  30302. this.gain.disconnect( this.filter );
  30303. this.filter.disconnect( this.context.destination );
  30304. } else {
  30305. this.gain.disconnect( this.context.destination );
  30306. }
  30307. this.filter = value;
  30308. this.gain.connect( this.filter );
  30309. this.filter.connect( this.context.destination );
  30310. return this;
  30311. },
  30312. getMasterVolume: function () {
  30313. return this.gain.gain.value;
  30314. },
  30315. setMasterVolume: function ( value ) {
  30316. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  30317. return this;
  30318. },
  30319. updateMatrixWorld: function ( force ) {
  30320. Object3D.prototype.updateMatrixWorld.call( this, force );
  30321. var listener = this.context.listener;
  30322. var up = this.up;
  30323. this.timeDelta = this._clock.getDelta();
  30324. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  30325. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  30326. if ( listener.positionX ) {
  30327. // code path for Chrome (see #14393)
  30328. var endTime = this.context.currentTime + this.timeDelta;
  30329. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  30330. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  30331. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  30332. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  30333. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  30334. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  30335. listener.upX.linearRampToValueAtTime( up.x, endTime );
  30336. listener.upY.linearRampToValueAtTime( up.y, endTime );
  30337. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  30338. } else {
  30339. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  30340. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  30341. }
  30342. }
  30343. } );
  30344. /**
  30345. * @author mrdoob / http://mrdoob.com/
  30346. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  30347. */
  30348. function Audio( listener ) {
  30349. Object3D.call( this );
  30350. this.type = 'Audio';
  30351. this.listener = listener;
  30352. this.context = listener.context;
  30353. this.gain = this.context.createGain();
  30354. this.gain.connect( listener.getInput() );
  30355. this.autoplay = false;
  30356. this.buffer = null;
  30357. this.detune = 0;
  30358. this.loop = false;
  30359. this.startTime = 0;
  30360. this.offset = 0;
  30361. this.duration = undefined;
  30362. this.playbackRate = 1;
  30363. this.isPlaying = false;
  30364. this.hasPlaybackControl = true;
  30365. this.sourceType = 'empty';
  30366. this.filters = [];
  30367. }
  30368. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  30369. constructor: Audio,
  30370. getOutput: function () {
  30371. return this.gain;
  30372. },
  30373. setNodeSource: function ( audioNode ) {
  30374. this.hasPlaybackControl = false;
  30375. this.sourceType = 'audioNode';
  30376. this.source = audioNode;
  30377. this.connect();
  30378. return this;
  30379. },
  30380. setMediaElementSource: function ( mediaElement ) {
  30381. this.hasPlaybackControl = false;
  30382. this.sourceType = 'mediaNode';
  30383. this.source = this.context.createMediaElementSource( mediaElement );
  30384. this.connect();
  30385. return this;
  30386. },
  30387. setMediaStreamSource: function ( mediaStream ) {
  30388. this.hasPlaybackControl = false;
  30389. this.sourceType = 'mediaStreamNode';
  30390. this.source = this.context.createMediaStreamSource( mediaStream );
  30391. this.connect();
  30392. return this;
  30393. },
  30394. setBuffer: function ( audioBuffer ) {
  30395. this.buffer = audioBuffer;
  30396. this.sourceType = 'buffer';
  30397. if ( this.autoplay ) { this.play(); }
  30398. return this;
  30399. },
  30400. play: function () {
  30401. if ( this.isPlaying === true ) {
  30402. console.warn( 'THREE.Audio: Audio is already playing.' );
  30403. return;
  30404. }
  30405. if ( this.hasPlaybackControl === false ) {
  30406. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30407. return;
  30408. }
  30409. var source = this.context.createBufferSource();
  30410. source.buffer = this.buffer;
  30411. source.loop = this.loop;
  30412. source.onended = this.onEnded.bind( this );
  30413. this.startTime = this.context.currentTime;
  30414. source.start( this.startTime, this.offset, this.duration );
  30415. this.isPlaying = true;
  30416. this.source = source;
  30417. this.setDetune( this.detune );
  30418. this.setPlaybackRate( this.playbackRate );
  30419. return this.connect();
  30420. },
  30421. pause: function () {
  30422. if ( this.hasPlaybackControl === false ) {
  30423. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30424. return;
  30425. }
  30426. if ( this.isPlaying === true ) {
  30427. this.source.stop();
  30428. this.source.onended = null;
  30429. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  30430. this.isPlaying = false;
  30431. }
  30432. return this;
  30433. },
  30434. stop: function () {
  30435. if ( this.hasPlaybackControl === false ) {
  30436. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30437. return;
  30438. }
  30439. this.source.stop();
  30440. this.source.onended = null;
  30441. this.offset = 0;
  30442. this.isPlaying = false;
  30443. return this;
  30444. },
  30445. connect: function () {
  30446. if ( this.filters.length > 0 ) {
  30447. this.source.connect( this.filters[ 0 ] );
  30448. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  30449. this.filters[ i - 1 ].connect( this.filters[ i ] );
  30450. }
  30451. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  30452. } else {
  30453. this.source.connect( this.getOutput() );
  30454. }
  30455. return this;
  30456. },
  30457. disconnect: function () {
  30458. if ( this.filters.length > 0 ) {
  30459. this.source.disconnect( this.filters[ 0 ] );
  30460. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  30461. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  30462. }
  30463. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  30464. } else {
  30465. this.source.disconnect( this.getOutput() );
  30466. }
  30467. return this;
  30468. },
  30469. getFilters: function () {
  30470. return this.filters;
  30471. },
  30472. setFilters: function ( value ) {
  30473. if ( ! value ) { value = []; }
  30474. if ( this.isPlaying === true ) {
  30475. this.disconnect();
  30476. this.filters = value;
  30477. this.connect();
  30478. } else {
  30479. this.filters = value;
  30480. }
  30481. return this;
  30482. },
  30483. setDetune: function ( value ) {
  30484. this.detune = value;
  30485. if ( this.source.detune === undefined ) { return; } // only set detune when available
  30486. if ( this.isPlaying === true ) {
  30487. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  30488. }
  30489. return this;
  30490. },
  30491. getDetune: function () {
  30492. return this.detune;
  30493. },
  30494. getFilter: function () {
  30495. return this.getFilters()[ 0 ];
  30496. },
  30497. setFilter: function ( filter ) {
  30498. return this.setFilters( filter ? [ filter ] : [] );
  30499. },
  30500. setPlaybackRate: function ( value ) {
  30501. if ( this.hasPlaybackControl === false ) {
  30502. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30503. return;
  30504. }
  30505. this.playbackRate = value;
  30506. if ( this.isPlaying === true ) {
  30507. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  30508. }
  30509. return this;
  30510. },
  30511. getPlaybackRate: function () {
  30512. return this.playbackRate;
  30513. },
  30514. onEnded: function () {
  30515. this.isPlaying = false;
  30516. },
  30517. getLoop: function () {
  30518. if ( this.hasPlaybackControl === false ) {
  30519. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30520. return false;
  30521. }
  30522. return this.loop;
  30523. },
  30524. setLoop: function ( value ) {
  30525. if ( this.hasPlaybackControl === false ) {
  30526. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  30527. return;
  30528. }
  30529. this.loop = value;
  30530. if ( this.isPlaying === true ) {
  30531. this.source.loop = this.loop;
  30532. }
  30533. return this;
  30534. },
  30535. getVolume: function () {
  30536. return this.gain.gain.value;
  30537. },
  30538. setVolume: function ( value ) {
  30539. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  30540. return this;
  30541. }
  30542. } );
  30543. /**
  30544. * @author mrdoob / http://mrdoob.com/
  30545. */
  30546. var _position$3 = new Vector3();
  30547. var _quaternion$4 = new Quaternion();
  30548. var _scale$2 = new Vector3();
  30549. var _orientation$1 = new Vector3();
  30550. function PositionalAudio( listener ) {
  30551. Audio.call( this, listener );
  30552. this.panner = this.context.createPanner();
  30553. this.panner.panningModel = 'HRTF';
  30554. this.panner.connect( this.gain );
  30555. }
  30556. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  30557. constructor: PositionalAudio,
  30558. getOutput: function () {
  30559. return this.panner;
  30560. },
  30561. getRefDistance: function () {
  30562. return this.panner.refDistance;
  30563. },
  30564. setRefDistance: function ( value ) {
  30565. this.panner.refDistance = value;
  30566. return this;
  30567. },
  30568. getRolloffFactor: function () {
  30569. return this.panner.rolloffFactor;
  30570. },
  30571. setRolloffFactor: function ( value ) {
  30572. this.panner.rolloffFactor = value;
  30573. return this;
  30574. },
  30575. getDistanceModel: function () {
  30576. return this.panner.distanceModel;
  30577. },
  30578. setDistanceModel: function ( value ) {
  30579. this.panner.distanceModel = value;
  30580. return this;
  30581. },
  30582. getMaxDistance: function () {
  30583. return this.panner.maxDistance;
  30584. },
  30585. setMaxDistance: function ( value ) {
  30586. this.panner.maxDistance = value;
  30587. return this;
  30588. },
  30589. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  30590. this.panner.coneInnerAngle = coneInnerAngle;
  30591. this.panner.coneOuterAngle = coneOuterAngle;
  30592. this.panner.coneOuterGain = coneOuterGain;
  30593. return this;
  30594. },
  30595. updateMatrixWorld: function ( force ) {
  30596. Object3D.prototype.updateMatrixWorld.call( this, force );
  30597. if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; }
  30598. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  30599. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  30600. var panner = this.panner;
  30601. if ( panner.positionX ) {
  30602. // code path for Chrome and Firefox (see #14393)
  30603. var endTime = this.context.currentTime + this.listener.timeDelta;
  30604. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  30605. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  30606. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  30607. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  30608. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  30609. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  30610. } else {
  30611. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  30612. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  30613. }
  30614. }
  30615. } );
  30616. /**
  30617. * @author mrdoob / http://mrdoob.com/
  30618. */
  30619. function AudioAnalyser( audio, fftSize ) {
  30620. this.analyser = audio.context.createAnalyser();
  30621. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  30622. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  30623. audio.getOutput().connect( this.analyser );
  30624. }
  30625. Object.assign( AudioAnalyser.prototype, {
  30626. getFrequencyData: function () {
  30627. this.analyser.getByteFrequencyData( this.data );
  30628. return this.data;
  30629. },
  30630. getAverageFrequency: function () {
  30631. var value = 0, data = this.getFrequencyData();
  30632. for ( var i = 0; i < data.length; i ++ ) {
  30633. value += data[ i ];
  30634. }
  30635. return value / data.length;
  30636. }
  30637. } );
  30638. /**
  30639. *
  30640. * Buffered scene graph property that allows weighted accumulation.
  30641. *
  30642. *
  30643. * @author Ben Houston / http://clara.io/
  30644. * @author David Sarno / http://lighthaus.us/
  30645. * @author tschw
  30646. */
  30647. function PropertyMixer( binding, typeName, valueSize ) {
  30648. this.binding = binding;
  30649. this.valueSize = valueSize;
  30650. var bufferType = Float64Array,
  30651. mixFunction;
  30652. switch ( typeName ) {
  30653. case 'quaternion':
  30654. mixFunction = this._slerp;
  30655. break;
  30656. case 'string':
  30657. case 'bool':
  30658. bufferType = Array;
  30659. mixFunction = this._select;
  30660. break;
  30661. default:
  30662. mixFunction = this._lerp;
  30663. }
  30664. this.buffer = new bufferType( valueSize * 4 );
  30665. // layout: [ incoming | accu0 | accu1 | orig ]
  30666. //
  30667. // interpolators can use .buffer as their .result
  30668. // the data then goes to 'incoming'
  30669. //
  30670. // 'accu0' and 'accu1' are used frame-interleaved for
  30671. // the cumulative result and are compared to detect
  30672. // changes
  30673. //
  30674. // 'orig' stores the original state of the property
  30675. this._mixBufferRegion = mixFunction;
  30676. this.cumulativeWeight = 0;
  30677. this.useCount = 0;
  30678. this.referenceCount = 0;
  30679. }
  30680. Object.assign( PropertyMixer.prototype, {
  30681. // accumulate data in the 'incoming' region into 'accu<i>'
  30682. accumulate: function ( accuIndex, weight ) {
  30683. // note: happily accumulating nothing when weight = 0, the caller knows
  30684. // the weight and shouldn't have made the call in the first place
  30685. var buffer = this.buffer,
  30686. stride = this.valueSize,
  30687. offset = accuIndex * stride + stride,
  30688. currentWeight = this.cumulativeWeight;
  30689. if ( currentWeight === 0 ) {
  30690. // accuN := incoming * weight
  30691. for ( var i = 0; i !== stride; ++ i ) {
  30692. buffer[ offset + i ] = buffer[ i ];
  30693. }
  30694. currentWeight = weight;
  30695. } else {
  30696. // accuN := accuN + incoming * weight
  30697. currentWeight += weight;
  30698. var mix = weight / currentWeight;
  30699. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  30700. }
  30701. this.cumulativeWeight = currentWeight;
  30702. },
  30703. // apply the state of 'accu<i>' to the binding when accus differ
  30704. apply: function ( accuIndex ) {
  30705. var stride = this.valueSize,
  30706. buffer = this.buffer,
  30707. offset = accuIndex * stride + stride,
  30708. weight = this.cumulativeWeight,
  30709. binding = this.binding;
  30710. this.cumulativeWeight = 0;
  30711. if ( weight < 1 ) {
  30712. // accuN := accuN + original * ( 1 - cumulativeWeight )
  30713. var originalValueOffset = stride * 3;
  30714. this._mixBufferRegion(
  30715. buffer, offset, originalValueOffset, 1 - weight, stride );
  30716. }
  30717. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  30718. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  30719. // value has changed -> update scene graph
  30720. binding.setValue( buffer, offset );
  30721. break;
  30722. }
  30723. }
  30724. },
  30725. // remember the state of the bound property and copy it to both accus
  30726. saveOriginalState: function () {
  30727. var binding = this.binding;
  30728. var buffer = this.buffer,
  30729. stride = this.valueSize,
  30730. originalValueOffset = stride * 3;
  30731. binding.getValue( buffer, originalValueOffset );
  30732. // accu[0..1] := orig -- initially detect changes against the original
  30733. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  30734. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  30735. }
  30736. this.cumulativeWeight = 0;
  30737. },
  30738. // apply the state previously taken via 'saveOriginalState' to the binding
  30739. restoreOriginalState: function () {
  30740. var originalValueOffset = this.valueSize * 3;
  30741. this.binding.setValue( this.buffer, originalValueOffset );
  30742. },
  30743. // mix functions
  30744. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  30745. if ( t >= 0.5 ) {
  30746. for ( var i = 0; i !== stride; ++ i ) {
  30747. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  30748. }
  30749. }
  30750. },
  30751. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  30752. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  30753. },
  30754. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  30755. var s = 1 - t;
  30756. for ( var i = 0; i !== stride; ++ i ) {
  30757. var j = dstOffset + i;
  30758. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  30759. }
  30760. }
  30761. } );
  30762. /**
  30763. *
  30764. * A reference to a real property in the scene graph.
  30765. *
  30766. *
  30767. * @author Ben Houston / http://clara.io/
  30768. * @author David Sarno / http://lighthaus.us/
  30769. * @author tschw
  30770. */
  30771. // Characters [].:/ are reserved for track binding syntax.
  30772. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  30773. var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  30774. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  30775. // only latin characters, and the unicode \p{L} is not yet supported. So
  30776. // instead, we exclude reserved characters and match everything else.
  30777. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  30778. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  30779. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  30780. // be matched to parse the rest of the track name.
  30781. var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  30782. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  30783. var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  30784. // Object on target node, and accessor. May not contain reserved
  30785. // characters. Accessor may contain any character except closing bracket.
  30786. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  30787. // Property and accessor. May not contain reserved characters. Accessor may
  30788. // contain any non-bracket characters.
  30789. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  30790. var _trackRe = new RegExp( ''
  30791. + '^'
  30792. + _directoryRe
  30793. + _nodeRe
  30794. + _objectRe
  30795. + _propertyRe
  30796. + '$'
  30797. );
  30798. var _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  30799. function Composite( targetGroup, path, optionalParsedPath ) {
  30800. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  30801. this._targetGroup = targetGroup;
  30802. this._bindings = targetGroup.subscribe_( path, parsedPath );
  30803. }
  30804. Object.assign( Composite.prototype, {
  30805. getValue: function ( array, offset ) {
  30806. this.bind(); // bind all binding
  30807. var firstValidIndex = this._targetGroup.nCachedObjects_,
  30808. binding = this._bindings[ firstValidIndex ];
  30809. // and only call .getValue on the first
  30810. if ( binding !== undefined ) { binding.getValue( array, offset ); }
  30811. },
  30812. setValue: function ( array, offset ) {
  30813. var bindings = this._bindings;
  30814. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  30815. bindings[ i ].setValue( array, offset );
  30816. }
  30817. },
  30818. bind: function () {
  30819. var bindings = this._bindings;
  30820. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  30821. bindings[ i ].bind();
  30822. }
  30823. },
  30824. unbind: function () {
  30825. var bindings = this._bindings;
  30826. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  30827. bindings[ i ].unbind();
  30828. }
  30829. }
  30830. } );
  30831. function PropertyBinding( rootNode, path, parsedPath ) {
  30832. this.path = path;
  30833. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  30834. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  30835. this.rootNode = rootNode;
  30836. }
  30837. Object.assign( PropertyBinding, {
  30838. Composite: Composite,
  30839. create: function ( root, path, parsedPath ) {
  30840. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  30841. return new PropertyBinding( root, path, parsedPath );
  30842. } else {
  30843. return new PropertyBinding.Composite( root, path, parsedPath );
  30844. }
  30845. },
  30846. /**
  30847. * Replaces spaces with underscores and removes unsupported characters from
  30848. * node names, to ensure compatibility with parseTrackName().
  30849. *
  30850. * @param {string} name Node name to be sanitized.
  30851. * @return {string}
  30852. */
  30853. sanitizeNodeName: function ( name ) {
  30854. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  30855. },
  30856. parseTrackName: function ( trackName ) {
  30857. var matches = _trackRe.exec( trackName );
  30858. if ( ! matches ) {
  30859. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  30860. }
  30861. var results = {
  30862. // directoryName: matches[ 1 ], // (tschw) currently unused
  30863. nodeName: matches[ 2 ],
  30864. objectName: matches[ 3 ],
  30865. objectIndex: matches[ 4 ],
  30866. propertyName: matches[ 5 ], // required
  30867. propertyIndex: matches[ 6 ]
  30868. };
  30869. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  30870. if ( lastDot !== undefined && lastDot !== - 1 ) {
  30871. var objectName = results.nodeName.substring( lastDot + 1 );
  30872. // Object names must be checked against a whitelist. Otherwise, there
  30873. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  30874. // 'bar' could be the objectName, or part of a nodeName (which can
  30875. // include '.' characters).
  30876. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  30877. results.nodeName = results.nodeName.substring( 0, lastDot );
  30878. results.objectName = objectName;
  30879. }
  30880. }
  30881. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  30882. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  30883. }
  30884. return results;
  30885. },
  30886. findNode: function ( root, nodeName ) {
  30887. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  30888. return root;
  30889. }
  30890. // search into skeleton bones.
  30891. if ( root.skeleton ) {
  30892. var bone = root.skeleton.getBoneByName( nodeName );
  30893. if ( bone !== undefined ) {
  30894. return bone;
  30895. }
  30896. }
  30897. // search into node subtree.
  30898. if ( root.children ) {
  30899. var searchNodeSubtree = function ( children ) {
  30900. for ( var i = 0; i < children.length; i ++ ) {
  30901. var childNode = children[ i ];
  30902. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  30903. return childNode;
  30904. }
  30905. var result = searchNodeSubtree( childNode.children );
  30906. if ( result ) { return result; }
  30907. }
  30908. return null;
  30909. };
  30910. var subTreeNode = searchNodeSubtree( root.children );
  30911. if ( subTreeNode ) {
  30912. return subTreeNode;
  30913. }
  30914. }
  30915. return null;
  30916. }
  30917. } );
  30918. Object.assign( PropertyBinding.prototype, { // prototype, continued
  30919. // these are used to "bind" a nonexistent property
  30920. _getValue_unavailable: function () {},
  30921. _setValue_unavailable: function () {},
  30922. BindingType: {
  30923. Direct: 0,
  30924. EntireArray: 1,
  30925. ArrayElement: 2,
  30926. HasFromToArray: 3
  30927. },
  30928. Versioning: {
  30929. None: 0,
  30930. NeedsUpdate: 1,
  30931. MatrixWorldNeedsUpdate: 2
  30932. },
  30933. GetterByBindingType: [
  30934. function getValue_direct( buffer, offset ) {
  30935. buffer[ offset ] = this.node[ this.propertyName ];
  30936. },
  30937. function getValue_array( buffer, offset ) {
  30938. var source = this.resolvedProperty;
  30939. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  30940. buffer[ offset ++ ] = source[ i ];
  30941. }
  30942. },
  30943. function getValue_arrayElement( buffer, offset ) {
  30944. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  30945. },
  30946. function getValue_toArray( buffer, offset ) {
  30947. this.resolvedProperty.toArray( buffer, offset );
  30948. }
  30949. ],
  30950. SetterByBindingTypeAndVersioning: [
  30951. [
  30952. // Direct
  30953. function setValue_direct( buffer, offset ) {
  30954. this.targetObject[ this.propertyName ] = buffer[ offset ];
  30955. },
  30956. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  30957. this.targetObject[ this.propertyName ] = buffer[ offset ];
  30958. this.targetObject.needsUpdate = true;
  30959. },
  30960. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  30961. this.targetObject[ this.propertyName ] = buffer[ offset ];
  30962. this.targetObject.matrixWorldNeedsUpdate = true;
  30963. }
  30964. ], [
  30965. // EntireArray
  30966. function setValue_array( buffer, offset ) {
  30967. var dest = this.resolvedProperty;
  30968. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  30969. dest[ i ] = buffer[ offset ++ ];
  30970. }
  30971. },
  30972. function setValue_array_setNeedsUpdate( buffer, offset ) {
  30973. var dest = this.resolvedProperty;
  30974. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  30975. dest[ i ] = buffer[ offset ++ ];
  30976. }
  30977. this.targetObject.needsUpdate = true;
  30978. },
  30979. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  30980. var dest = this.resolvedProperty;
  30981. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  30982. dest[ i ] = buffer[ offset ++ ];
  30983. }
  30984. this.targetObject.matrixWorldNeedsUpdate = true;
  30985. }
  30986. ], [
  30987. // ArrayElement
  30988. function setValue_arrayElement( buffer, offset ) {
  30989. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  30990. },
  30991. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  30992. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  30993. this.targetObject.needsUpdate = true;
  30994. },
  30995. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  30996. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  30997. this.targetObject.matrixWorldNeedsUpdate = true;
  30998. }
  30999. ], [
  31000. // HasToFromArray
  31001. function setValue_fromArray( buffer, offset ) {
  31002. this.resolvedProperty.fromArray( buffer, offset );
  31003. },
  31004. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  31005. this.resolvedProperty.fromArray( buffer, offset );
  31006. this.targetObject.needsUpdate = true;
  31007. },
  31008. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31009. this.resolvedProperty.fromArray( buffer, offset );
  31010. this.targetObject.matrixWorldNeedsUpdate = true;
  31011. }
  31012. ]
  31013. ],
  31014. getValue: function getValue_unbound( targetArray, offset ) {
  31015. this.bind();
  31016. this.getValue( targetArray, offset );
  31017. // Note: This class uses a State pattern on a per-method basis:
  31018. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31019. // prototype version of these methods with one that represents
  31020. // the bound state. When the property is not found, the methods
  31021. // become no-ops.
  31022. },
  31023. setValue: function getValue_unbound( sourceArray, offset ) {
  31024. this.bind();
  31025. this.setValue( sourceArray, offset );
  31026. },
  31027. // create getter / setter pair for a property in the scene graph
  31028. bind: function () {
  31029. var targetObject = this.node,
  31030. parsedPath = this.parsedPath,
  31031. objectName = parsedPath.objectName,
  31032. propertyName = parsedPath.propertyName,
  31033. propertyIndex = parsedPath.propertyIndex;
  31034. if ( ! targetObject ) {
  31035. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  31036. this.node = targetObject;
  31037. }
  31038. // set fail state so we can just 'return' on error
  31039. this.getValue = this._getValue_unavailable;
  31040. this.setValue = this._setValue_unavailable;
  31041. // ensure there is a value node
  31042. if ( ! targetObject ) {
  31043. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  31044. return;
  31045. }
  31046. if ( objectName ) {
  31047. var objectIndex = parsedPath.objectIndex;
  31048. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31049. switch ( objectName ) {
  31050. case 'materials':
  31051. if ( ! targetObject.material ) {
  31052. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  31053. return;
  31054. }
  31055. if ( ! targetObject.material.materials ) {
  31056. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  31057. return;
  31058. }
  31059. targetObject = targetObject.material.materials;
  31060. break;
  31061. case 'bones':
  31062. if ( ! targetObject.skeleton ) {
  31063. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  31064. return;
  31065. }
  31066. // potential future optimization: skip this if propertyIndex is already an integer
  31067. // and convert the integer string to a true integer.
  31068. targetObject = targetObject.skeleton.bones;
  31069. // support resolving morphTarget names into indices.
  31070. for ( var i = 0; i < targetObject.length; i ++ ) {
  31071. if ( targetObject[ i ].name === objectIndex ) {
  31072. objectIndex = i;
  31073. break;
  31074. }
  31075. }
  31076. break;
  31077. default:
  31078. if ( targetObject[ objectName ] === undefined ) {
  31079. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  31080. return;
  31081. }
  31082. targetObject = targetObject[ objectName ];
  31083. }
  31084. if ( objectIndex !== undefined ) {
  31085. if ( targetObject[ objectIndex ] === undefined ) {
  31086. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  31087. return;
  31088. }
  31089. targetObject = targetObject[ objectIndex ];
  31090. }
  31091. }
  31092. // resolve property
  31093. var nodeProperty = targetObject[ propertyName ];
  31094. if ( nodeProperty === undefined ) {
  31095. var nodeName = parsedPath.nodeName;
  31096. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  31097. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  31098. return;
  31099. }
  31100. // determine versioning scheme
  31101. var versioning = this.Versioning.None;
  31102. this.targetObject = targetObject;
  31103. if ( targetObject.needsUpdate !== undefined ) { // material
  31104. versioning = this.Versioning.NeedsUpdate;
  31105. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  31106. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31107. }
  31108. // determine how the property gets bound
  31109. var bindingType = this.BindingType.Direct;
  31110. if ( propertyIndex !== undefined ) {
  31111. // access a sub element of the property array (only primitives are supported right now)
  31112. if ( propertyName === "morphTargetInfluences" ) {
  31113. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31114. // support resolving morphTarget names into indices.
  31115. if ( ! targetObject.geometry ) {
  31116. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  31117. return;
  31118. }
  31119. if ( targetObject.geometry.isBufferGeometry ) {
  31120. if ( ! targetObject.geometry.morphAttributes ) {
  31121. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  31122. return;
  31123. }
  31124. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  31125. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  31126. propertyIndex = i;
  31127. break;
  31128. }
  31129. }
  31130. } else {
  31131. if ( ! targetObject.geometry.morphTargets ) {
  31132. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  31133. return;
  31134. }
  31135. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  31136. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  31137. propertyIndex = i;
  31138. break;
  31139. }
  31140. }
  31141. }
  31142. }
  31143. bindingType = this.BindingType.ArrayElement;
  31144. this.resolvedProperty = nodeProperty;
  31145. this.propertyIndex = propertyIndex;
  31146. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  31147. // must use copy for Object3D.Euler/Quaternion
  31148. bindingType = this.BindingType.HasFromToArray;
  31149. this.resolvedProperty = nodeProperty;
  31150. } else if ( Array.isArray( nodeProperty ) ) {
  31151. bindingType = this.BindingType.EntireArray;
  31152. this.resolvedProperty = nodeProperty;
  31153. } else {
  31154. this.propertyName = propertyName;
  31155. }
  31156. // select getter / setter
  31157. this.getValue = this.GetterByBindingType[ bindingType ];
  31158. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  31159. },
  31160. unbind: function () {
  31161. this.node = null;
  31162. // back to the prototype version of getValue / setValue
  31163. // note: avoiding to mutate the shape of 'this' via 'delete'
  31164. this.getValue = this._getValue_unbound;
  31165. this.setValue = this._setValue_unbound;
  31166. }
  31167. } );
  31168. //!\ DECLARE ALIAS AFTER assign prototype !
  31169. Object.assign( PropertyBinding.prototype, {
  31170. // initial state of these methods that calls 'bind'
  31171. _getValue_unbound: PropertyBinding.prototype.getValue,
  31172. _setValue_unbound: PropertyBinding.prototype.setValue,
  31173. } );
  31174. /**
  31175. *
  31176. * A group of objects that receives a shared animation state.
  31177. *
  31178. * Usage:
  31179. *
  31180. * - Add objects you would otherwise pass as 'root' to the
  31181. * constructor or the .clipAction method of AnimationMixer.
  31182. *
  31183. * - Instead pass this object as 'root'.
  31184. *
  31185. * - You can also add and remove objects later when the mixer
  31186. * is running.
  31187. *
  31188. * Note:
  31189. *
  31190. * Objects of this class appear as one object to the mixer,
  31191. * so cache control of the individual objects must be done
  31192. * on the group.
  31193. *
  31194. * Limitation:
  31195. *
  31196. * - The animated properties must be compatible among the
  31197. * all objects in the group.
  31198. *
  31199. * - A single property can either be controlled through a
  31200. * target group or directly, but not both.
  31201. *
  31202. * @author tschw
  31203. */
  31204. function AnimationObjectGroup() {
  31205. this.uuid = _Math.generateUUID();
  31206. // cached objects followed by the active ones
  31207. this._objects = Array.prototype.slice.call( arguments );
  31208. this.nCachedObjects_ = 0; // threshold
  31209. // note: read by PropertyBinding.Composite
  31210. var indices = {};
  31211. this._indicesByUUID = indices; // for bookkeeping
  31212. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31213. indices[ arguments[ i ].uuid ] = i;
  31214. }
  31215. this._paths = []; // inside: string
  31216. this._parsedPaths = []; // inside: { we don't care, here }
  31217. this._bindings = []; // inside: Array< PropertyBinding >
  31218. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  31219. var scope = this;
  31220. this.stats = {
  31221. objects: {
  31222. get total() {
  31223. return scope._objects.length;
  31224. },
  31225. get inUse() {
  31226. return this.total - scope.nCachedObjects_;
  31227. }
  31228. },
  31229. get bindingsPerObject() {
  31230. return scope._bindings.length;
  31231. }
  31232. };
  31233. }
  31234. Object.assign( AnimationObjectGroup.prototype, {
  31235. isAnimationObjectGroup: true,
  31236. add: function () {
  31237. var objects = this._objects,
  31238. nObjects = objects.length,
  31239. nCachedObjects = this.nCachedObjects_,
  31240. indicesByUUID = this._indicesByUUID,
  31241. paths = this._paths,
  31242. parsedPaths = this._parsedPaths,
  31243. bindings = this._bindings,
  31244. nBindings = bindings.length,
  31245. knownObject = undefined;
  31246. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31247. var object = arguments[ i ],
  31248. uuid = object.uuid,
  31249. index = indicesByUUID[ uuid ];
  31250. if ( index === undefined ) {
  31251. // unknown object -> add it to the ACTIVE region
  31252. index = nObjects ++;
  31253. indicesByUUID[ uuid ] = index;
  31254. objects.push( object );
  31255. // accounting is done, now do the same for all bindings
  31256. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31257. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  31258. }
  31259. } else if ( index < nCachedObjects ) {
  31260. knownObject = objects[ index ];
  31261. // move existing object to the ACTIVE region
  31262. var firstActiveIndex = -- nCachedObjects,
  31263. lastCachedObject = objects[ firstActiveIndex ];
  31264. indicesByUUID[ lastCachedObject.uuid ] = index;
  31265. objects[ index ] = lastCachedObject;
  31266. indicesByUUID[ uuid ] = firstActiveIndex;
  31267. objects[ firstActiveIndex ] = object;
  31268. // accounting is done, now do the same for all bindings
  31269. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31270. var bindingsForPath = bindings[ j ],
  31271. lastCached = bindingsForPath[ firstActiveIndex ],
  31272. binding = bindingsForPath[ index ];
  31273. bindingsForPath[ index ] = lastCached;
  31274. if ( binding === undefined ) {
  31275. // since we do not bother to create new bindings
  31276. // for objects that are cached, the binding may
  31277. // or may not exist
  31278. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  31279. }
  31280. bindingsForPath[ firstActiveIndex ] = binding;
  31281. }
  31282. } else if ( objects[ index ] !== knownObject ) {
  31283. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  31284. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  31285. } // else the object is already where we want it to be
  31286. } // for arguments
  31287. this.nCachedObjects_ = nCachedObjects;
  31288. },
  31289. remove: function () {
  31290. var objects = this._objects,
  31291. nCachedObjects = this.nCachedObjects_,
  31292. indicesByUUID = this._indicesByUUID,
  31293. bindings = this._bindings,
  31294. nBindings = bindings.length;
  31295. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31296. var object = arguments[ i ],
  31297. uuid = object.uuid,
  31298. index = indicesByUUID[ uuid ];
  31299. if ( index !== undefined && index >= nCachedObjects ) {
  31300. // move existing object into the CACHED region
  31301. var lastCachedIndex = nCachedObjects ++,
  31302. firstActiveObject = objects[ lastCachedIndex ];
  31303. indicesByUUID[ firstActiveObject.uuid ] = index;
  31304. objects[ index ] = firstActiveObject;
  31305. indicesByUUID[ uuid ] = lastCachedIndex;
  31306. objects[ lastCachedIndex ] = object;
  31307. // accounting is done, now do the same for all bindings
  31308. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31309. var bindingsForPath = bindings[ j ],
  31310. firstActive = bindingsForPath[ lastCachedIndex ],
  31311. binding = bindingsForPath[ index ];
  31312. bindingsForPath[ index ] = firstActive;
  31313. bindingsForPath[ lastCachedIndex ] = binding;
  31314. }
  31315. }
  31316. } // for arguments
  31317. this.nCachedObjects_ = nCachedObjects;
  31318. },
  31319. // remove & forget
  31320. uncache: function () {
  31321. var objects = this._objects,
  31322. nObjects = objects.length,
  31323. nCachedObjects = this.nCachedObjects_,
  31324. indicesByUUID = this._indicesByUUID,
  31325. bindings = this._bindings,
  31326. nBindings = bindings.length;
  31327. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31328. var object = arguments[ i ],
  31329. uuid = object.uuid,
  31330. index = indicesByUUID[ uuid ];
  31331. if ( index !== undefined ) {
  31332. delete indicesByUUID[ uuid ];
  31333. if ( index < nCachedObjects ) {
  31334. // object is cached, shrink the CACHED region
  31335. var firstActiveIndex = -- nCachedObjects,
  31336. lastCachedObject = objects[ firstActiveIndex ],
  31337. lastIndex = -- nObjects,
  31338. lastObject = objects[ lastIndex ];
  31339. // last cached object takes this object's place
  31340. indicesByUUID[ lastCachedObject.uuid ] = index;
  31341. objects[ index ] = lastCachedObject;
  31342. // last object goes to the activated slot and pop
  31343. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  31344. objects[ firstActiveIndex ] = lastObject;
  31345. objects.pop();
  31346. // accounting is done, now do the same for all bindings
  31347. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31348. var bindingsForPath = bindings[ j ],
  31349. lastCached = bindingsForPath[ firstActiveIndex ],
  31350. last = bindingsForPath[ lastIndex ];
  31351. bindingsForPath[ index ] = lastCached;
  31352. bindingsForPath[ firstActiveIndex ] = last;
  31353. bindingsForPath.pop();
  31354. }
  31355. } else {
  31356. // object is active, just swap with the last and pop
  31357. var lastIndex = -- nObjects,
  31358. lastObject = objects[ lastIndex ];
  31359. indicesByUUID[ lastObject.uuid ] = index;
  31360. objects[ index ] = lastObject;
  31361. objects.pop();
  31362. // accounting is done, now do the same for all bindings
  31363. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31364. var bindingsForPath = bindings[ j ];
  31365. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  31366. bindingsForPath.pop();
  31367. }
  31368. } // cached or active
  31369. } // if object is known
  31370. } // for arguments
  31371. this.nCachedObjects_ = nCachedObjects;
  31372. },
  31373. // Internal interface used by befriended PropertyBinding.Composite:
  31374. subscribe_: function ( path, parsedPath ) {
  31375. // returns an array of bindings for the given path that is changed
  31376. // according to the contained objects in the group
  31377. var indicesByPath = this._bindingsIndicesByPath,
  31378. index = indicesByPath[ path ],
  31379. bindings = this._bindings;
  31380. if ( index !== undefined ) { return bindings[ index ]; }
  31381. var paths = this._paths,
  31382. parsedPaths = this._parsedPaths,
  31383. objects = this._objects,
  31384. nObjects = objects.length,
  31385. nCachedObjects = this.nCachedObjects_,
  31386. bindingsForPath = new Array( nObjects );
  31387. index = bindings.length;
  31388. indicesByPath[ path ] = index;
  31389. paths.push( path );
  31390. parsedPaths.push( parsedPath );
  31391. bindings.push( bindingsForPath );
  31392. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  31393. var object = objects[ i ];
  31394. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  31395. }
  31396. return bindingsForPath;
  31397. },
  31398. unsubscribe_: function ( path ) {
  31399. // tells the group to forget about a property path and no longer
  31400. // update the array previously obtained with 'subscribe_'
  31401. var indicesByPath = this._bindingsIndicesByPath,
  31402. index = indicesByPath[ path ];
  31403. if ( index !== undefined ) {
  31404. var paths = this._paths,
  31405. parsedPaths = this._parsedPaths,
  31406. bindings = this._bindings,
  31407. lastBindingsIndex = bindings.length - 1,
  31408. lastBindings = bindings[ lastBindingsIndex ],
  31409. lastBindingsPath = path[ lastBindingsIndex ];
  31410. indicesByPath[ lastBindingsPath ] = index;
  31411. bindings[ index ] = lastBindings;
  31412. bindings.pop();
  31413. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  31414. parsedPaths.pop();
  31415. paths[ index ] = paths[ lastBindingsIndex ];
  31416. paths.pop();
  31417. }
  31418. }
  31419. } );
  31420. /**
  31421. *
  31422. * Action provided by AnimationMixer for scheduling clip playback on specific
  31423. * objects.
  31424. *
  31425. * @author Ben Houston / http://clara.io/
  31426. * @author David Sarno / http://lighthaus.us/
  31427. * @author tschw
  31428. *
  31429. */
  31430. function AnimationAction( mixer, clip, localRoot ) {
  31431. this._mixer = mixer;
  31432. this._clip = clip;
  31433. this._localRoot = localRoot || null;
  31434. var tracks = clip.tracks,
  31435. nTracks = tracks.length,
  31436. interpolants = new Array( nTracks );
  31437. var interpolantSettings = {
  31438. endingStart: ZeroCurvatureEnding,
  31439. endingEnd: ZeroCurvatureEnding
  31440. };
  31441. for ( var i = 0; i !== nTracks; ++ i ) {
  31442. var interpolant = tracks[ i ].createInterpolant( null );
  31443. interpolants[ i ] = interpolant;
  31444. interpolant.settings = interpolantSettings;
  31445. }
  31446. this._interpolantSettings = interpolantSettings;
  31447. this._interpolants = interpolants; // bound by the mixer
  31448. // inside: PropertyMixer (managed by the mixer)
  31449. this._propertyBindings = new Array( nTracks );
  31450. this._cacheIndex = null; // for the memory manager
  31451. this._byClipCacheIndex = null; // for the memory manager
  31452. this._timeScaleInterpolant = null;
  31453. this._weightInterpolant = null;
  31454. this.loop = LoopRepeat;
  31455. this._loopCount = - 1;
  31456. // global mixer time when the action is to be started
  31457. // it's set back to 'null' upon start of the action
  31458. this._startTime = null;
  31459. // scaled local time of the action
  31460. // gets clamped or wrapped to 0..clip.duration according to loop
  31461. this.time = 0;
  31462. this.timeScale = 1;
  31463. this._effectiveTimeScale = 1;
  31464. this.weight = 1;
  31465. this._effectiveWeight = 1;
  31466. this.repetitions = Infinity; // no. of repetitions when looping
  31467. this.paused = false; // true -> zero effective time scale
  31468. this.enabled = true; // false -> zero effective weight
  31469. this.clampWhenFinished = false;// keep feeding the last frame?
  31470. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  31471. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  31472. }
  31473. Object.assign( AnimationAction.prototype, {
  31474. // State & Scheduling
  31475. play: function () {
  31476. this._mixer._activateAction( this );
  31477. return this;
  31478. },
  31479. stop: function () {
  31480. this._mixer._deactivateAction( this );
  31481. return this.reset();
  31482. },
  31483. reset: function () {
  31484. this.paused = false;
  31485. this.enabled = true;
  31486. this.time = 0; // restart clip
  31487. this._loopCount = - 1;// forget previous loops
  31488. this._startTime = null;// forget scheduling
  31489. return this.stopFading().stopWarping();
  31490. },
  31491. isRunning: function () {
  31492. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  31493. this._startTime === null && this._mixer._isActiveAction( this );
  31494. },
  31495. // return true when play has been called
  31496. isScheduled: function () {
  31497. return this._mixer._isActiveAction( this );
  31498. },
  31499. startAt: function ( time ) {
  31500. this._startTime = time;
  31501. return this;
  31502. },
  31503. setLoop: function ( mode, repetitions ) {
  31504. this.loop = mode;
  31505. this.repetitions = repetitions;
  31506. return this;
  31507. },
  31508. // Weight
  31509. // set the weight stopping any scheduled fading
  31510. // although .enabled = false yields an effective weight of zero, this
  31511. // method does *not* change .enabled, because it would be confusing
  31512. setEffectiveWeight: function ( weight ) {
  31513. this.weight = weight;
  31514. // note: same logic as when updated at runtime
  31515. this._effectiveWeight = this.enabled ? weight : 0;
  31516. return this.stopFading();
  31517. },
  31518. // return the weight considering fading and .enabled
  31519. getEffectiveWeight: function () {
  31520. return this._effectiveWeight;
  31521. },
  31522. fadeIn: function ( duration ) {
  31523. return this._scheduleFading( duration, 0, 1 );
  31524. },
  31525. fadeOut: function ( duration ) {
  31526. return this._scheduleFading( duration, 1, 0 );
  31527. },
  31528. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  31529. fadeOutAction.fadeOut( duration );
  31530. this.fadeIn( duration );
  31531. if ( warp ) {
  31532. var fadeInDuration = this._clip.duration,
  31533. fadeOutDuration = fadeOutAction._clip.duration,
  31534. startEndRatio = fadeOutDuration / fadeInDuration,
  31535. endStartRatio = fadeInDuration / fadeOutDuration;
  31536. fadeOutAction.warp( 1.0, startEndRatio, duration );
  31537. this.warp( endStartRatio, 1.0, duration );
  31538. }
  31539. return this;
  31540. },
  31541. crossFadeTo: function ( fadeInAction, duration, warp ) {
  31542. return fadeInAction.crossFadeFrom( this, duration, warp );
  31543. },
  31544. stopFading: function () {
  31545. var weightInterpolant = this._weightInterpolant;
  31546. if ( weightInterpolant !== null ) {
  31547. this._weightInterpolant = null;
  31548. this._mixer._takeBackControlInterpolant( weightInterpolant );
  31549. }
  31550. return this;
  31551. },
  31552. // Time Scale Control
  31553. // set the time scale stopping any scheduled warping
  31554. // although .paused = true yields an effective time scale of zero, this
  31555. // method does *not* change .paused, because it would be confusing
  31556. setEffectiveTimeScale: function ( timeScale ) {
  31557. this.timeScale = timeScale;
  31558. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  31559. return this.stopWarping();
  31560. },
  31561. // return the time scale considering warping and .paused
  31562. getEffectiveTimeScale: function () {
  31563. return this._effectiveTimeScale;
  31564. },
  31565. setDuration: function ( duration ) {
  31566. this.timeScale = this._clip.duration / duration;
  31567. return this.stopWarping();
  31568. },
  31569. syncWith: function ( action ) {
  31570. this.time = action.time;
  31571. this.timeScale = action.timeScale;
  31572. return this.stopWarping();
  31573. },
  31574. halt: function ( duration ) {
  31575. return this.warp( this._effectiveTimeScale, 0, duration );
  31576. },
  31577. warp: function ( startTimeScale, endTimeScale, duration ) {
  31578. var mixer = this._mixer, now = mixer.time,
  31579. interpolant = this._timeScaleInterpolant,
  31580. timeScale = this.timeScale;
  31581. if ( interpolant === null ) {
  31582. interpolant = mixer._lendControlInterpolant();
  31583. this._timeScaleInterpolant = interpolant;
  31584. }
  31585. var times = interpolant.parameterPositions,
  31586. values = interpolant.sampleValues;
  31587. times[ 0 ] = now;
  31588. times[ 1 ] = now + duration;
  31589. values[ 0 ] = startTimeScale / timeScale;
  31590. values[ 1 ] = endTimeScale / timeScale;
  31591. return this;
  31592. },
  31593. stopWarping: function () {
  31594. var timeScaleInterpolant = this._timeScaleInterpolant;
  31595. if ( timeScaleInterpolant !== null ) {
  31596. this._timeScaleInterpolant = null;
  31597. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  31598. }
  31599. return this;
  31600. },
  31601. // Object Accessors
  31602. getMixer: function () {
  31603. return this._mixer;
  31604. },
  31605. getClip: function () {
  31606. return this._clip;
  31607. },
  31608. getRoot: function () {
  31609. return this._localRoot || this._mixer._root;
  31610. },
  31611. // Interna
  31612. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  31613. // called by the mixer
  31614. if ( ! this.enabled ) {
  31615. // call ._updateWeight() to update ._effectiveWeight
  31616. this._updateWeight( time );
  31617. return;
  31618. }
  31619. var startTime = this._startTime;
  31620. if ( startTime !== null ) {
  31621. // check for scheduled start of action
  31622. var timeRunning = ( time - startTime ) * timeDirection;
  31623. if ( timeRunning < 0 || timeDirection === 0 ) {
  31624. return; // yet to come / don't decide when delta = 0
  31625. }
  31626. // start
  31627. this._startTime = null; // unschedule
  31628. deltaTime = timeDirection * timeRunning;
  31629. }
  31630. // apply time scale and advance time
  31631. deltaTime *= this._updateTimeScale( time );
  31632. var clipTime = this._updateTime( deltaTime );
  31633. // note: _updateTime may disable the action resulting in
  31634. // an effective weight of 0
  31635. var weight = this._updateWeight( time );
  31636. if ( weight > 0 ) {
  31637. var interpolants = this._interpolants;
  31638. var propertyMixers = this._propertyBindings;
  31639. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  31640. interpolants[ j ].evaluate( clipTime );
  31641. propertyMixers[ j ].accumulate( accuIndex, weight );
  31642. }
  31643. }
  31644. },
  31645. _updateWeight: function ( time ) {
  31646. var weight = 0;
  31647. if ( this.enabled ) {
  31648. weight = this.weight;
  31649. var interpolant = this._weightInterpolant;
  31650. if ( interpolant !== null ) {
  31651. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  31652. weight *= interpolantValue;
  31653. if ( time > interpolant.parameterPositions[ 1 ] ) {
  31654. this.stopFading();
  31655. if ( interpolantValue === 0 ) {
  31656. // faded out, disable
  31657. this.enabled = false;
  31658. }
  31659. }
  31660. }
  31661. }
  31662. this._effectiveWeight = weight;
  31663. return weight;
  31664. },
  31665. _updateTimeScale: function ( time ) {
  31666. var timeScale = 0;
  31667. if ( ! this.paused ) {
  31668. timeScale = this.timeScale;
  31669. var interpolant = this._timeScaleInterpolant;
  31670. if ( interpolant !== null ) {
  31671. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  31672. timeScale *= interpolantValue;
  31673. if ( time > interpolant.parameterPositions[ 1 ] ) {
  31674. this.stopWarping();
  31675. if ( timeScale === 0 ) {
  31676. // motion has halted, pause
  31677. this.paused = true;
  31678. } else {
  31679. // warp done - apply final time scale
  31680. this.timeScale = timeScale;
  31681. }
  31682. }
  31683. }
  31684. }
  31685. this._effectiveTimeScale = timeScale;
  31686. return timeScale;
  31687. },
  31688. _updateTime: function ( deltaTime ) {
  31689. var time = this.time + deltaTime;
  31690. var duration = this._clip.duration;
  31691. var loop = this.loop;
  31692. var loopCount = this._loopCount;
  31693. var pingPong = ( loop === LoopPingPong );
  31694. if ( deltaTime === 0 ) {
  31695. if ( loopCount === - 1 ) { return time; }
  31696. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  31697. }
  31698. if ( loop === LoopOnce ) {
  31699. if ( loopCount === - 1 ) {
  31700. // just started
  31701. this._loopCount = 0;
  31702. this._setEndings( true, true, false );
  31703. }
  31704. handle_stop: {
  31705. if ( time >= duration ) {
  31706. time = duration;
  31707. } else if ( time < 0 ) {
  31708. time = 0;
  31709. } else {
  31710. this.time = time;
  31711. break handle_stop;
  31712. }
  31713. if ( this.clampWhenFinished ) { this.paused = true; }
  31714. else { this.enabled = false; }
  31715. this.time = time;
  31716. this._mixer.dispatchEvent( {
  31717. type: 'finished', action: this,
  31718. direction: deltaTime < 0 ? - 1 : 1
  31719. } );
  31720. }
  31721. } else { // repetitive Repeat or PingPong
  31722. if ( loopCount === - 1 ) {
  31723. // just started
  31724. if ( deltaTime >= 0 ) {
  31725. loopCount = 0;
  31726. this._setEndings( true, this.repetitions === 0, pingPong );
  31727. } else {
  31728. // when looping in reverse direction, the initial
  31729. // transition through zero counts as a repetition,
  31730. // so leave loopCount at -1
  31731. this._setEndings( this.repetitions === 0, true, pingPong );
  31732. }
  31733. }
  31734. if ( time >= duration || time < 0 ) {
  31735. // wrap around
  31736. var loopDelta = Math.floor( time / duration ); // signed
  31737. time -= duration * loopDelta;
  31738. loopCount += Math.abs( loopDelta );
  31739. var pending = this.repetitions - loopCount;
  31740. if ( pending <= 0 ) {
  31741. // have to stop (switch state, clamp time, fire event)
  31742. if ( this.clampWhenFinished ) { this.paused = true; }
  31743. else { this.enabled = false; }
  31744. time = deltaTime > 0 ? duration : 0;
  31745. this.time = time;
  31746. this._mixer.dispatchEvent( {
  31747. type: 'finished', action: this,
  31748. direction: deltaTime > 0 ? 1 : - 1
  31749. } );
  31750. } else {
  31751. // keep running
  31752. if ( pending === 1 ) {
  31753. // entering the last round
  31754. var atStart = deltaTime < 0;
  31755. this._setEndings( atStart, ! atStart, pingPong );
  31756. } else {
  31757. this._setEndings( false, false, pingPong );
  31758. }
  31759. this._loopCount = loopCount;
  31760. this.time = time;
  31761. this._mixer.dispatchEvent( {
  31762. type: 'loop', action: this, loopDelta: loopDelta
  31763. } );
  31764. }
  31765. } else {
  31766. this.time = time;
  31767. }
  31768. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  31769. // invert time for the "pong round"
  31770. return duration - time;
  31771. }
  31772. }
  31773. return time;
  31774. },
  31775. _setEndings: function ( atStart, atEnd, pingPong ) {
  31776. var settings = this._interpolantSettings;
  31777. if ( pingPong ) {
  31778. settings.endingStart = ZeroSlopeEnding;
  31779. settings.endingEnd = ZeroSlopeEnding;
  31780. } else {
  31781. // assuming for LoopOnce atStart == atEnd == true
  31782. if ( atStart ) {
  31783. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  31784. } else {
  31785. settings.endingStart = WrapAroundEnding;
  31786. }
  31787. if ( atEnd ) {
  31788. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  31789. } else {
  31790. settings.endingEnd = WrapAroundEnding;
  31791. }
  31792. }
  31793. },
  31794. _scheduleFading: function ( duration, weightNow, weightThen ) {
  31795. var mixer = this._mixer, now = mixer.time,
  31796. interpolant = this._weightInterpolant;
  31797. if ( interpolant === null ) {
  31798. interpolant = mixer._lendControlInterpolant();
  31799. this._weightInterpolant = interpolant;
  31800. }
  31801. var times = interpolant.parameterPositions,
  31802. values = interpolant.sampleValues;
  31803. times[ 0 ] = now;
  31804. values[ 0 ] = weightNow;
  31805. times[ 1 ] = now + duration;
  31806. values[ 1 ] = weightThen;
  31807. return this;
  31808. }
  31809. } );
  31810. /**
  31811. *
  31812. * Player for AnimationClips.
  31813. *
  31814. *
  31815. * @author Ben Houston / http://clara.io/
  31816. * @author David Sarno / http://lighthaus.us/
  31817. * @author tschw
  31818. */
  31819. function AnimationMixer( root ) {
  31820. this._root = root;
  31821. this._initMemoryManager();
  31822. this._accuIndex = 0;
  31823. this.time = 0;
  31824. this.timeScale = 1.0;
  31825. }
  31826. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  31827. constructor: AnimationMixer,
  31828. _bindAction: function ( action, prototypeAction ) {
  31829. var root = action._localRoot || this._root,
  31830. tracks = action._clip.tracks,
  31831. nTracks = tracks.length,
  31832. bindings = action._propertyBindings,
  31833. interpolants = action._interpolants,
  31834. rootUuid = root.uuid,
  31835. bindingsByRoot = this._bindingsByRootAndName,
  31836. bindingsByName = bindingsByRoot[ rootUuid ];
  31837. if ( bindingsByName === undefined ) {
  31838. bindingsByName = {};
  31839. bindingsByRoot[ rootUuid ] = bindingsByName;
  31840. }
  31841. for ( var i = 0; i !== nTracks; ++ i ) {
  31842. var track = tracks[ i ],
  31843. trackName = track.name,
  31844. binding = bindingsByName[ trackName ];
  31845. if ( binding !== undefined ) {
  31846. bindings[ i ] = binding;
  31847. } else {
  31848. binding = bindings[ i ];
  31849. if ( binding !== undefined ) {
  31850. // existing binding, make sure the cache knows
  31851. if ( binding._cacheIndex === null ) {
  31852. ++ binding.referenceCount;
  31853. this._addInactiveBinding( binding, rootUuid, trackName );
  31854. }
  31855. continue;
  31856. }
  31857. var path = prototypeAction && prototypeAction.
  31858. _propertyBindings[ i ].binding.parsedPath;
  31859. binding = new PropertyMixer(
  31860. PropertyBinding.create( root, trackName, path ),
  31861. track.ValueTypeName, track.getValueSize() );
  31862. ++ binding.referenceCount;
  31863. this._addInactiveBinding( binding, rootUuid, trackName );
  31864. bindings[ i ] = binding;
  31865. }
  31866. interpolants[ i ].resultBuffer = binding.buffer;
  31867. }
  31868. },
  31869. _activateAction: function ( action ) {
  31870. if ( ! this._isActiveAction( action ) ) {
  31871. if ( action._cacheIndex === null ) {
  31872. // this action has been forgotten by the cache, but the user
  31873. // appears to be still using it -> rebind
  31874. var rootUuid = ( action._localRoot || this._root ).uuid,
  31875. clipUuid = action._clip.uuid,
  31876. actionsForClip = this._actionsByClip[ clipUuid ];
  31877. this._bindAction( action,
  31878. actionsForClip && actionsForClip.knownActions[ 0 ] );
  31879. this._addInactiveAction( action, clipUuid, rootUuid );
  31880. }
  31881. var bindings = action._propertyBindings;
  31882. // increment reference counts / sort out state
  31883. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  31884. var binding = bindings[ i ];
  31885. if ( binding.useCount ++ === 0 ) {
  31886. this._lendBinding( binding );
  31887. binding.saveOriginalState();
  31888. }
  31889. }
  31890. this._lendAction( action );
  31891. }
  31892. },
  31893. _deactivateAction: function ( action ) {
  31894. if ( this._isActiveAction( action ) ) {
  31895. var bindings = action._propertyBindings;
  31896. // decrement reference counts / sort out state
  31897. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  31898. var binding = bindings[ i ];
  31899. if ( -- binding.useCount === 0 ) {
  31900. binding.restoreOriginalState();
  31901. this._takeBackBinding( binding );
  31902. }
  31903. }
  31904. this._takeBackAction( action );
  31905. }
  31906. },
  31907. // Memory manager
  31908. _initMemoryManager: function () {
  31909. this._actions = []; // 'nActiveActions' followed by inactive ones
  31910. this._nActiveActions = 0;
  31911. this._actionsByClip = {};
  31912. // inside:
  31913. // {
  31914. // knownActions: Array< AnimationAction > - used as prototypes
  31915. // actionByRoot: AnimationAction - lookup
  31916. // }
  31917. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  31918. this._nActiveBindings = 0;
  31919. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  31920. this._controlInterpolants = []; // same game as above
  31921. this._nActiveControlInterpolants = 0;
  31922. var scope = this;
  31923. this.stats = {
  31924. actions: {
  31925. get total() {
  31926. return scope._actions.length;
  31927. },
  31928. get inUse() {
  31929. return scope._nActiveActions;
  31930. }
  31931. },
  31932. bindings: {
  31933. get total() {
  31934. return scope._bindings.length;
  31935. },
  31936. get inUse() {
  31937. return scope._nActiveBindings;
  31938. }
  31939. },
  31940. controlInterpolants: {
  31941. get total() {
  31942. return scope._controlInterpolants.length;
  31943. },
  31944. get inUse() {
  31945. return scope._nActiveControlInterpolants;
  31946. }
  31947. }
  31948. };
  31949. },
  31950. // Memory management for AnimationAction objects
  31951. _isActiveAction: function ( action ) {
  31952. var index = action._cacheIndex;
  31953. return index !== null && index < this._nActiveActions;
  31954. },
  31955. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  31956. var actions = this._actions,
  31957. actionsByClip = this._actionsByClip,
  31958. actionsForClip = actionsByClip[ clipUuid ];
  31959. if ( actionsForClip === undefined ) {
  31960. actionsForClip = {
  31961. knownActions: [ action ],
  31962. actionByRoot: {}
  31963. };
  31964. action._byClipCacheIndex = 0;
  31965. actionsByClip[ clipUuid ] = actionsForClip;
  31966. } else {
  31967. var knownActions = actionsForClip.knownActions;
  31968. action._byClipCacheIndex = knownActions.length;
  31969. knownActions.push( action );
  31970. }
  31971. action._cacheIndex = actions.length;
  31972. actions.push( action );
  31973. actionsForClip.actionByRoot[ rootUuid ] = action;
  31974. },
  31975. _removeInactiveAction: function ( action ) {
  31976. var actions = this._actions,
  31977. lastInactiveAction = actions[ actions.length - 1 ],
  31978. cacheIndex = action._cacheIndex;
  31979. lastInactiveAction._cacheIndex = cacheIndex;
  31980. actions[ cacheIndex ] = lastInactiveAction;
  31981. actions.pop();
  31982. action._cacheIndex = null;
  31983. var clipUuid = action._clip.uuid,
  31984. actionsByClip = this._actionsByClip,
  31985. actionsForClip = actionsByClip[ clipUuid ],
  31986. knownActionsForClip = actionsForClip.knownActions,
  31987. lastKnownAction =
  31988. knownActionsForClip[ knownActionsForClip.length - 1 ],
  31989. byClipCacheIndex = action._byClipCacheIndex;
  31990. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  31991. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  31992. knownActionsForClip.pop();
  31993. action._byClipCacheIndex = null;
  31994. var actionByRoot = actionsForClip.actionByRoot,
  31995. rootUuid = ( action._localRoot || this._root ).uuid;
  31996. delete actionByRoot[ rootUuid ];
  31997. if ( knownActionsForClip.length === 0 ) {
  31998. delete actionsByClip[ clipUuid ];
  31999. }
  32000. this._removeInactiveBindingsForAction( action );
  32001. },
  32002. _removeInactiveBindingsForAction: function ( action ) {
  32003. var bindings = action._propertyBindings;
  32004. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32005. var binding = bindings[ i ];
  32006. if ( -- binding.referenceCount === 0 ) {
  32007. this._removeInactiveBinding( binding );
  32008. }
  32009. }
  32010. },
  32011. _lendAction: function ( action ) {
  32012. // [ active actions | inactive actions ]
  32013. // [ active actions >| inactive actions ]
  32014. // s a
  32015. // <-swap->
  32016. // a s
  32017. var actions = this._actions,
  32018. prevIndex = action._cacheIndex,
  32019. lastActiveIndex = this._nActiveActions ++,
  32020. firstInactiveAction = actions[ lastActiveIndex ];
  32021. action._cacheIndex = lastActiveIndex;
  32022. actions[ lastActiveIndex ] = action;
  32023. firstInactiveAction._cacheIndex = prevIndex;
  32024. actions[ prevIndex ] = firstInactiveAction;
  32025. },
  32026. _takeBackAction: function ( action ) {
  32027. // [ active actions | inactive actions ]
  32028. // [ active actions |< inactive actions ]
  32029. // a s
  32030. // <-swap->
  32031. // s a
  32032. var actions = this._actions,
  32033. prevIndex = action._cacheIndex,
  32034. firstInactiveIndex = -- this._nActiveActions,
  32035. lastActiveAction = actions[ firstInactiveIndex ];
  32036. action._cacheIndex = firstInactiveIndex;
  32037. actions[ firstInactiveIndex ] = action;
  32038. lastActiveAction._cacheIndex = prevIndex;
  32039. actions[ prevIndex ] = lastActiveAction;
  32040. },
  32041. // Memory management for PropertyMixer objects
  32042. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  32043. var bindingsByRoot = this._bindingsByRootAndName,
  32044. bindingByName = bindingsByRoot[ rootUuid ],
  32045. bindings = this._bindings;
  32046. if ( bindingByName === undefined ) {
  32047. bindingByName = {};
  32048. bindingsByRoot[ rootUuid ] = bindingByName;
  32049. }
  32050. bindingByName[ trackName ] = binding;
  32051. binding._cacheIndex = bindings.length;
  32052. bindings.push( binding );
  32053. },
  32054. _removeInactiveBinding: function ( binding ) {
  32055. var bindings = this._bindings,
  32056. propBinding = binding.binding,
  32057. rootUuid = propBinding.rootNode.uuid,
  32058. trackName = propBinding.path,
  32059. bindingsByRoot = this._bindingsByRootAndName,
  32060. bindingByName = bindingsByRoot[ rootUuid ],
  32061. lastInactiveBinding = bindings[ bindings.length - 1 ],
  32062. cacheIndex = binding._cacheIndex;
  32063. lastInactiveBinding._cacheIndex = cacheIndex;
  32064. bindings[ cacheIndex ] = lastInactiveBinding;
  32065. bindings.pop();
  32066. delete bindingByName[ trackName ];
  32067. if ( Object.keys( bindingByName ).length === 0 ) {
  32068. delete bindingsByRoot[ rootUuid ];
  32069. }
  32070. },
  32071. _lendBinding: function ( binding ) {
  32072. var bindings = this._bindings,
  32073. prevIndex = binding._cacheIndex,
  32074. lastActiveIndex = this._nActiveBindings ++,
  32075. firstInactiveBinding = bindings[ lastActiveIndex ];
  32076. binding._cacheIndex = lastActiveIndex;
  32077. bindings[ lastActiveIndex ] = binding;
  32078. firstInactiveBinding._cacheIndex = prevIndex;
  32079. bindings[ prevIndex ] = firstInactiveBinding;
  32080. },
  32081. _takeBackBinding: function ( binding ) {
  32082. var bindings = this._bindings,
  32083. prevIndex = binding._cacheIndex,
  32084. firstInactiveIndex = -- this._nActiveBindings,
  32085. lastActiveBinding = bindings[ firstInactiveIndex ];
  32086. binding._cacheIndex = firstInactiveIndex;
  32087. bindings[ firstInactiveIndex ] = binding;
  32088. lastActiveBinding._cacheIndex = prevIndex;
  32089. bindings[ prevIndex ] = lastActiveBinding;
  32090. },
  32091. // Memory management of Interpolants for weight and time scale
  32092. _lendControlInterpolant: function () {
  32093. var interpolants = this._controlInterpolants,
  32094. lastActiveIndex = this._nActiveControlInterpolants ++,
  32095. interpolant = interpolants[ lastActiveIndex ];
  32096. if ( interpolant === undefined ) {
  32097. interpolant = new LinearInterpolant(
  32098. new Float32Array( 2 ), new Float32Array( 2 ),
  32099. 1, this._controlInterpolantsResultBuffer );
  32100. interpolant.__cacheIndex = lastActiveIndex;
  32101. interpolants[ lastActiveIndex ] = interpolant;
  32102. }
  32103. return interpolant;
  32104. },
  32105. _takeBackControlInterpolant: function ( interpolant ) {
  32106. var interpolants = this._controlInterpolants,
  32107. prevIndex = interpolant.__cacheIndex,
  32108. firstInactiveIndex = -- this._nActiveControlInterpolants,
  32109. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  32110. interpolant.__cacheIndex = firstInactiveIndex;
  32111. interpolants[ firstInactiveIndex ] = interpolant;
  32112. lastActiveInterpolant.__cacheIndex = prevIndex;
  32113. interpolants[ prevIndex ] = lastActiveInterpolant;
  32114. },
  32115. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  32116. // return an action for a clip optionally using a custom root target
  32117. // object (this method allocates a lot of dynamic memory in case a
  32118. // previously unknown clip/root combination is specified)
  32119. clipAction: function ( clip, optionalRoot ) {
  32120. var root = optionalRoot || this._root,
  32121. rootUuid = root.uuid,
  32122. clipObject = typeof clip === 'string' ?
  32123. AnimationClip.findByName( root, clip ) : clip,
  32124. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  32125. actionsForClip = this._actionsByClip[ clipUuid ],
  32126. prototypeAction = null;
  32127. if ( actionsForClip !== undefined ) {
  32128. var existingAction =
  32129. actionsForClip.actionByRoot[ rootUuid ];
  32130. if ( existingAction !== undefined ) {
  32131. return existingAction;
  32132. }
  32133. // we know the clip, so we don't have to parse all
  32134. // the bindings again but can just copy
  32135. prototypeAction = actionsForClip.knownActions[ 0 ];
  32136. // also, take the clip from the prototype action
  32137. if ( clipObject === null )
  32138. { clipObject = prototypeAction._clip; }
  32139. }
  32140. // clip must be known when specified via string
  32141. if ( clipObject === null ) { return null; }
  32142. // allocate all resources required to run it
  32143. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  32144. this._bindAction( newAction, prototypeAction );
  32145. // and make the action known to the memory manager
  32146. this._addInactiveAction( newAction, clipUuid, rootUuid );
  32147. return newAction;
  32148. },
  32149. // get an existing action
  32150. existingAction: function ( clip, optionalRoot ) {
  32151. var root = optionalRoot || this._root,
  32152. rootUuid = root.uuid,
  32153. clipObject = typeof clip === 'string' ?
  32154. AnimationClip.findByName( root, clip ) : clip,
  32155. clipUuid = clipObject ? clipObject.uuid : clip,
  32156. actionsForClip = this._actionsByClip[ clipUuid ];
  32157. if ( actionsForClip !== undefined ) {
  32158. return actionsForClip.actionByRoot[ rootUuid ] || null;
  32159. }
  32160. return null;
  32161. },
  32162. // deactivates all previously scheduled actions
  32163. stopAllAction: function () {
  32164. var actions = this._actions,
  32165. nActions = this._nActiveActions,
  32166. bindings = this._bindings,
  32167. nBindings = this._nActiveBindings;
  32168. this._nActiveActions = 0;
  32169. this._nActiveBindings = 0;
  32170. for ( var i = 0; i !== nActions; ++ i ) {
  32171. actions[ i ].reset();
  32172. }
  32173. for ( var i = 0; i !== nBindings; ++ i ) {
  32174. bindings[ i ].useCount = 0;
  32175. }
  32176. return this;
  32177. },
  32178. // advance the time and update apply the animation
  32179. update: function ( deltaTime ) {
  32180. deltaTime *= this.timeScale;
  32181. var actions = this._actions,
  32182. nActions = this._nActiveActions,
  32183. time = this.time += deltaTime,
  32184. timeDirection = Math.sign( deltaTime ),
  32185. accuIndex = this._accuIndex ^= 1;
  32186. // run active actions
  32187. for ( var i = 0; i !== nActions; ++ i ) {
  32188. var action = actions[ i ];
  32189. action._update( time, deltaTime, timeDirection, accuIndex );
  32190. }
  32191. // update scene graph
  32192. var bindings = this._bindings,
  32193. nBindings = this._nActiveBindings;
  32194. for ( var i = 0; i !== nBindings; ++ i ) {
  32195. bindings[ i ].apply( accuIndex );
  32196. }
  32197. return this;
  32198. },
  32199. // return this mixer's root target object
  32200. getRoot: function () {
  32201. return this._root;
  32202. },
  32203. // free all resources specific to a particular clip
  32204. uncacheClip: function ( clip ) {
  32205. var actions = this._actions,
  32206. clipUuid = clip.uuid,
  32207. actionsByClip = this._actionsByClip,
  32208. actionsForClip = actionsByClip[ clipUuid ];
  32209. if ( actionsForClip !== undefined ) {
  32210. // note: just calling _removeInactiveAction would mess up the
  32211. // iteration state and also require updating the state we can
  32212. // just throw away
  32213. var actionsToRemove = actionsForClip.knownActions;
  32214. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  32215. var action = actionsToRemove[ i ];
  32216. this._deactivateAction( action );
  32217. var cacheIndex = action._cacheIndex,
  32218. lastInactiveAction = actions[ actions.length - 1 ];
  32219. action._cacheIndex = null;
  32220. action._byClipCacheIndex = null;
  32221. lastInactiveAction._cacheIndex = cacheIndex;
  32222. actions[ cacheIndex ] = lastInactiveAction;
  32223. actions.pop();
  32224. this._removeInactiveBindingsForAction( action );
  32225. }
  32226. delete actionsByClip[ clipUuid ];
  32227. }
  32228. },
  32229. // free all resources specific to a particular root target object
  32230. uncacheRoot: function ( root ) {
  32231. var rootUuid = root.uuid,
  32232. actionsByClip = this._actionsByClip;
  32233. for ( var clipUuid in actionsByClip ) {
  32234. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  32235. action = actionByRoot[ rootUuid ];
  32236. if ( action !== undefined ) {
  32237. this._deactivateAction( action );
  32238. this._removeInactiveAction( action );
  32239. }
  32240. }
  32241. var bindingsByRoot = this._bindingsByRootAndName,
  32242. bindingByName = bindingsByRoot[ rootUuid ];
  32243. if ( bindingByName !== undefined ) {
  32244. for ( var trackName in bindingByName ) {
  32245. var binding = bindingByName[ trackName ];
  32246. binding.restoreOriginalState();
  32247. this._removeInactiveBinding( binding );
  32248. }
  32249. }
  32250. },
  32251. // remove a targeted clip from the cache
  32252. uncacheAction: function ( clip, optionalRoot ) {
  32253. var action = this.existingAction( clip, optionalRoot );
  32254. if ( action !== null ) {
  32255. this._deactivateAction( action );
  32256. this._removeInactiveAction( action );
  32257. }
  32258. }
  32259. } );
  32260. /**
  32261. * @author mrdoob / http://mrdoob.com/
  32262. */
  32263. function Uniform( value ) {
  32264. if ( typeof value === 'string' ) {
  32265. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  32266. value = arguments[ 1 ];
  32267. }
  32268. this.value = value;
  32269. }
  32270. Uniform.prototype.clone = function () {
  32271. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  32272. };
  32273. /**
  32274. * @author benaadams / https://twitter.com/ben_a_adams
  32275. */
  32276. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  32277. InterleavedBuffer.call( this, array, stride );
  32278. this.meshPerAttribute = meshPerAttribute || 1;
  32279. }
  32280. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  32281. constructor: InstancedInterleavedBuffer,
  32282. isInstancedInterleavedBuffer: true,
  32283. copy: function ( source ) {
  32284. InterleavedBuffer.prototype.copy.call( this, source );
  32285. this.meshPerAttribute = source.meshPerAttribute;
  32286. return this;
  32287. }
  32288. } );
  32289. /**
  32290. * @author mrdoob / http://mrdoob.com/
  32291. * @author bhouston / http://clara.io/
  32292. * @author stephomi / http://stephaneginier.com/
  32293. */
  32294. function Raycaster( origin, direction, near, far ) {
  32295. this.ray = new Ray( origin, direction );
  32296. // direction is assumed to be normalized (for accurate distance calculations)
  32297. this.near = near || 0;
  32298. this.far = far || Infinity;
  32299. this.camera = null;
  32300. this.params = {
  32301. Mesh: {},
  32302. Line: {},
  32303. LOD: {},
  32304. Points: { threshold: 1 },
  32305. Sprite: {}
  32306. };
  32307. Object.defineProperties( this.params, {
  32308. PointCloud: {
  32309. get: function () {
  32310. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  32311. return this.Points;
  32312. }
  32313. }
  32314. } );
  32315. }
  32316. function ascSort( a, b ) {
  32317. return a.distance - b.distance;
  32318. }
  32319. function intersectObject( object, raycaster, intersects, recursive ) {
  32320. if ( object.visible === false ) { return; }
  32321. object.raycast( raycaster, intersects );
  32322. if ( recursive === true ) {
  32323. var children = object.children;
  32324. for ( var i = 0, l = children.length; i < l; i ++ ) {
  32325. intersectObject( children[ i ], raycaster, intersects, true );
  32326. }
  32327. }
  32328. }
  32329. Object.assign( Raycaster.prototype, {
  32330. linePrecision: 1,
  32331. set: function ( origin, direction ) {
  32332. // direction is assumed to be normalized (for accurate distance calculations)
  32333. this.ray.set( origin, direction );
  32334. },
  32335. setFromCamera: function ( coords, camera ) {
  32336. if ( ( camera && camera.isPerspectiveCamera ) ) {
  32337. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  32338. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  32339. this.camera = camera;
  32340. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  32341. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  32342. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  32343. this.camera = camera;
  32344. } else {
  32345. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  32346. }
  32347. },
  32348. intersectObject: function ( object, recursive, optionalTarget ) {
  32349. var intersects = optionalTarget || [];
  32350. intersectObject( object, this, intersects, recursive );
  32351. intersects.sort( ascSort );
  32352. return intersects;
  32353. },
  32354. intersectObjects: function ( objects, recursive, optionalTarget ) {
  32355. var intersects = optionalTarget || [];
  32356. if ( Array.isArray( objects ) === false ) {
  32357. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  32358. return intersects;
  32359. }
  32360. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  32361. intersectObject( objects[ i ], this, intersects, recursive );
  32362. }
  32363. intersects.sort( ascSort );
  32364. return intersects;
  32365. }
  32366. } );
  32367. /**
  32368. * @author bhouston / http://clara.io
  32369. * @author WestLangley / http://github.com/WestLangley
  32370. *
  32371. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  32372. *
  32373. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  32374. * The azimuthal angle (theta) is measured from the positive z-axiz.
  32375. */
  32376. function Spherical( radius, phi, theta ) {
  32377. this.radius = ( radius !== undefined ) ? radius : 1.0;
  32378. this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
  32379. this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
  32380. return this;
  32381. }
  32382. Object.assign( Spherical.prototype, {
  32383. set: function ( radius, phi, theta ) {
  32384. this.radius = radius;
  32385. this.phi = phi;
  32386. this.theta = theta;
  32387. return this;
  32388. },
  32389. clone: function () {
  32390. return new this.constructor().copy( this );
  32391. },
  32392. copy: function ( other ) {
  32393. this.radius = other.radius;
  32394. this.phi = other.phi;
  32395. this.theta = other.theta;
  32396. return this;
  32397. },
  32398. // restrict phi to be betwee EPS and PI-EPS
  32399. makeSafe: function () {
  32400. var EPS = 0.000001;
  32401. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  32402. return this;
  32403. },
  32404. setFromVector3: function ( v ) {
  32405. return this.setFromCartesianCoords( v.x, v.y, v.z );
  32406. },
  32407. setFromCartesianCoords: function ( x, y, z ) {
  32408. this.radius = Math.sqrt( x * x + y * y + z * z );
  32409. if ( this.radius === 0 ) {
  32410. this.theta = 0;
  32411. this.phi = 0;
  32412. } else {
  32413. this.theta = Math.atan2( x, z );
  32414. this.phi = Math.acos( _Math.clamp( y / this.radius, - 1, 1 ) );
  32415. }
  32416. return this;
  32417. }
  32418. } );
  32419. /**
  32420. * @author Mugen87 / https://github.com/Mugen87
  32421. *
  32422. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  32423. *
  32424. */
  32425. function Cylindrical( radius, theta, y ) {
  32426. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  32427. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  32428. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  32429. return this;
  32430. }
  32431. Object.assign( Cylindrical.prototype, {
  32432. set: function ( radius, theta, y ) {
  32433. this.radius = radius;
  32434. this.theta = theta;
  32435. this.y = y;
  32436. return this;
  32437. },
  32438. clone: function () {
  32439. return new this.constructor().copy( this );
  32440. },
  32441. copy: function ( other ) {
  32442. this.radius = other.radius;
  32443. this.theta = other.theta;
  32444. this.y = other.y;
  32445. return this;
  32446. },
  32447. setFromVector3: function ( v ) {
  32448. return this.setFromCartesianCoords( v.x, v.y, v.z );
  32449. },
  32450. setFromCartesianCoords: function ( x, y, z ) {
  32451. this.radius = Math.sqrt( x * x + z * z );
  32452. this.theta = Math.atan2( x, z );
  32453. this.y = y;
  32454. return this;
  32455. }
  32456. } );
  32457. /**
  32458. * @author bhouston / http://clara.io
  32459. */
  32460. var _vector$6 = new Vector2();
  32461. function Box2( min, max ) {
  32462. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  32463. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  32464. }
  32465. Object.assign( Box2.prototype, {
  32466. set: function ( min, max ) {
  32467. this.min.copy( min );
  32468. this.max.copy( max );
  32469. return this;
  32470. },
  32471. setFromPoints: function ( points ) {
  32472. this.makeEmpty();
  32473. for ( var i = 0, il = points.length; i < il; i ++ ) {
  32474. this.expandByPoint( points[ i ] );
  32475. }
  32476. return this;
  32477. },
  32478. setFromCenterAndSize: function ( center, size ) {
  32479. var halfSize = _vector$6.copy( size ).multiplyScalar( 0.5 );
  32480. this.min.copy( center ).sub( halfSize );
  32481. this.max.copy( center ).add( halfSize );
  32482. return this;
  32483. },
  32484. clone: function () {
  32485. return new this.constructor().copy( this );
  32486. },
  32487. copy: function ( box ) {
  32488. this.min.copy( box.min );
  32489. this.max.copy( box.max );
  32490. return this;
  32491. },
  32492. makeEmpty: function () {
  32493. this.min.x = this.min.y = + Infinity;
  32494. this.max.x = this.max.y = - Infinity;
  32495. return this;
  32496. },
  32497. isEmpty: function () {
  32498. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  32499. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  32500. },
  32501. getCenter: function ( target ) {
  32502. if ( target === undefined ) {
  32503. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  32504. target = new Vector2();
  32505. }
  32506. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  32507. },
  32508. getSize: function ( target ) {
  32509. if ( target === undefined ) {
  32510. console.warn( 'THREE.Box2: .getSize() target is now required' );
  32511. target = new Vector2();
  32512. }
  32513. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  32514. },
  32515. expandByPoint: function ( point ) {
  32516. this.min.min( point );
  32517. this.max.max( point );
  32518. return this;
  32519. },
  32520. expandByVector: function ( vector ) {
  32521. this.min.sub( vector );
  32522. this.max.add( vector );
  32523. return this;
  32524. },
  32525. expandByScalar: function ( scalar ) {
  32526. this.min.addScalar( - scalar );
  32527. this.max.addScalar( scalar );
  32528. return this;
  32529. },
  32530. containsPoint: function ( point ) {
  32531. return point.x < this.min.x || point.x > this.max.x ||
  32532. point.y < this.min.y || point.y > this.max.y ? false : true;
  32533. },
  32534. containsBox: function ( box ) {
  32535. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  32536. this.min.y <= box.min.y && box.max.y <= this.max.y;
  32537. },
  32538. getParameter: function ( point, target ) {
  32539. // This can potentially have a divide by zero if the box
  32540. // has a size dimension of 0.
  32541. if ( target === undefined ) {
  32542. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  32543. target = new Vector2();
  32544. }
  32545. return target.set(
  32546. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  32547. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  32548. );
  32549. },
  32550. intersectsBox: function ( box ) {
  32551. // using 4 splitting planes to rule out intersections
  32552. return box.max.x < this.min.x || box.min.x > this.max.x ||
  32553. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  32554. },
  32555. clampPoint: function ( point, target ) {
  32556. if ( target === undefined ) {
  32557. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  32558. target = new Vector2();
  32559. }
  32560. return target.copy( point ).clamp( this.min, this.max );
  32561. },
  32562. distanceToPoint: function ( point ) {
  32563. var clampedPoint = _vector$6.copy( point ).clamp( this.min, this.max );
  32564. return clampedPoint.sub( point ).length();
  32565. },
  32566. intersect: function ( box ) {
  32567. this.min.max( box.min );
  32568. this.max.min( box.max );
  32569. return this;
  32570. },
  32571. union: function ( box ) {
  32572. this.min.min( box.min );
  32573. this.max.max( box.max );
  32574. return this;
  32575. },
  32576. translate: function ( offset ) {
  32577. this.min.add( offset );
  32578. this.max.add( offset );
  32579. return this;
  32580. },
  32581. equals: function ( box ) {
  32582. return box.min.equals( this.min ) && box.max.equals( this.max );
  32583. }
  32584. } );
  32585. /**
  32586. * @author bhouston / http://clara.io
  32587. */
  32588. var _startP = new Vector3();
  32589. var _startEnd = new Vector3();
  32590. function Line3( start, end ) {
  32591. this.start = ( start !== undefined ) ? start : new Vector3();
  32592. this.end = ( end !== undefined ) ? end : new Vector3();
  32593. }
  32594. Object.assign( Line3.prototype, {
  32595. set: function ( start, end ) {
  32596. this.start.copy( start );
  32597. this.end.copy( end );
  32598. return this;
  32599. },
  32600. clone: function () {
  32601. return new this.constructor().copy( this );
  32602. },
  32603. copy: function ( line ) {
  32604. this.start.copy( line.start );
  32605. this.end.copy( line.end );
  32606. return this;
  32607. },
  32608. getCenter: function ( target ) {
  32609. if ( target === undefined ) {
  32610. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  32611. target = new Vector3();
  32612. }
  32613. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  32614. },
  32615. delta: function ( target ) {
  32616. if ( target === undefined ) {
  32617. console.warn( 'THREE.Line3: .delta() target is now required' );
  32618. target = new Vector3();
  32619. }
  32620. return target.subVectors( this.end, this.start );
  32621. },
  32622. distanceSq: function () {
  32623. return this.start.distanceToSquared( this.end );
  32624. },
  32625. distance: function () {
  32626. return this.start.distanceTo( this.end );
  32627. },
  32628. at: function ( t, target ) {
  32629. if ( target === undefined ) {
  32630. console.warn( 'THREE.Line3: .at() target is now required' );
  32631. target = new Vector3();
  32632. }
  32633. return this.delta( target ).multiplyScalar( t ).add( this.start );
  32634. },
  32635. closestPointToPointParameter: function ( point, clampToLine ) {
  32636. _startP.subVectors( point, this.start );
  32637. _startEnd.subVectors( this.end, this.start );
  32638. var startEnd2 = _startEnd.dot( _startEnd );
  32639. var startEnd_startP = _startEnd.dot( _startP );
  32640. var t = startEnd_startP / startEnd2;
  32641. if ( clampToLine ) {
  32642. t = _Math.clamp( t, 0, 1 );
  32643. }
  32644. return t;
  32645. },
  32646. closestPointToPoint: function ( point, clampToLine, target ) {
  32647. var t = this.closestPointToPointParameter( point, clampToLine );
  32648. if ( target === undefined ) {
  32649. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  32650. target = new Vector3();
  32651. }
  32652. return this.delta( target ).multiplyScalar( t ).add( this.start );
  32653. },
  32654. applyMatrix4: function ( matrix ) {
  32655. this.start.applyMatrix4( matrix );
  32656. this.end.applyMatrix4( matrix );
  32657. return this;
  32658. },
  32659. equals: function ( line ) {
  32660. return line.start.equals( this.start ) && line.end.equals( this.end );
  32661. }
  32662. } );
  32663. /**
  32664. * @author alteredq / http://alteredqualia.com/
  32665. */
  32666. function ImmediateRenderObject( material ) {
  32667. Object3D.call( this );
  32668. this.material = material;
  32669. this.render = function ( /* renderCallback */ ) {};
  32670. }
  32671. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  32672. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  32673. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  32674. /**
  32675. * @author mrdoob / http://mrdoob.com/
  32676. * @author WestLangley / http://github.com/WestLangley
  32677. */
  32678. var _v1$5 = new Vector3();
  32679. var _v2$3 = new Vector3();
  32680. var _normalMatrix$1 = new Matrix3();
  32681. var _keys = [ 'a', 'b', 'c' ];
  32682. function VertexNormalsHelper( object, size, hex, linewidth ) {
  32683. this.object = object;
  32684. this.size = ( size !== undefined ) ? size : 1;
  32685. var color = ( hex !== undefined ) ? hex : 0xff0000;
  32686. var width = ( linewidth !== undefined ) ? linewidth : 1;
  32687. //
  32688. var nNormals = 0;
  32689. var objGeometry = this.object.geometry;
  32690. if ( objGeometry && objGeometry.isGeometry ) {
  32691. nNormals = objGeometry.faces.length * 3;
  32692. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  32693. nNormals = objGeometry.attributes.normal.count;
  32694. }
  32695. //
  32696. var geometry = new BufferGeometry();
  32697. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  32698. geometry.addAttribute( 'position', positions );
  32699. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  32700. //
  32701. this.matrixAutoUpdate = false;
  32702. this.update();
  32703. }
  32704. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  32705. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  32706. VertexNormalsHelper.prototype.update = function () {
  32707. this.object.updateMatrixWorld( true );
  32708. _normalMatrix$1.getNormalMatrix( this.object.matrixWorld );
  32709. var matrixWorld = this.object.matrixWorld;
  32710. var position = this.geometry.attributes.position;
  32711. //
  32712. var objGeometry = this.object.geometry;
  32713. if ( objGeometry && objGeometry.isGeometry ) {
  32714. var vertices = objGeometry.vertices;
  32715. var faces = objGeometry.faces;
  32716. var idx = 0;
  32717. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  32718. var face = faces[ i ];
  32719. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  32720. var vertex = vertices[ face[ _keys[ j ] ] ];
  32721. var normal = face.vertexNormals[ j ];
  32722. _v1$5.copy( vertex ).applyMatrix4( matrixWorld );
  32723. _v2$3.copy( normal ).applyMatrix3( _normalMatrix$1 ).normalize().multiplyScalar( this.size ).add( _v1$5 );
  32724. position.setXYZ( idx, _v1$5.x, _v1$5.y, _v1$5.z );
  32725. idx = idx + 1;
  32726. position.setXYZ( idx, _v2$3.x, _v2$3.y, _v2$3.z );
  32727. idx = idx + 1;
  32728. }
  32729. }
  32730. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  32731. var objPos = objGeometry.attributes.position;
  32732. var objNorm = objGeometry.attributes.normal;
  32733. var idx = 0;
  32734. // for simplicity, ignore index and drawcalls, and render every normal
  32735. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  32736. _v1$5.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  32737. _v2$3.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  32738. _v2$3.applyMatrix3( _normalMatrix$1 ).normalize().multiplyScalar( this.size ).add( _v1$5 );
  32739. position.setXYZ( idx, _v1$5.x, _v1$5.y, _v1$5.z );
  32740. idx = idx + 1;
  32741. position.setXYZ( idx, _v2$3.x, _v2$3.y, _v2$3.z );
  32742. idx = idx + 1;
  32743. }
  32744. }
  32745. position.needsUpdate = true;
  32746. };
  32747. /**
  32748. * @author alteredq / http://alteredqualia.com/
  32749. * @author mrdoob / http://mrdoob.com/
  32750. * @author WestLangley / http://github.com/WestLangley
  32751. */
  32752. var _vector$7 = new Vector3();
  32753. function SpotLightHelper( light, color ) {
  32754. Object3D.call( this );
  32755. this.light = light;
  32756. this.light.updateMatrixWorld();
  32757. this.matrix = light.matrixWorld;
  32758. this.matrixAutoUpdate = false;
  32759. this.color = color;
  32760. var geometry = new BufferGeometry();
  32761. var positions = [
  32762. 0, 0, 0, 0, 0, 1,
  32763. 0, 0, 0, 1, 0, 1,
  32764. 0, 0, 0, - 1, 0, 1,
  32765. 0, 0, 0, 0, 1, 1,
  32766. 0, 0, 0, 0, - 1, 1
  32767. ];
  32768. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  32769. var p1 = ( i / l ) * Math.PI * 2;
  32770. var p2 = ( j / l ) * Math.PI * 2;
  32771. positions.push(
  32772. Math.cos( p1 ), Math.sin( p1 ), 1,
  32773. Math.cos( p2 ), Math.sin( p2 ), 1
  32774. );
  32775. }
  32776. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32777. var material = new LineBasicMaterial( { fog: false } );
  32778. this.cone = new LineSegments( geometry, material );
  32779. this.add( this.cone );
  32780. this.update();
  32781. }
  32782. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  32783. SpotLightHelper.prototype.constructor = SpotLightHelper;
  32784. SpotLightHelper.prototype.dispose = function () {
  32785. this.cone.geometry.dispose();
  32786. this.cone.material.dispose();
  32787. };
  32788. SpotLightHelper.prototype.update = function () {
  32789. this.light.updateMatrixWorld();
  32790. var coneLength = this.light.distance ? this.light.distance : 1000;
  32791. var coneWidth = coneLength * Math.tan( this.light.angle );
  32792. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  32793. _vector$7.setFromMatrixPosition( this.light.target.matrixWorld );
  32794. this.cone.lookAt( _vector$7 );
  32795. if ( this.color !== undefined ) {
  32796. this.cone.material.color.set( this.color );
  32797. } else {
  32798. this.cone.material.color.copy( this.light.color );
  32799. }
  32800. };
  32801. /**
  32802. * @author Sean Griffin / http://twitter.com/sgrif
  32803. * @author Michael Guerrero / http://realitymeltdown.com
  32804. * @author mrdoob / http://mrdoob.com/
  32805. * @author ikerr / http://verold.com
  32806. * @author Mugen87 / https://github.com/Mugen87
  32807. */
  32808. var _vector$8 = new Vector3();
  32809. var _boneMatrix = new Matrix4();
  32810. var _matrixWorldInv = new Matrix4();
  32811. function getBoneList( object ) {
  32812. var boneList = [];
  32813. if ( object && object.isBone ) {
  32814. boneList.push( object );
  32815. }
  32816. for ( var i = 0; i < object.children.length; i ++ ) {
  32817. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  32818. }
  32819. return boneList;
  32820. }
  32821. function SkeletonHelper( object ) {
  32822. var bones = getBoneList( object );
  32823. var geometry = new BufferGeometry();
  32824. var vertices = [];
  32825. var colors = [];
  32826. var color1 = new Color( 0, 0, 1 );
  32827. var color2 = new Color( 0, 1, 0 );
  32828. for ( var i = 0; i < bones.length; i ++ ) {
  32829. var bone = bones[ i ];
  32830. if ( bone.parent && bone.parent.isBone ) {
  32831. vertices.push( 0, 0, 0 );
  32832. vertices.push( 0, 0, 0 );
  32833. colors.push( color1.r, color1.g, color1.b );
  32834. colors.push( color2.r, color2.g, color2.b );
  32835. }
  32836. }
  32837. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32838. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32839. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  32840. LineSegments.call( this, geometry, material );
  32841. this.root = object;
  32842. this.bones = bones;
  32843. this.matrix = object.matrixWorld;
  32844. this.matrixAutoUpdate = false;
  32845. }
  32846. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  32847. SkeletonHelper.prototype.constructor = SkeletonHelper;
  32848. SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {
  32849. var bones = this.bones;
  32850. var geometry = this.geometry;
  32851. var position = geometry.getAttribute( 'position' );
  32852. _matrixWorldInv.getInverse( this.root.matrixWorld );
  32853. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  32854. var bone = bones[ i ];
  32855. if ( bone.parent && bone.parent.isBone ) {
  32856. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  32857. _vector$8.setFromMatrixPosition( _boneMatrix );
  32858. position.setXYZ( j, _vector$8.x, _vector$8.y, _vector$8.z );
  32859. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  32860. _vector$8.setFromMatrixPosition( _boneMatrix );
  32861. position.setXYZ( j + 1, _vector$8.x, _vector$8.y, _vector$8.z );
  32862. j += 2;
  32863. }
  32864. }
  32865. geometry.getAttribute( 'position' ).needsUpdate = true;
  32866. Object3D.prototype.updateMatrixWorld.call( this, force );
  32867. };
  32868. /**
  32869. * @author alteredq / http://alteredqualia.com/
  32870. * @author mrdoob / http://mrdoob.com/
  32871. */
  32872. function PointLightHelper( light, sphereSize, color ) {
  32873. this.light = light;
  32874. this.light.updateMatrixWorld();
  32875. this.color = color;
  32876. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  32877. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  32878. Mesh.call( this, geometry, material );
  32879. this.matrix = this.light.matrixWorld;
  32880. this.matrixAutoUpdate = false;
  32881. this.update();
  32882. /*
  32883. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  32884. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  32885. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  32886. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  32887. var d = light.distance;
  32888. if ( d === 0.0 ) {
  32889. this.lightDistance.visible = false;
  32890. } else {
  32891. this.lightDistance.scale.set( d, d, d );
  32892. }
  32893. this.add( this.lightDistance );
  32894. */
  32895. }
  32896. PointLightHelper.prototype = Object.create( Mesh.prototype );
  32897. PointLightHelper.prototype.constructor = PointLightHelper;
  32898. PointLightHelper.prototype.dispose = function () {
  32899. this.geometry.dispose();
  32900. this.material.dispose();
  32901. };
  32902. PointLightHelper.prototype.update = function () {
  32903. if ( this.color !== undefined ) {
  32904. this.material.color.set( this.color );
  32905. } else {
  32906. this.material.color.copy( this.light.color );
  32907. }
  32908. /*
  32909. var d = this.light.distance;
  32910. if ( d === 0.0 ) {
  32911. this.lightDistance.visible = false;
  32912. } else {
  32913. this.lightDistance.visible = true;
  32914. this.lightDistance.scale.set( d, d, d );
  32915. }
  32916. */
  32917. };
  32918. /**
  32919. * @author abelnation / http://github.com/abelnation
  32920. * @author Mugen87 / http://github.com/Mugen87
  32921. * @author WestLangley / http://github.com/WestLangley
  32922. *
  32923. * This helper must be added as a child of the light
  32924. */
  32925. function RectAreaLightHelper( light, color ) {
  32926. this.type = 'RectAreaLightHelper';
  32927. this.light = light;
  32928. this.color = color; // optional hardwired color for the helper
  32929. var positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  32930. var geometry = new BufferGeometry();
  32931. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32932. geometry.computeBoundingSphere();
  32933. var material = new LineBasicMaterial( { fog: false } );
  32934. Line.call( this, geometry, material );
  32935. //
  32936. var positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  32937. var geometry2 = new BufferGeometry();
  32938. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  32939. geometry2.computeBoundingSphere();
  32940. this.add( new Mesh( geometry2, new MeshBasicMaterial( { side: BackSide, fog: false } ) ) );
  32941. this.update();
  32942. }
  32943. RectAreaLightHelper.prototype = Object.create( Line.prototype );
  32944. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  32945. RectAreaLightHelper.prototype.update = function () {
  32946. this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 );
  32947. if ( this.color !== undefined ) {
  32948. this.material.color.set( this.color );
  32949. this.children[ 0 ].material.color.set( this.color );
  32950. } else {
  32951. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  32952. // prevent hue shift
  32953. var c = this.material.color;
  32954. var max = Math.max( c.r, c.g, c.b );
  32955. if ( max > 1 ) { c.multiplyScalar( 1 / max ); }
  32956. this.children[ 0 ].material.color.copy( this.material.color );
  32957. }
  32958. };
  32959. RectAreaLightHelper.prototype.dispose = function () {
  32960. this.geometry.dispose();
  32961. this.material.dispose();
  32962. this.children[ 0 ].geometry.dispose();
  32963. this.children[ 0 ].material.dispose();
  32964. };
  32965. /**
  32966. * @author alteredq / http://alteredqualia.com/
  32967. * @author mrdoob / http://mrdoob.com/
  32968. * @author Mugen87 / https://github.com/Mugen87
  32969. */
  32970. var _vector$9 = new Vector3();
  32971. var _color1 = new Color();
  32972. var _color2 = new Color();
  32973. function HemisphereLightHelper( light, size, color ) {
  32974. Object3D.call( this );
  32975. this.light = light;
  32976. this.light.updateMatrixWorld();
  32977. this.matrix = light.matrixWorld;
  32978. this.matrixAutoUpdate = false;
  32979. this.color = color;
  32980. var geometry = new OctahedronBufferGeometry( size );
  32981. geometry.rotateY( Math.PI * 0.5 );
  32982. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  32983. if ( this.color === undefined ) { this.material.vertexColors = VertexColors; }
  32984. var position = geometry.getAttribute( 'position' );
  32985. var colors = new Float32Array( position.count * 3 );
  32986. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  32987. this.add( new Mesh( geometry, this.material ) );
  32988. this.update();
  32989. }
  32990. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  32991. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  32992. HemisphereLightHelper.prototype.dispose = function () {
  32993. this.children[ 0 ].geometry.dispose();
  32994. this.children[ 0 ].material.dispose();
  32995. };
  32996. HemisphereLightHelper.prototype.update = function () {
  32997. var mesh = this.children[ 0 ];
  32998. if ( this.color !== undefined ) {
  32999. this.material.color.set( this.color );
  33000. } else {
  33001. var colors = mesh.geometry.getAttribute( 'color' );
  33002. _color1.copy( this.light.color );
  33003. _color2.copy( this.light.groundColor );
  33004. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  33005. var color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  33006. colors.setXYZ( i, color.r, color.g, color.b );
  33007. }
  33008. colors.needsUpdate = true;
  33009. }
  33010. mesh.lookAt( _vector$9.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  33011. };
  33012. /**
  33013. * @author WestLangley / http://github.com/WestLangley
  33014. */
  33015. function LightProbeHelper( lightProbe, size ) {
  33016. this.lightProbe = lightProbe;
  33017. this.size = size;
  33018. var defines = {};
  33019. defines[ 'GAMMA_OUTPUT' ] = "";
  33020. // material
  33021. var material = new ShaderMaterial( {
  33022. defines: defines,
  33023. uniforms: {
  33024. sh: { value: this.lightProbe.sh.coefficients }, // by reference
  33025. intensity: { value: this.lightProbe.intensity }
  33026. },
  33027. vertexShader: [
  33028. 'varying vec3 vNormal;',
  33029. 'void main() {',
  33030. ' vNormal = normalize( normalMatrix * normal );',
  33031. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  33032. '}' ].join( '\n' ),
  33033. fragmentShader: [
  33034. '#define RECIPROCAL_PI 0.318309886',
  33035. 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {',
  33036. ' // matrix is assumed to be orthogonal',
  33037. ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );',
  33038. '}',
  33039. 'vec3 linearToOutput( in vec3 a ) {',
  33040. ' #ifdef GAMMA_OUTPUT',
  33041. ' return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );',
  33042. ' #else',
  33043. ' return a;',
  33044. ' #endif',
  33045. '}',
  33046. '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf',
  33047. 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {',
  33048. ' // normal is assumed to have unit length',
  33049. ' float x = normal.x, y = normal.y, z = normal.z;',
  33050. ' // band 0',
  33051. ' vec3 result = shCoefficients[ 0 ] * 0.886227;',
  33052. ' // band 1',
  33053. ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;',
  33054. ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;',
  33055. ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;',
  33056. ' // band 2',
  33057. ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;',
  33058. ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;',
  33059. ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );',
  33060. ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;',
  33061. ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );',
  33062. ' return result;',
  33063. '}',
  33064. 'uniform vec3 sh[ 9 ]; // sh coefficients',
  33065. 'uniform float intensity; // light probe intensity',
  33066. 'varying vec3 vNormal;',
  33067. 'void main() {',
  33068. ' vec3 normal = normalize( vNormal );',
  33069. ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );',
  33070. ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );',
  33071. ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;',
  33072. ' outgoingLight = linearToOutput( outgoingLight );',
  33073. ' gl_FragColor = vec4( outgoingLight, 1.0 );',
  33074. '}'
  33075. ].join( '\n' )
  33076. } );
  33077. var geometry = new SphereBufferGeometry( 1, 32, 16 );
  33078. Mesh.call( this, geometry, material );
  33079. this.onBeforeRender();
  33080. }
  33081. LightProbeHelper.prototype = Object.create( Mesh.prototype );
  33082. LightProbeHelper.prototype.constructor = LightProbeHelper;
  33083. LightProbeHelper.prototype.dispose = function () {
  33084. this.geometry.dispose();
  33085. this.material.dispose();
  33086. };
  33087. LightProbeHelper.prototype.onBeforeRender = function () {
  33088. this.position.copy( this.lightProbe.position );
  33089. this.scale.set( 1, 1, 1 ).multiplyScalar( this.size );
  33090. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  33091. };
  33092. /**
  33093. * @author mrdoob / http://mrdoob.com/
  33094. */
  33095. function GridHelper( size, divisions, color1, color2 ) {
  33096. size = size || 10;
  33097. divisions = divisions || 10;
  33098. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33099. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33100. var center = divisions / 2;
  33101. var step = size / divisions;
  33102. var halfSize = size / 2;
  33103. var vertices = [], colors = [];
  33104. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  33105. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  33106. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  33107. var color = i === center ? color1 : color2;
  33108. color.toArray( colors, j ); j += 3;
  33109. color.toArray( colors, j ); j += 3;
  33110. color.toArray( colors, j ); j += 3;
  33111. color.toArray( colors, j ); j += 3;
  33112. }
  33113. var geometry = new BufferGeometry();
  33114. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33115. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33116. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  33117. LineSegments.call( this, geometry, material );
  33118. }
  33119. GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), {
  33120. constructor: GridHelper,
  33121. copy: function ( source ) {
  33122. LineSegments.prototype.copy.call( this, source );
  33123. this.geometry.copy( source.geometry );
  33124. this.material.copy( source.material );
  33125. return this;
  33126. },
  33127. clone: function () {
  33128. return new this.constructor().copy( this );
  33129. }
  33130. } );
  33131. /**
  33132. * @author mrdoob / http://mrdoob.com/
  33133. * @author Mugen87 / http://github.com/Mugen87
  33134. * @author Hectate / http://www.github.com/Hectate
  33135. */
  33136. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  33137. radius = radius || 10;
  33138. radials = radials || 16;
  33139. circles = circles || 8;
  33140. divisions = divisions || 64;
  33141. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33142. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33143. var vertices = [];
  33144. var colors = [];
  33145. var x, z;
  33146. var v, i, j, r, color;
  33147. // create the radials
  33148. for ( i = 0; i <= radials; i ++ ) {
  33149. v = ( i / radials ) * ( Math.PI * 2 );
  33150. x = Math.sin( v ) * radius;
  33151. z = Math.cos( v ) * radius;
  33152. vertices.push( 0, 0, 0 );
  33153. vertices.push( x, 0, z );
  33154. color = ( i & 1 ) ? color1 : color2;
  33155. colors.push( color.r, color.g, color.b );
  33156. colors.push( color.r, color.g, color.b );
  33157. }
  33158. // create the circles
  33159. for ( i = 0; i <= circles; i ++ ) {
  33160. color = ( i & 1 ) ? color1 : color2;
  33161. r = radius - ( radius / circles * i );
  33162. for ( j = 0; j < divisions; j ++ ) {
  33163. // first vertex
  33164. v = ( j / divisions ) * ( Math.PI * 2 );
  33165. x = Math.sin( v ) * r;
  33166. z = Math.cos( v ) * r;
  33167. vertices.push( x, 0, z );
  33168. colors.push( color.r, color.g, color.b );
  33169. // second vertex
  33170. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  33171. x = Math.sin( v ) * r;
  33172. z = Math.cos( v ) * r;
  33173. vertices.push( x, 0, z );
  33174. colors.push( color.r, color.g, color.b );
  33175. }
  33176. }
  33177. var geometry = new BufferGeometry();
  33178. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33179. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33180. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  33181. LineSegments.call( this, geometry, material );
  33182. }
  33183. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  33184. PolarGridHelper.prototype.constructor = PolarGridHelper;
  33185. /**
  33186. * @author Mugen87 / http://github.com/Mugen87
  33187. */
  33188. function PositionalAudioHelper( audio, range, divisionsInnerAngle, divisionsOuterAngle ) {
  33189. this.audio = audio;
  33190. this.range = range || 1;
  33191. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  33192. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  33193. var geometry = new BufferGeometry();
  33194. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  33195. var positions = new Float32Array( ( divisions * 3 + 3 ) * 3 );
  33196. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  33197. var materialInnerAngle = new LineBasicMaterial( { color: 0x00ff00 } );
  33198. var materialOuterAngle = new LineBasicMaterial( { color: 0xffff00 } );
  33199. Line.call( this, geometry, [ materialOuterAngle, materialInnerAngle ] );
  33200. this.update();
  33201. }
  33202. PositionalAudioHelper.prototype = Object.create( Line.prototype );
  33203. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  33204. PositionalAudioHelper.prototype.update = function () {
  33205. var audio = this.audio;
  33206. var range = this.range;
  33207. var divisionsInnerAngle = this.divisionsInnerAngle;
  33208. var divisionsOuterAngle = this.divisionsOuterAngle;
  33209. var coneInnerAngle = _Math.degToRad( audio.panner.coneInnerAngle );
  33210. var coneOuterAngle = _Math.degToRad( audio.panner.coneOuterAngle );
  33211. var halfConeInnerAngle = coneInnerAngle / 2;
  33212. var halfConeOuterAngle = coneOuterAngle / 2;
  33213. var start = 0;
  33214. var count = 0;
  33215. var i, stride;
  33216. var geometry = this.geometry;
  33217. var positionAttribute = geometry.attributes.position;
  33218. geometry.clearGroups();
  33219. //
  33220. function generateSegment( from, to, divisions, materialIndex ) {
  33221. var step = ( to - from ) / divisions;
  33222. positionAttribute.setXYZ( start, 0, 0, 0 );
  33223. count ++;
  33224. for ( i = from; i < to; i += step ) {
  33225. stride = start + count;
  33226. positionAttribute.setXYZ( stride, Math.sin( i ) * range, 0, Math.cos( i ) * range );
  33227. positionAttribute.setXYZ( stride + 1, Math.sin( Math.min( i + step, to ) ) * range, 0, Math.cos( Math.min( i + step, to ) ) * range );
  33228. positionAttribute.setXYZ( stride + 2, 0, 0, 0 );
  33229. count += 3;
  33230. }
  33231. geometry.addGroup( start, count, materialIndex );
  33232. start += count;
  33233. count = 0;
  33234. }
  33235. //
  33236. generateSegment( - halfConeOuterAngle, - halfConeInnerAngle, divisionsOuterAngle, 0 );
  33237. generateSegment( - halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1 );
  33238. generateSegment( halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0 );
  33239. //
  33240. positionAttribute.needsUpdate = true;
  33241. if ( coneInnerAngle === coneOuterAngle ) { this.material[ 0 ].visible = false; }
  33242. };
  33243. PositionalAudioHelper.prototype.dispose = function () {
  33244. this.geometry.dispose();
  33245. this.material[ 0 ].dispose();
  33246. this.material[ 1 ].dispose();
  33247. };
  33248. /**
  33249. * @author mrdoob / http://mrdoob.com/
  33250. * @author WestLangley / http://github.com/WestLangley
  33251. */
  33252. var _v1$6 = new Vector3();
  33253. var _v2$4 = new Vector3();
  33254. var _normalMatrix$2 = new Matrix3();
  33255. function FaceNormalsHelper( object, size, hex, linewidth ) {
  33256. // FaceNormalsHelper only supports THREE.Geometry
  33257. this.object = object;
  33258. this.size = ( size !== undefined ) ? size : 1;
  33259. var color = ( hex !== undefined ) ? hex : 0xffff00;
  33260. var width = ( linewidth !== undefined ) ? linewidth : 1;
  33261. //
  33262. var nNormals = 0;
  33263. var objGeometry = this.object.geometry;
  33264. if ( objGeometry && objGeometry.isGeometry ) {
  33265. nNormals = objGeometry.faces.length;
  33266. } else {
  33267. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  33268. }
  33269. //
  33270. var geometry = new BufferGeometry();
  33271. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  33272. geometry.addAttribute( 'position', positions );
  33273. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  33274. //
  33275. this.matrixAutoUpdate = false;
  33276. this.update();
  33277. }
  33278. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  33279. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  33280. FaceNormalsHelper.prototype.update = function () {
  33281. this.object.updateMatrixWorld( true );
  33282. _normalMatrix$2.getNormalMatrix( this.object.matrixWorld );
  33283. var matrixWorld = this.object.matrixWorld;
  33284. var position = this.geometry.attributes.position;
  33285. //
  33286. var objGeometry = this.object.geometry;
  33287. var vertices = objGeometry.vertices;
  33288. var faces = objGeometry.faces;
  33289. var idx = 0;
  33290. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  33291. var face = faces[ i ];
  33292. var normal = face.normal;
  33293. _v1$6.copy( vertices[ face.a ] )
  33294. .add( vertices[ face.b ] )
  33295. .add( vertices[ face.c ] )
  33296. .divideScalar( 3 )
  33297. .applyMatrix4( matrixWorld );
  33298. _v2$4.copy( normal ).applyMatrix3( _normalMatrix$2 ).normalize().multiplyScalar( this.size ).add( _v1$6 );
  33299. position.setXYZ( idx, _v1$6.x, _v1$6.y, _v1$6.z );
  33300. idx = idx + 1;
  33301. position.setXYZ( idx, _v2$4.x, _v2$4.y, _v2$4.z );
  33302. idx = idx + 1;
  33303. }
  33304. position.needsUpdate = true;
  33305. };
  33306. /**
  33307. * @author alteredq / http://alteredqualia.com/
  33308. * @author mrdoob / http://mrdoob.com/
  33309. * @author WestLangley / http://github.com/WestLangley
  33310. */
  33311. var _v1$7 = new Vector3();
  33312. var _v2$5 = new Vector3();
  33313. var _v3$1 = new Vector3();
  33314. function DirectionalLightHelper( light, size, color ) {
  33315. Object3D.call( this );
  33316. this.light = light;
  33317. this.light.updateMatrixWorld();
  33318. this.matrix = light.matrixWorld;
  33319. this.matrixAutoUpdate = false;
  33320. this.color = color;
  33321. if ( size === undefined ) { size = 1; }
  33322. var geometry = new BufferGeometry();
  33323. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  33324. - size, size, 0,
  33325. size, size, 0,
  33326. size, - size, 0,
  33327. - size, - size, 0,
  33328. - size, size, 0
  33329. ], 3 ) );
  33330. var material = new LineBasicMaterial( { fog: false } );
  33331. this.lightPlane = new Line( geometry, material );
  33332. this.add( this.lightPlane );
  33333. geometry = new BufferGeometry();
  33334. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  33335. this.targetLine = new Line( geometry, material );
  33336. this.add( this.targetLine );
  33337. this.update();
  33338. }
  33339. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  33340. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  33341. DirectionalLightHelper.prototype.dispose = function () {
  33342. this.lightPlane.geometry.dispose();
  33343. this.lightPlane.material.dispose();
  33344. this.targetLine.geometry.dispose();
  33345. this.targetLine.material.dispose();
  33346. };
  33347. DirectionalLightHelper.prototype.update = function () {
  33348. _v1$7.setFromMatrixPosition( this.light.matrixWorld );
  33349. _v2$5.setFromMatrixPosition( this.light.target.matrixWorld );
  33350. _v3$1.subVectors( _v2$5, _v1$7 );
  33351. this.lightPlane.lookAt( _v2$5 );
  33352. if ( this.color !== undefined ) {
  33353. this.lightPlane.material.color.set( this.color );
  33354. this.targetLine.material.color.set( this.color );
  33355. } else {
  33356. this.lightPlane.material.color.copy( this.light.color );
  33357. this.targetLine.material.color.copy( this.light.color );
  33358. }
  33359. this.targetLine.lookAt( _v2$5 );
  33360. this.targetLine.scale.z = _v3$1.length();
  33361. };
  33362. /**
  33363. * @author alteredq / http://alteredqualia.com/
  33364. * @author Mugen87 / https://github.com/Mugen87
  33365. *
  33366. * - shows frustum, line of sight and up of the camera
  33367. * - suitable for fast updates
  33368. * - based on frustum visualization in lightgl.js shadowmap example
  33369. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33370. */
  33371. var _vector$a = new Vector3();
  33372. var _camera = new Camera();
  33373. function CameraHelper( camera ) {
  33374. var geometry = new BufferGeometry();
  33375. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  33376. var vertices = [];
  33377. var colors = [];
  33378. var pointMap = {};
  33379. // colors
  33380. var colorFrustum = new Color( 0xffaa00 );
  33381. var colorCone = new Color( 0xff0000 );
  33382. var colorUp = new Color( 0x00aaff );
  33383. var colorTarget = new Color( 0xffffff );
  33384. var colorCross = new Color( 0x333333 );
  33385. // near
  33386. addLine( 'n1', 'n2', colorFrustum );
  33387. addLine( 'n2', 'n4', colorFrustum );
  33388. addLine( 'n4', 'n3', colorFrustum );
  33389. addLine( 'n3', 'n1', colorFrustum );
  33390. // far
  33391. addLine( 'f1', 'f2', colorFrustum );
  33392. addLine( 'f2', 'f4', colorFrustum );
  33393. addLine( 'f4', 'f3', colorFrustum );
  33394. addLine( 'f3', 'f1', colorFrustum );
  33395. // sides
  33396. addLine( 'n1', 'f1', colorFrustum );
  33397. addLine( 'n2', 'f2', colorFrustum );
  33398. addLine( 'n3', 'f3', colorFrustum );
  33399. addLine( 'n4', 'f4', colorFrustum );
  33400. // cone
  33401. addLine( 'p', 'n1', colorCone );
  33402. addLine( 'p', 'n2', colorCone );
  33403. addLine( 'p', 'n3', colorCone );
  33404. addLine( 'p', 'n4', colorCone );
  33405. // up
  33406. addLine( 'u1', 'u2', colorUp );
  33407. addLine( 'u2', 'u3', colorUp );
  33408. addLine( 'u3', 'u1', colorUp );
  33409. // target
  33410. addLine( 'c', 't', colorTarget );
  33411. addLine( 'p', 'c', colorCross );
  33412. // cross
  33413. addLine( 'cn1', 'cn2', colorCross );
  33414. addLine( 'cn3', 'cn4', colorCross );
  33415. addLine( 'cf1', 'cf2', colorCross );
  33416. addLine( 'cf3', 'cf4', colorCross );
  33417. function addLine( a, b, color ) {
  33418. addPoint( a, color );
  33419. addPoint( b, color );
  33420. }
  33421. function addPoint( id, color ) {
  33422. vertices.push( 0, 0, 0 );
  33423. colors.push( color.r, color.g, color.b );
  33424. if ( pointMap[ id ] === undefined ) {
  33425. pointMap[ id ] = [];
  33426. }
  33427. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  33428. }
  33429. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33430. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33431. LineSegments.call( this, geometry, material );
  33432. this.camera = camera;
  33433. if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); }
  33434. this.matrix = camera.matrixWorld;
  33435. this.matrixAutoUpdate = false;
  33436. this.pointMap = pointMap;
  33437. this.update();
  33438. }
  33439. CameraHelper.prototype = Object.create( LineSegments.prototype );
  33440. CameraHelper.prototype.constructor = CameraHelper;
  33441. CameraHelper.prototype.update = function () {
  33442. var geometry = this.geometry;
  33443. var pointMap = this.pointMap;
  33444. var w = 1, h = 1;
  33445. // we need just camera projection matrix inverse
  33446. // world matrix must be identity
  33447. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  33448. // center / target
  33449. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  33450. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  33451. // near
  33452. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  33453. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  33454. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  33455. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  33456. // far
  33457. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  33458. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  33459. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  33460. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  33461. // up
  33462. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  33463. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  33464. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  33465. // cross
  33466. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  33467. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  33468. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  33469. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  33470. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  33471. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  33472. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  33473. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  33474. geometry.getAttribute( 'position' ).needsUpdate = true;
  33475. };
  33476. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  33477. _vector$a.set( x, y, z ).unproject( camera );
  33478. var points = pointMap[ point ];
  33479. if ( points !== undefined ) {
  33480. var position = geometry.getAttribute( 'position' );
  33481. for ( var i = 0, l = points.length; i < l; i ++ ) {
  33482. position.setXYZ( points[ i ], _vector$a.x, _vector$a.y, _vector$a.z );
  33483. }
  33484. }
  33485. }
  33486. /**
  33487. * @author mrdoob / http://mrdoob.com/
  33488. * @author Mugen87 / http://github.com/Mugen87
  33489. */
  33490. var _box$2 = new Box3();
  33491. function BoxHelper( object, color ) {
  33492. this.object = object;
  33493. if ( color === undefined ) { color = 0xffff00; }
  33494. 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 ] );
  33495. var positions = new Float32Array( 8 * 3 );
  33496. var geometry = new BufferGeometry();
  33497. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  33498. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  33499. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  33500. this.matrixAutoUpdate = false;
  33501. this.update();
  33502. }
  33503. BoxHelper.prototype = Object.create( LineSegments.prototype );
  33504. BoxHelper.prototype.constructor = BoxHelper;
  33505. BoxHelper.prototype.update = function ( object ) {
  33506. if ( object !== undefined ) {
  33507. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  33508. }
  33509. if ( this.object !== undefined ) {
  33510. _box$2.setFromObject( this.object );
  33511. }
  33512. if ( _box$2.isEmpty() ) { return; }
  33513. var min = _box$2.min;
  33514. var max = _box$2.max;
  33515. /*
  33516. 5____4
  33517. 1/___0/|
  33518. | 6__|_7
  33519. 2/___3/
  33520. 0: max.x, max.y, max.z
  33521. 1: min.x, max.y, max.z
  33522. 2: min.x, min.y, max.z
  33523. 3: max.x, min.y, max.z
  33524. 4: max.x, max.y, min.z
  33525. 5: min.x, max.y, min.z
  33526. 6: min.x, min.y, min.z
  33527. 7: max.x, min.y, min.z
  33528. */
  33529. var position = this.geometry.attributes.position;
  33530. var array = position.array;
  33531. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  33532. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  33533. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  33534. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  33535. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  33536. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  33537. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  33538. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  33539. position.needsUpdate = true;
  33540. this.geometry.computeBoundingSphere();
  33541. };
  33542. BoxHelper.prototype.setFromObject = function ( object ) {
  33543. this.object = object;
  33544. this.update();
  33545. return this;
  33546. };
  33547. BoxHelper.prototype.copy = function ( source ) {
  33548. LineSegments.prototype.copy.call( this, source );
  33549. this.object = source.object;
  33550. return this;
  33551. };
  33552. BoxHelper.prototype.clone = function () {
  33553. return new this.constructor().copy( this );
  33554. };
  33555. /**
  33556. * @author WestLangley / http://github.com/WestLangley
  33557. */
  33558. function Box3Helper( box, color ) {
  33559. this.type = 'Box3Helper';
  33560. this.box = box;
  33561. color = color || 0xffff00;
  33562. 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 ] );
  33563. 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 ];
  33564. var geometry = new BufferGeometry();
  33565. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  33566. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  33567. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  33568. this.geometry.computeBoundingSphere();
  33569. }
  33570. Box3Helper.prototype = Object.create( LineSegments.prototype );
  33571. Box3Helper.prototype.constructor = Box3Helper;
  33572. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  33573. var box = this.box;
  33574. if ( box.isEmpty() ) { return; }
  33575. box.getCenter( this.position );
  33576. box.getSize( this.scale );
  33577. this.scale.multiplyScalar( 0.5 );
  33578. Object3D.prototype.updateMatrixWorld.call( this, force );
  33579. };
  33580. /**
  33581. * @author WestLangley / http://github.com/WestLangley
  33582. */
  33583. function PlaneHelper( plane, size, hex ) {
  33584. this.type = 'PlaneHelper';
  33585. this.plane = plane;
  33586. this.size = ( size === undefined ) ? 1 : size;
  33587. var color = ( hex !== undefined ) ? hex : 0xffff00;
  33588. 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 ];
  33589. var geometry = new BufferGeometry();
  33590. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  33591. geometry.computeBoundingSphere();
  33592. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  33593. //
  33594. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  33595. var geometry2 = new BufferGeometry();
  33596. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  33597. geometry2.computeBoundingSphere();
  33598. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  33599. }
  33600. PlaneHelper.prototype = Object.create( Line.prototype );
  33601. PlaneHelper.prototype.constructor = PlaneHelper;
  33602. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  33603. var scale = - this.plane.constant;
  33604. if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter
  33605. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  33606. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  33607. this.lookAt( this.plane.normal );
  33608. Object3D.prototype.updateMatrixWorld.call( this, force );
  33609. };
  33610. /**
  33611. * @author WestLangley / http://github.com/WestLangley
  33612. * @author zz85 / http://github.com/zz85
  33613. * @author bhouston / http://clara.io
  33614. *
  33615. * Creates an arrow for visualizing directions
  33616. *
  33617. * Parameters:
  33618. * dir - Vector3
  33619. * origin - Vector3
  33620. * length - Number
  33621. * color - color in hex value
  33622. * headLength - Number
  33623. * headWidth - Number
  33624. */
  33625. var _axis = new Vector3();
  33626. var _lineGeometry, _coneGeometry;
  33627. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  33628. // dir is assumed to be normalized
  33629. Object3D.call( this );
  33630. if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); }
  33631. if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); }
  33632. if ( length === undefined ) { length = 1; }
  33633. if ( color === undefined ) { color = 0xffff00; }
  33634. if ( headLength === undefined ) { headLength = 0.2 * length; }
  33635. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  33636. if ( _lineGeometry === undefined ) {
  33637. _lineGeometry = new BufferGeometry();
  33638. _lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  33639. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  33640. _coneGeometry.translate( 0, - 0.5, 0 );
  33641. }
  33642. this.position.copy( origin );
  33643. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color } ) );
  33644. this.line.matrixAutoUpdate = false;
  33645. this.add( this.line );
  33646. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color } ) );
  33647. this.cone.matrixAutoUpdate = false;
  33648. this.add( this.cone );
  33649. this.setDirection( dir );
  33650. this.setLength( length, headLength, headWidth );
  33651. }
  33652. ArrowHelper.prototype = Object.create( Object3D.prototype );
  33653. ArrowHelper.prototype.constructor = ArrowHelper;
  33654. ArrowHelper.prototype.setDirection = function ( dir ) {
  33655. // dir is assumed to be normalized
  33656. if ( dir.y > 0.99999 ) {
  33657. this.quaternion.set( 0, 0, 0, 1 );
  33658. } else if ( dir.y < - 0.99999 ) {
  33659. this.quaternion.set( 1, 0, 0, 0 );
  33660. } else {
  33661. _axis.set( dir.z, 0, - dir.x ).normalize();
  33662. var radians = Math.acos( dir.y );
  33663. this.quaternion.setFromAxisAngle( _axis, radians );
  33664. }
  33665. };
  33666. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  33667. if ( headLength === undefined ) { headLength = 0.2 * length; }
  33668. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  33669. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  33670. this.line.updateMatrix();
  33671. this.cone.scale.set( headWidth, headLength, headWidth );
  33672. this.cone.position.y = length;
  33673. this.cone.updateMatrix();
  33674. };
  33675. ArrowHelper.prototype.setColor = function ( color ) {
  33676. this.line.material.color.set( color );
  33677. this.cone.material.color.set( color );
  33678. };
  33679. ArrowHelper.prototype.copy = function ( source ) {
  33680. Object3D.prototype.copy.call( this, source, false );
  33681. this.line.copy( source.line );
  33682. this.cone.copy( source.cone );
  33683. return this;
  33684. };
  33685. ArrowHelper.prototype.clone = function () {
  33686. return new this.constructor().copy( this );
  33687. };
  33688. /**
  33689. * @author sroucheray / http://sroucheray.org/
  33690. * @author mrdoob / http://mrdoob.com/
  33691. */
  33692. function AxesHelper( size ) {
  33693. size = size || 1;
  33694. var vertices = [
  33695. 0, 0, 0, size, 0, 0,
  33696. 0, 0, 0, 0, size, 0,
  33697. 0, 0, 0, 0, 0, size
  33698. ];
  33699. var colors = [
  33700. 1, 0, 0, 1, 0.6, 0,
  33701. 0, 1, 0, 0.6, 1, 0,
  33702. 0, 0, 1, 0, 0.6, 1
  33703. ];
  33704. var geometry = new BufferGeometry();
  33705. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33706. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33707. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  33708. LineSegments.call( this, geometry, material );
  33709. }
  33710. AxesHelper.prototype = Object.create( LineSegments.prototype );
  33711. AxesHelper.prototype.constructor = AxesHelper;
  33712. /**
  33713. * @author mrdoob / http://mrdoob.com/
  33714. */
  33715. function Face4( a, b, c, d, normal, color, materialIndex ) {
  33716. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  33717. return new Face3( a, b, c, normal, color, materialIndex );
  33718. }
  33719. var LineStrip = 0;
  33720. var LinePieces = 1;
  33721. function MeshFaceMaterial( materials ) {
  33722. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  33723. return materials;
  33724. }
  33725. function MultiMaterial( materials ) {
  33726. if ( materials === undefined ) { materials = []; }
  33727. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  33728. materials.isMultiMaterial = true;
  33729. materials.materials = materials;
  33730. materials.clone = function () {
  33731. return materials.slice();
  33732. };
  33733. return materials;
  33734. }
  33735. function PointCloud( geometry, material ) {
  33736. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  33737. return new Points( geometry, material );
  33738. }
  33739. function Particle( material ) {
  33740. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  33741. return new Sprite( material );
  33742. }
  33743. function ParticleSystem( geometry, material ) {
  33744. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  33745. return new Points( geometry, material );
  33746. }
  33747. function PointCloudMaterial( parameters ) {
  33748. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  33749. return new PointsMaterial( parameters );
  33750. }
  33751. function ParticleBasicMaterial( parameters ) {
  33752. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  33753. return new PointsMaterial( parameters );
  33754. }
  33755. function ParticleSystemMaterial( parameters ) {
  33756. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  33757. return new PointsMaterial( parameters );
  33758. }
  33759. function Vertex( x, y, z ) {
  33760. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  33761. return new Vector3( x, y, z );
  33762. }
  33763. //
  33764. function DynamicBufferAttribute( array, itemSize ) {
  33765. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  33766. return new BufferAttribute( array, itemSize ).setDynamic( true );
  33767. }
  33768. function Int8Attribute( array, itemSize ) {
  33769. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  33770. return new Int8BufferAttribute( array, itemSize );
  33771. }
  33772. function Uint8Attribute( array, itemSize ) {
  33773. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  33774. return new Uint8BufferAttribute( array, itemSize );
  33775. }
  33776. function Uint8ClampedAttribute( array, itemSize ) {
  33777. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  33778. return new Uint8ClampedBufferAttribute( array, itemSize );
  33779. }
  33780. function Int16Attribute( array, itemSize ) {
  33781. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  33782. return new Int16BufferAttribute( array, itemSize );
  33783. }
  33784. function Uint16Attribute( array, itemSize ) {
  33785. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  33786. return new Uint16BufferAttribute( array, itemSize );
  33787. }
  33788. function Int32Attribute( array, itemSize ) {
  33789. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  33790. return new Int32BufferAttribute( array, itemSize );
  33791. }
  33792. function Uint32Attribute( array, itemSize ) {
  33793. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  33794. return new Uint32BufferAttribute( array, itemSize );
  33795. }
  33796. function Float32Attribute( array, itemSize ) {
  33797. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  33798. return new Float32BufferAttribute( array, itemSize );
  33799. }
  33800. function Float64Attribute( array, itemSize ) {
  33801. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  33802. return new Float64BufferAttribute( array, itemSize );
  33803. }
  33804. //
  33805. Curve.create = function ( construct, getPoint ) {
  33806. console.log( 'THREE.Curve.create() has been deprecated' );
  33807. construct.prototype = Object.create( Curve.prototype );
  33808. construct.prototype.constructor = construct;
  33809. construct.prototype.getPoint = getPoint;
  33810. return construct;
  33811. };
  33812. //
  33813. Object.assign( CurvePath.prototype, {
  33814. createPointsGeometry: function ( divisions ) {
  33815. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  33816. // generate geometry from path points (for Line or Points objects)
  33817. var pts = this.getPoints( divisions );
  33818. return this.createGeometry( pts );
  33819. },
  33820. createSpacedPointsGeometry: function ( divisions ) {
  33821. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  33822. // generate geometry from equidistant sampling along the path
  33823. var pts = this.getSpacedPoints( divisions );
  33824. return this.createGeometry( pts );
  33825. },
  33826. createGeometry: function ( points ) {
  33827. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  33828. var geometry = new Geometry();
  33829. for ( var i = 0, l = points.length; i < l; i ++ ) {
  33830. var point = points[ i ];
  33831. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  33832. }
  33833. return geometry;
  33834. }
  33835. } );
  33836. //
  33837. Object.assign( Path.prototype, {
  33838. fromPoints: function ( points ) {
  33839. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  33840. this.setFromPoints( points );
  33841. }
  33842. } );
  33843. //
  33844. function ClosedSplineCurve3( points ) {
  33845. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  33846. CatmullRomCurve3.call( this, points );
  33847. this.type = 'catmullrom';
  33848. this.closed = true;
  33849. }
  33850. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  33851. //
  33852. function SplineCurve3( points ) {
  33853. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  33854. CatmullRomCurve3.call( this, points );
  33855. this.type = 'catmullrom';
  33856. }
  33857. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  33858. //
  33859. function Spline( points ) {
  33860. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  33861. CatmullRomCurve3.call( this, points );
  33862. this.type = 'catmullrom';
  33863. }
  33864. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  33865. Object.assign( Spline.prototype, {
  33866. initFromArray: function ( /* a */ ) {
  33867. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  33868. },
  33869. getControlPointsArray: function ( /* optionalTarget */ ) {
  33870. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  33871. },
  33872. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  33873. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  33874. }
  33875. } );
  33876. //
  33877. function AxisHelper( size ) {
  33878. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  33879. return new AxesHelper( size );
  33880. }
  33881. function BoundingBoxHelper( object, color ) {
  33882. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  33883. return new BoxHelper( object, color );
  33884. }
  33885. function EdgesHelper( object, hex ) {
  33886. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  33887. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  33888. }
  33889. GridHelper.prototype.setColors = function () {
  33890. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  33891. };
  33892. SkeletonHelper.prototype.update = function () {
  33893. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  33894. };
  33895. function WireframeHelper( object, hex ) {
  33896. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  33897. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  33898. }
  33899. //
  33900. Object.assign( Loader.prototype, {
  33901. extractUrlBase: function ( url ) {
  33902. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  33903. return LoaderUtils.extractUrlBase( url );
  33904. }
  33905. } );
  33906. Loader.Handlers = {
  33907. add: function ( /* regex, loader */ ) {
  33908. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  33909. },
  33910. get: function ( /* file */ ) {
  33911. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  33912. }
  33913. };
  33914. function XHRLoader( manager ) {
  33915. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  33916. return new FileLoader( manager );
  33917. }
  33918. function BinaryTextureLoader( manager ) {
  33919. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  33920. return new DataTextureLoader( manager );
  33921. }
  33922. Object.assign( ObjectLoader.prototype, {
  33923. setTexturePath: function ( value ) {
  33924. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  33925. return this.setResourcePath( value );
  33926. }
  33927. } );
  33928. //
  33929. Object.assign( Box2.prototype, {
  33930. center: function ( optionalTarget ) {
  33931. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  33932. return this.getCenter( optionalTarget );
  33933. },
  33934. empty: function () {
  33935. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  33936. return this.isEmpty();
  33937. },
  33938. isIntersectionBox: function ( box ) {
  33939. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  33940. return this.intersectsBox( box );
  33941. },
  33942. size: function ( optionalTarget ) {
  33943. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  33944. return this.getSize( optionalTarget );
  33945. }
  33946. } );
  33947. Object.assign( Box3.prototype, {
  33948. center: function ( optionalTarget ) {
  33949. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  33950. return this.getCenter( optionalTarget );
  33951. },
  33952. empty: function () {
  33953. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  33954. return this.isEmpty();
  33955. },
  33956. isIntersectionBox: function ( box ) {
  33957. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  33958. return this.intersectsBox( box );
  33959. },
  33960. isIntersectionSphere: function ( sphere ) {
  33961. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  33962. return this.intersectsSphere( sphere );
  33963. },
  33964. size: function ( optionalTarget ) {
  33965. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  33966. return this.getSize( optionalTarget );
  33967. }
  33968. } );
  33969. Line3.prototype.center = function ( optionalTarget ) {
  33970. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  33971. return this.getCenter( optionalTarget );
  33972. };
  33973. Object.assign( _Math, {
  33974. random16: function () {
  33975. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  33976. return Math.random();
  33977. },
  33978. nearestPowerOfTwo: function ( value ) {
  33979. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  33980. return _Math.floorPowerOfTwo( value );
  33981. },
  33982. nextPowerOfTwo: function ( value ) {
  33983. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  33984. return _Math.ceilPowerOfTwo( value );
  33985. }
  33986. } );
  33987. Object.assign( Matrix3.prototype, {
  33988. flattenToArrayOffset: function ( array, offset ) {
  33989. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  33990. return this.toArray( array, offset );
  33991. },
  33992. multiplyVector3: function ( vector ) {
  33993. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  33994. return vector.applyMatrix3( this );
  33995. },
  33996. multiplyVector3Array: function ( /* a */ ) {
  33997. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  33998. },
  33999. applyToBuffer: function ( buffer /*, offset, length */ ) {
  34000. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  34001. return this.applyToBufferAttribute( buffer );
  34002. },
  34003. applyToVector3Array: function ( /* array, offset, length */ ) {
  34004. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  34005. }
  34006. } );
  34007. Object.assign( Matrix4.prototype, {
  34008. extractPosition: function ( m ) {
  34009. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  34010. return this.copyPosition( m );
  34011. },
  34012. flattenToArrayOffset: function ( array, offset ) {
  34013. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  34014. return this.toArray( array, offset );
  34015. },
  34016. getPosition: function () {
  34017. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  34018. return new Vector3().setFromMatrixColumn( this, 3 );
  34019. },
  34020. setRotationFromQuaternion: function ( q ) {
  34021. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  34022. return this.makeRotationFromQuaternion( q );
  34023. },
  34024. multiplyToArray: function () {
  34025. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  34026. },
  34027. multiplyVector3: function ( vector ) {
  34028. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34029. return vector.applyMatrix4( this );
  34030. },
  34031. multiplyVector4: function ( vector ) {
  34032. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34033. return vector.applyMatrix4( this );
  34034. },
  34035. multiplyVector3Array: function ( /* a */ ) {
  34036. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  34037. },
  34038. rotateAxis: function ( v ) {
  34039. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  34040. v.transformDirection( this );
  34041. },
  34042. crossVector: function ( vector ) {
  34043. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34044. return vector.applyMatrix4( this );
  34045. },
  34046. translate: function () {
  34047. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  34048. },
  34049. rotateX: function () {
  34050. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  34051. },
  34052. rotateY: function () {
  34053. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  34054. },
  34055. rotateZ: function () {
  34056. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  34057. },
  34058. rotateByAxis: function () {
  34059. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  34060. },
  34061. applyToBuffer: function ( buffer /*, offset, length */ ) {
  34062. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  34063. return this.applyToBufferAttribute( buffer );
  34064. },
  34065. applyToVector3Array: function ( /* array, offset, length */ ) {
  34066. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  34067. },
  34068. makeFrustum: function ( left, right, bottom, top, near, far ) {
  34069. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  34070. return this.makePerspective( left, right, top, bottom, near, far );
  34071. }
  34072. } );
  34073. Plane.prototype.isIntersectionLine = function ( line ) {
  34074. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  34075. return this.intersectsLine( line );
  34076. };
  34077. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  34078. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  34079. return vector.applyQuaternion( this );
  34080. };
  34081. Object.assign( Ray.prototype, {
  34082. isIntersectionBox: function ( box ) {
  34083. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34084. return this.intersectsBox( box );
  34085. },
  34086. isIntersectionPlane: function ( plane ) {
  34087. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  34088. return this.intersectsPlane( plane );
  34089. },
  34090. isIntersectionSphere: function ( sphere ) {
  34091. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  34092. return this.intersectsSphere( sphere );
  34093. }
  34094. } );
  34095. Object.assign( Triangle.prototype, {
  34096. area: function () {
  34097. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  34098. return this.getArea();
  34099. },
  34100. barycoordFromPoint: function ( point, target ) {
  34101. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  34102. return this.getBarycoord( point, target );
  34103. },
  34104. midpoint: function ( target ) {
  34105. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  34106. return this.getMidpoint( target );
  34107. },
  34108. normal: function ( target ) {
  34109. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  34110. return this.getNormal( target );
  34111. },
  34112. plane: function ( target ) {
  34113. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  34114. return this.getPlane( target );
  34115. }
  34116. } );
  34117. Object.assign( Triangle, {
  34118. barycoordFromPoint: function ( point, a, b, c, target ) {
  34119. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  34120. return Triangle.getBarycoord( point, a, b, c, target );
  34121. },
  34122. normal: function ( a, b, c, target ) {
  34123. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  34124. return Triangle.getNormal( a, b, c, target );
  34125. }
  34126. } );
  34127. Object.assign( Shape.prototype, {
  34128. extractAllPoints: function ( divisions ) {
  34129. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  34130. return this.extractPoints( divisions );
  34131. },
  34132. extrude: function ( options ) {
  34133. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  34134. return new ExtrudeGeometry( this, options );
  34135. },
  34136. makeGeometry: function ( options ) {
  34137. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  34138. return new ShapeGeometry( this, options );
  34139. }
  34140. } );
  34141. Object.assign( Vector2.prototype, {
  34142. fromAttribute: function ( attribute, index, offset ) {
  34143. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  34144. return this.fromBufferAttribute( attribute, index, offset );
  34145. },
  34146. distanceToManhattan: function ( v ) {
  34147. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  34148. return this.manhattanDistanceTo( v );
  34149. },
  34150. lengthManhattan: function () {
  34151. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  34152. return this.manhattanLength();
  34153. }
  34154. } );
  34155. Object.assign( Vector3.prototype, {
  34156. setEulerFromRotationMatrix: function () {
  34157. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  34158. },
  34159. setEulerFromQuaternion: function () {
  34160. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  34161. },
  34162. getPositionFromMatrix: function ( m ) {
  34163. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  34164. return this.setFromMatrixPosition( m );
  34165. },
  34166. getScaleFromMatrix: function ( m ) {
  34167. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  34168. return this.setFromMatrixScale( m );
  34169. },
  34170. getColumnFromMatrix: function ( index, matrix ) {
  34171. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  34172. return this.setFromMatrixColumn( matrix, index );
  34173. },
  34174. applyProjection: function ( m ) {
  34175. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  34176. return this.applyMatrix4( m );
  34177. },
  34178. fromAttribute: function ( attribute, index, offset ) {
  34179. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  34180. return this.fromBufferAttribute( attribute, index, offset );
  34181. },
  34182. distanceToManhattan: function ( v ) {
  34183. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  34184. return this.manhattanDistanceTo( v );
  34185. },
  34186. lengthManhattan: function () {
  34187. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  34188. return this.manhattanLength();
  34189. }
  34190. } );
  34191. Object.assign( Vector4.prototype, {
  34192. fromAttribute: function ( attribute, index, offset ) {
  34193. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  34194. return this.fromBufferAttribute( attribute, index, offset );
  34195. },
  34196. lengthManhattan: function () {
  34197. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  34198. return this.manhattanLength();
  34199. }
  34200. } );
  34201. //
  34202. Object.assign( Geometry.prototype, {
  34203. computeTangents: function () {
  34204. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  34205. },
  34206. computeLineDistances: function () {
  34207. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  34208. }
  34209. } );
  34210. Object.assign( Object3D.prototype, {
  34211. getChildByName: function ( name ) {
  34212. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  34213. return this.getObjectByName( name );
  34214. },
  34215. renderDepth: function () {
  34216. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  34217. },
  34218. translate: function ( distance, axis ) {
  34219. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  34220. return this.translateOnAxis( axis, distance );
  34221. },
  34222. getWorldRotation: function () {
  34223. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  34224. }
  34225. } );
  34226. Object.defineProperties( Object3D.prototype, {
  34227. eulerOrder: {
  34228. get: function () {
  34229. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  34230. return this.rotation.order;
  34231. },
  34232. set: function ( value ) {
  34233. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  34234. this.rotation.order = value;
  34235. }
  34236. },
  34237. useQuaternion: {
  34238. get: function () {
  34239. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  34240. },
  34241. set: function () {
  34242. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  34243. }
  34244. }
  34245. } );
  34246. Object.defineProperties( LOD.prototype, {
  34247. objects: {
  34248. get: function () {
  34249. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  34250. return this.levels;
  34251. }
  34252. }
  34253. } );
  34254. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  34255. get: function () {
  34256. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  34257. },
  34258. set: function () {
  34259. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  34260. }
  34261. } );
  34262. SkinnedMesh.prototype.initBones = function () {
  34263. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  34264. };
  34265. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  34266. get: function () {
  34267. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  34268. return this.arcLengthDivisions;
  34269. },
  34270. set: function ( value ) {
  34271. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  34272. this.arcLengthDivisions = value;
  34273. }
  34274. } );
  34275. //
  34276. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  34277. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  34278. "Use .setFocalLength and .filmGauge for a photographic setup." );
  34279. if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; }
  34280. this.setFocalLength( focalLength );
  34281. };
  34282. //
  34283. Object.defineProperties( Light.prototype, {
  34284. onlyShadow: {
  34285. set: function () {
  34286. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  34287. }
  34288. },
  34289. shadowCameraFov: {
  34290. set: function ( value ) {
  34291. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  34292. this.shadow.camera.fov = value;
  34293. }
  34294. },
  34295. shadowCameraLeft: {
  34296. set: function ( value ) {
  34297. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  34298. this.shadow.camera.left = value;
  34299. }
  34300. },
  34301. shadowCameraRight: {
  34302. set: function ( value ) {
  34303. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  34304. this.shadow.camera.right = value;
  34305. }
  34306. },
  34307. shadowCameraTop: {
  34308. set: function ( value ) {
  34309. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  34310. this.shadow.camera.top = value;
  34311. }
  34312. },
  34313. shadowCameraBottom: {
  34314. set: function ( value ) {
  34315. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  34316. this.shadow.camera.bottom = value;
  34317. }
  34318. },
  34319. shadowCameraNear: {
  34320. set: function ( value ) {
  34321. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  34322. this.shadow.camera.near = value;
  34323. }
  34324. },
  34325. shadowCameraFar: {
  34326. set: function ( value ) {
  34327. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  34328. this.shadow.camera.far = value;
  34329. }
  34330. },
  34331. shadowCameraVisible: {
  34332. set: function () {
  34333. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  34334. }
  34335. },
  34336. shadowBias: {
  34337. set: function ( value ) {
  34338. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  34339. this.shadow.bias = value;
  34340. }
  34341. },
  34342. shadowDarkness: {
  34343. set: function () {
  34344. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  34345. }
  34346. },
  34347. shadowMapWidth: {
  34348. set: function ( value ) {
  34349. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  34350. this.shadow.mapSize.width = value;
  34351. }
  34352. },
  34353. shadowMapHeight: {
  34354. set: function ( value ) {
  34355. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  34356. this.shadow.mapSize.height = value;
  34357. }
  34358. }
  34359. } );
  34360. //
  34361. Object.defineProperties( BufferAttribute.prototype, {
  34362. length: {
  34363. get: function () {
  34364. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  34365. return this.array.length;
  34366. }
  34367. }
  34368. } );
  34369. Object.assign( BufferAttribute.prototype, {
  34370. copyIndicesArray: function ( /* indices */ ) {
  34371. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  34372. },
  34373. setArray: function ( array ) {
  34374. console.warn( 'THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  34375. this.count = array !== undefined ? array.length / this.itemSize : 0;
  34376. this.array = array;
  34377. return this;
  34378. }
  34379. } );
  34380. Object.assign( BufferGeometry.prototype, {
  34381. addIndex: function ( index ) {
  34382. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  34383. this.setIndex( index );
  34384. },
  34385. addDrawCall: function ( start, count, indexOffset ) {
  34386. if ( indexOffset !== undefined ) {
  34387. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  34388. }
  34389. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  34390. this.addGroup( start, count );
  34391. },
  34392. clearDrawCalls: function () {
  34393. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  34394. this.clearGroups();
  34395. },
  34396. computeTangents: function () {
  34397. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  34398. },
  34399. computeOffsets: function () {
  34400. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  34401. }
  34402. } );
  34403. Object.defineProperties( BufferGeometry.prototype, {
  34404. drawcalls: {
  34405. get: function () {
  34406. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  34407. return this.groups;
  34408. }
  34409. },
  34410. offsets: {
  34411. get: function () {
  34412. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  34413. return this.groups;
  34414. }
  34415. }
  34416. } );
  34417. Object.assign( InterleavedBuffer.prototype, {
  34418. setArray: function ( array ) {
  34419. console.warn( 'THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  34420. this.count = array !== undefined ? array.length / this.stride : 0;
  34421. this.array = array;
  34422. return this;
  34423. }
  34424. } );
  34425. //
  34426. Object.assign( ExtrudeBufferGeometry.prototype, {
  34427. getArrays: function () {
  34428. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  34429. },
  34430. addShapeList: function () {
  34431. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  34432. },
  34433. addShape: function () {
  34434. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  34435. }
  34436. } );
  34437. //
  34438. Object.defineProperties( Uniform.prototype, {
  34439. dynamic: {
  34440. set: function () {
  34441. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  34442. }
  34443. },
  34444. onUpdate: {
  34445. value: function () {
  34446. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  34447. return this;
  34448. }
  34449. }
  34450. } );
  34451. //
  34452. Object.defineProperties( Material.prototype, {
  34453. wrapAround: {
  34454. get: function () {
  34455. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  34456. },
  34457. set: function () {
  34458. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  34459. }
  34460. },
  34461. overdraw: {
  34462. get: function () {
  34463. console.warn( 'THREE.Material: .overdraw has been removed.' );
  34464. },
  34465. set: function () {
  34466. console.warn( 'THREE.Material: .overdraw has been removed.' );
  34467. }
  34468. },
  34469. wrapRGB: {
  34470. get: function () {
  34471. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  34472. return new Color();
  34473. }
  34474. },
  34475. shading: {
  34476. get: function () {
  34477. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  34478. },
  34479. set: function ( value ) {
  34480. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  34481. this.flatShading = ( value === FlatShading );
  34482. }
  34483. },
  34484. stencilMask: {
  34485. get: function () {
  34486. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  34487. return this.stencilFuncMask;
  34488. },
  34489. set: function ( value ) {
  34490. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  34491. this.stencilFuncMask = value;
  34492. }
  34493. }
  34494. } );
  34495. Object.defineProperties( MeshPhongMaterial.prototype, {
  34496. metal: {
  34497. get: function () {
  34498. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  34499. return false;
  34500. },
  34501. set: function () {
  34502. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  34503. }
  34504. }
  34505. } );
  34506. Object.defineProperties( ShaderMaterial.prototype, {
  34507. derivatives: {
  34508. get: function () {
  34509. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  34510. return this.extensions.derivatives;
  34511. },
  34512. set: function ( value ) {
  34513. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  34514. this.extensions.derivatives = value;
  34515. }
  34516. }
  34517. } );
  34518. //
  34519. Object.assign( WebGLRenderer.prototype, {
  34520. clearTarget: function ( renderTarget, color, depth, stencil ) {
  34521. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  34522. this.setRenderTarget( renderTarget );
  34523. this.clear( color, depth, stencil );
  34524. },
  34525. animate: function ( callback ) {
  34526. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  34527. this.setAnimationLoop( callback );
  34528. },
  34529. getCurrentRenderTarget: function () {
  34530. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  34531. return this.getRenderTarget();
  34532. },
  34533. getMaxAnisotropy: function () {
  34534. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  34535. return this.capabilities.getMaxAnisotropy();
  34536. },
  34537. getPrecision: function () {
  34538. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  34539. return this.capabilities.precision;
  34540. },
  34541. resetGLState: function () {
  34542. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  34543. return this.state.reset();
  34544. },
  34545. supportsFloatTextures: function () {
  34546. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  34547. return this.extensions.get( 'OES_texture_float' );
  34548. },
  34549. supportsHalfFloatTextures: function () {
  34550. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  34551. return this.extensions.get( 'OES_texture_half_float' );
  34552. },
  34553. supportsStandardDerivatives: function () {
  34554. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  34555. return this.extensions.get( 'OES_standard_derivatives' );
  34556. },
  34557. supportsCompressedTextureS3TC: function () {
  34558. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  34559. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  34560. },
  34561. supportsCompressedTexturePVRTC: function () {
  34562. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  34563. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  34564. },
  34565. supportsBlendMinMax: function () {
  34566. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  34567. return this.extensions.get( 'EXT_blend_minmax' );
  34568. },
  34569. supportsVertexTextures: function () {
  34570. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  34571. return this.capabilities.vertexTextures;
  34572. },
  34573. supportsInstancedArrays: function () {
  34574. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  34575. return this.extensions.get( 'ANGLE_instanced_arrays' );
  34576. },
  34577. enableScissorTest: function ( boolean ) {
  34578. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  34579. this.setScissorTest( boolean );
  34580. },
  34581. initMaterial: function () {
  34582. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  34583. },
  34584. addPrePlugin: function () {
  34585. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  34586. },
  34587. addPostPlugin: function () {
  34588. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  34589. },
  34590. updateShadowMap: function () {
  34591. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  34592. },
  34593. setFaceCulling: function () {
  34594. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  34595. },
  34596. allocTextureUnit: function () {
  34597. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  34598. },
  34599. setTexture: function () {
  34600. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  34601. },
  34602. setTextureCube: function () {
  34603. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  34604. },
  34605. getActiveMipMapLevel: function () {
  34606. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  34607. return this.getActiveMipmapLevel();
  34608. }
  34609. } );
  34610. Object.defineProperties( WebGLRenderer.prototype, {
  34611. shadowMapEnabled: {
  34612. get: function () {
  34613. return this.shadowMap.enabled;
  34614. },
  34615. set: function ( value ) {
  34616. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  34617. this.shadowMap.enabled = value;
  34618. }
  34619. },
  34620. shadowMapType: {
  34621. get: function () {
  34622. return this.shadowMap.type;
  34623. },
  34624. set: function ( value ) {
  34625. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  34626. this.shadowMap.type = value;
  34627. }
  34628. },
  34629. shadowMapCullFace: {
  34630. get: function () {
  34631. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  34632. return undefined;
  34633. },
  34634. set: function ( /* value */ ) {
  34635. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  34636. }
  34637. },
  34638. context: {
  34639. get: function () {
  34640. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  34641. return this.getContext();
  34642. }
  34643. }
  34644. } );
  34645. Object.defineProperties( WebGLShadowMap.prototype, {
  34646. cullFace: {
  34647. get: function () {
  34648. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  34649. return undefined;
  34650. },
  34651. set: function ( /* cullFace */ ) {
  34652. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  34653. }
  34654. },
  34655. renderReverseSided: {
  34656. get: function () {
  34657. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  34658. return undefined;
  34659. },
  34660. set: function () {
  34661. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  34662. }
  34663. },
  34664. renderSingleSided: {
  34665. get: function () {
  34666. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  34667. return undefined;
  34668. },
  34669. set: function () {
  34670. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  34671. }
  34672. }
  34673. } );
  34674. //
  34675. Object.defineProperties( WebGLRenderTargetCube.prototype, {
  34676. activeCubeFace: {
  34677. set: function ( /* value */ ) {
  34678. console.warn( 'THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().' );
  34679. }
  34680. },
  34681. activeMipMapLevel: {
  34682. set: function ( /* value */ ) {
  34683. console.warn( 'THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().' );
  34684. }
  34685. }
  34686. } );
  34687. //
  34688. Object.defineProperties( WebGLRenderTarget.prototype, {
  34689. wrapS: {
  34690. get: function () {
  34691. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  34692. return this.texture.wrapS;
  34693. },
  34694. set: function ( value ) {
  34695. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  34696. this.texture.wrapS = value;
  34697. }
  34698. },
  34699. wrapT: {
  34700. get: function () {
  34701. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  34702. return this.texture.wrapT;
  34703. },
  34704. set: function ( value ) {
  34705. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  34706. this.texture.wrapT = value;
  34707. }
  34708. },
  34709. magFilter: {
  34710. get: function () {
  34711. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  34712. return this.texture.magFilter;
  34713. },
  34714. set: function ( value ) {
  34715. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  34716. this.texture.magFilter = value;
  34717. }
  34718. },
  34719. minFilter: {
  34720. get: function () {
  34721. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  34722. return this.texture.minFilter;
  34723. },
  34724. set: function ( value ) {
  34725. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  34726. this.texture.minFilter = value;
  34727. }
  34728. },
  34729. anisotropy: {
  34730. get: function () {
  34731. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  34732. return this.texture.anisotropy;
  34733. },
  34734. set: function ( value ) {
  34735. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  34736. this.texture.anisotropy = value;
  34737. }
  34738. },
  34739. offset: {
  34740. get: function () {
  34741. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  34742. return this.texture.offset;
  34743. },
  34744. set: function ( value ) {
  34745. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  34746. this.texture.offset = value;
  34747. }
  34748. },
  34749. repeat: {
  34750. get: function () {
  34751. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  34752. return this.texture.repeat;
  34753. },
  34754. set: function ( value ) {
  34755. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  34756. this.texture.repeat = value;
  34757. }
  34758. },
  34759. format: {
  34760. get: function () {
  34761. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  34762. return this.texture.format;
  34763. },
  34764. set: function ( value ) {
  34765. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  34766. this.texture.format = value;
  34767. }
  34768. },
  34769. type: {
  34770. get: function () {
  34771. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  34772. return this.texture.type;
  34773. },
  34774. set: function ( value ) {
  34775. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  34776. this.texture.type = value;
  34777. }
  34778. },
  34779. generateMipmaps: {
  34780. get: function () {
  34781. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  34782. return this.texture.generateMipmaps;
  34783. },
  34784. set: function ( value ) {
  34785. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  34786. this.texture.generateMipmaps = value;
  34787. }
  34788. }
  34789. } );
  34790. //
  34791. Object.defineProperties( WebVRManager.prototype, {
  34792. standing: {
  34793. set: function ( /* value */ ) {
  34794. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  34795. }
  34796. },
  34797. userHeight: {
  34798. set: function ( /* value */ ) {
  34799. console.warn( 'THREE.WebVRManager: .userHeight has been removed.' );
  34800. }
  34801. }
  34802. } );
  34803. //
  34804. Audio.prototype.load = function ( file ) {
  34805. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  34806. var scope = this;
  34807. var audioLoader = new AudioLoader();
  34808. audioLoader.load( file, function ( buffer ) {
  34809. scope.setBuffer( buffer );
  34810. } );
  34811. return this;
  34812. };
  34813. AudioAnalyser.prototype.getData = function () {
  34814. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  34815. return this.getFrequencyData();
  34816. };
  34817. //
  34818. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  34819. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  34820. return this.update( renderer, scene );
  34821. };
  34822. //
  34823. var GeometryUtils = {
  34824. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  34825. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  34826. var matrix;
  34827. if ( geometry2.isMesh ) {
  34828. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  34829. matrix = geometry2.matrix;
  34830. geometry2 = geometry2.geometry;
  34831. }
  34832. geometry1.merge( geometry2, matrix, materialIndexOffset );
  34833. },
  34834. center: function ( geometry ) {
  34835. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  34836. return geometry.center();
  34837. }
  34838. };
  34839. ImageUtils.crossOrigin = undefined;
  34840. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  34841. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  34842. var loader = new TextureLoader();
  34843. loader.setCrossOrigin( this.crossOrigin );
  34844. var texture = loader.load( url, onLoad, undefined, onError );
  34845. if ( mapping ) { texture.mapping = mapping; }
  34846. return texture;
  34847. };
  34848. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  34849. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  34850. var loader = new CubeTextureLoader();
  34851. loader.setCrossOrigin( this.crossOrigin );
  34852. var texture = loader.load( urls, onLoad, undefined, onError );
  34853. if ( mapping ) { texture.mapping = mapping; }
  34854. return texture;
  34855. };
  34856. ImageUtils.loadCompressedTexture = function () {
  34857. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  34858. };
  34859. ImageUtils.loadCompressedTextureCube = function () {
  34860. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  34861. };
  34862. //
  34863. function CanvasRenderer() {
  34864. console.error( 'THREE.CanvasRenderer has been removed' );
  34865. }
  34866. //
  34867. function JSONLoader() {
  34868. console.error( 'THREE.JSONLoader has been removed.' );
  34869. }
  34870. //
  34871. var SceneUtils = {
  34872. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  34873. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  34874. },
  34875. detach: function ( /* child, parent, scene */ ) {
  34876. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  34877. },
  34878. attach: function ( /* child, scene, parent */ ) {
  34879. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  34880. }
  34881. };
  34882. //
  34883. function LensFlare() {
  34884. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  34885. }
  34886. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  34887. /* eslint-disable no-undef */
  34888. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  34889. revision: REVISION,
  34890. } } ) );
  34891. /* eslint-enable no-undef */
  34892. }
  34893. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  34894. exports.AddEquation = AddEquation;
  34895. exports.AddOperation = AddOperation;
  34896. exports.AdditiveBlending = AdditiveBlending;
  34897. exports.AlphaFormat = AlphaFormat;
  34898. exports.AlwaysDepth = AlwaysDepth;
  34899. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  34900. exports.AmbientLight = AmbientLight;
  34901. exports.AmbientLightProbe = AmbientLightProbe;
  34902. exports.AnimationClip = AnimationClip;
  34903. exports.AnimationLoader = AnimationLoader;
  34904. exports.AnimationMixer = AnimationMixer;
  34905. exports.AnimationObjectGroup = AnimationObjectGroup;
  34906. exports.AnimationUtils = AnimationUtils;
  34907. exports.ArcCurve = ArcCurve;
  34908. exports.ArrayCamera = ArrayCamera;
  34909. exports.ArrowHelper = ArrowHelper;
  34910. exports.Audio = Audio;
  34911. exports.AudioAnalyser = AudioAnalyser;
  34912. exports.AudioContext = AudioContext;
  34913. exports.AudioListener = AudioListener;
  34914. exports.AudioLoader = AudioLoader;
  34915. exports.AxesHelper = AxesHelper;
  34916. exports.AxisHelper = AxisHelper;
  34917. exports.BackSide = BackSide;
  34918. exports.BasicDepthPacking = BasicDepthPacking;
  34919. exports.BasicShadowMap = BasicShadowMap;
  34920. exports.BinaryTextureLoader = BinaryTextureLoader;
  34921. exports.Bone = Bone;
  34922. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  34923. exports.BoundingBoxHelper = BoundingBoxHelper;
  34924. exports.Box2 = Box2;
  34925. exports.Box3 = Box3;
  34926. exports.Box3Helper = Box3Helper;
  34927. exports.BoxBufferGeometry = BoxBufferGeometry;
  34928. exports.BoxGeometry = BoxGeometry;
  34929. exports.BoxHelper = BoxHelper;
  34930. exports.BufferAttribute = BufferAttribute;
  34931. exports.BufferGeometry = BufferGeometry;
  34932. exports.BufferGeometryLoader = BufferGeometryLoader;
  34933. exports.ByteType = ByteType;
  34934. exports.Cache = Cache;
  34935. exports.Camera = Camera;
  34936. exports.CameraHelper = CameraHelper;
  34937. exports.CanvasRenderer = CanvasRenderer;
  34938. exports.CanvasTexture = CanvasTexture;
  34939. exports.CatmullRomCurve3 = CatmullRomCurve3;
  34940. exports.CineonToneMapping = CineonToneMapping;
  34941. exports.CircleBufferGeometry = CircleBufferGeometry;
  34942. exports.CircleGeometry = CircleGeometry;
  34943. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  34944. exports.Clock = Clock;
  34945. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  34946. exports.Color = Color;
  34947. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  34948. exports.CompressedTexture = CompressedTexture;
  34949. exports.CompressedTextureLoader = CompressedTextureLoader;
  34950. exports.ConeBufferGeometry = ConeBufferGeometry;
  34951. exports.ConeGeometry = ConeGeometry;
  34952. exports.CubeCamera = CubeCamera;
  34953. exports.CubeGeometry = BoxGeometry;
  34954. exports.CubeReflectionMapping = CubeReflectionMapping;
  34955. exports.CubeRefractionMapping = CubeRefractionMapping;
  34956. exports.CubeTexture = CubeTexture;
  34957. exports.CubeTextureLoader = CubeTextureLoader;
  34958. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  34959. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  34960. exports.CubicBezierCurve = CubicBezierCurve;
  34961. exports.CubicBezierCurve3 = CubicBezierCurve3;
  34962. exports.CubicInterpolant = CubicInterpolant;
  34963. exports.CullFaceBack = CullFaceBack;
  34964. exports.CullFaceFront = CullFaceFront;
  34965. exports.CullFaceFrontBack = CullFaceFrontBack;
  34966. exports.CullFaceNone = CullFaceNone;
  34967. exports.Curve = Curve;
  34968. exports.CurvePath = CurvePath;
  34969. exports.CustomBlending = CustomBlending;
  34970. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  34971. exports.CylinderGeometry = CylinderGeometry;
  34972. exports.Cylindrical = Cylindrical;
  34973. exports.DataTexture = DataTexture;
  34974. exports.DataTexture2DArray = DataTexture2DArray;
  34975. exports.DataTexture3D = DataTexture3D;
  34976. exports.DataTextureLoader = DataTextureLoader;
  34977. exports.DecrementStencilOp = DecrementStencilOp;
  34978. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  34979. exports.DefaultLoadingManager = DefaultLoadingManager;
  34980. exports.DepthFormat = DepthFormat;
  34981. exports.DepthStencilFormat = DepthStencilFormat;
  34982. exports.DepthTexture = DepthTexture;
  34983. exports.DirectionalLight = DirectionalLight;
  34984. exports.DirectionalLightHelper = DirectionalLightHelper;
  34985. exports.DirectionalLightShadow = DirectionalLightShadow;
  34986. exports.DiscreteInterpolant = DiscreteInterpolant;
  34987. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  34988. exports.DodecahedronGeometry = DodecahedronGeometry;
  34989. exports.DoubleSide = DoubleSide;
  34990. exports.DstAlphaFactor = DstAlphaFactor;
  34991. exports.DstColorFactor = DstColorFactor;
  34992. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  34993. exports.EdgesGeometry = EdgesGeometry;
  34994. exports.EdgesHelper = EdgesHelper;
  34995. exports.EllipseCurve = EllipseCurve;
  34996. exports.EqualDepth = EqualDepth;
  34997. exports.EqualStencilFunc = EqualStencilFunc;
  34998. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  34999. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  35000. exports.Euler = Euler;
  35001. exports.EventDispatcher = EventDispatcher;
  35002. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  35003. exports.ExtrudeGeometry = ExtrudeGeometry;
  35004. exports.Face3 = Face3;
  35005. exports.Face4 = Face4;
  35006. exports.FaceColors = FaceColors;
  35007. exports.FaceNormalsHelper = FaceNormalsHelper;
  35008. exports.FileLoader = FileLoader;
  35009. exports.FlatShading = FlatShading;
  35010. exports.Float32Attribute = Float32Attribute;
  35011. exports.Float32BufferAttribute = Float32BufferAttribute;
  35012. exports.Float64Attribute = Float64Attribute;
  35013. exports.Float64BufferAttribute = Float64BufferAttribute;
  35014. exports.FloatType = FloatType;
  35015. exports.Fog = Fog;
  35016. exports.FogExp2 = FogExp2;
  35017. exports.Font = Font;
  35018. exports.FontLoader = FontLoader;
  35019. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  35020. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  35021. exports.FrontSide = FrontSide;
  35022. exports.Frustum = Frustum;
  35023. exports.GammaEncoding = GammaEncoding;
  35024. exports.Geometry = Geometry;
  35025. exports.GeometryUtils = GeometryUtils;
  35026. exports.GreaterDepth = GreaterDepth;
  35027. exports.GreaterEqualDepth = GreaterEqualDepth;
  35028. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  35029. exports.GreaterStencilFunc = GreaterStencilFunc;
  35030. exports.GridHelper = GridHelper;
  35031. exports.Group = Group;
  35032. exports.HalfFloatType = HalfFloatType;
  35033. exports.HemisphereLight = HemisphereLight;
  35034. exports.HemisphereLightHelper = HemisphereLightHelper;
  35035. exports.HemisphereLightProbe = HemisphereLightProbe;
  35036. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  35037. exports.IcosahedronGeometry = IcosahedronGeometry;
  35038. exports.ImageBitmapLoader = ImageBitmapLoader;
  35039. exports.ImageLoader = ImageLoader;
  35040. exports.ImageUtils = ImageUtils;
  35041. exports.ImmediateRenderObject = ImmediateRenderObject;
  35042. exports.IncrementStencilOp = IncrementStencilOp;
  35043. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  35044. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  35045. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  35046. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  35047. exports.Int16Attribute = Int16Attribute;
  35048. exports.Int16BufferAttribute = Int16BufferAttribute;
  35049. exports.Int32Attribute = Int32Attribute;
  35050. exports.Int32BufferAttribute = Int32BufferAttribute;
  35051. exports.Int8Attribute = Int8Attribute;
  35052. exports.Int8BufferAttribute = Int8BufferAttribute;
  35053. exports.IntType = IntType;
  35054. exports.InterleavedBuffer = InterleavedBuffer;
  35055. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  35056. exports.Interpolant = Interpolant;
  35057. exports.InterpolateDiscrete = InterpolateDiscrete;
  35058. exports.InterpolateLinear = InterpolateLinear;
  35059. exports.InterpolateSmooth = InterpolateSmooth;
  35060. exports.InvertStencilOp = InvertStencilOp;
  35061. exports.JSONLoader = JSONLoader;
  35062. exports.KeepStencilOp = KeepStencilOp;
  35063. exports.KeyframeTrack = KeyframeTrack;
  35064. exports.LOD = LOD;
  35065. exports.LatheBufferGeometry = LatheBufferGeometry;
  35066. exports.LatheGeometry = LatheGeometry;
  35067. exports.Layers = Layers;
  35068. exports.LensFlare = LensFlare;
  35069. exports.LessDepth = LessDepth;
  35070. exports.LessEqualDepth = LessEqualDepth;
  35071. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  35072. exports.LessStencilFunc = LessStencilFunc;
  35073. exports.Light = Light;
  35074. exports.LightProbe = LightProbe;
  35075. exports.LightProbeHelper = LightProbeHelper;
  35076. exports.LightShadow = LightShadow;
  35077. exports.Line = Line;
  35078. exports.Line3 = Line3;
  35079. exports.LineBasicMaterial = LineBasicMaterial;
  35080. exports.LineCurve = LineCurve;
  35081. exports.LineCurve3 = LineCurve3;
  35082. exports.LineDashedMaterial = LineDashedMaterial;
  35083. exports.LineLoop = LineLoop;
  35084. exports.LinePieces = LinePieces;
  35085. exports.LineSegments = LineSegments;
  35086. exports.LineStrip = LineStrip;
  35087. exports.LinearEncoding = LinearEncoding;
  35088. exports.LinearFilter = LinearFilter;
  35089. exports.LinearInterpolant = LinearInterpolant;
  35090. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  35091. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  35092. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  35093. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  35094. exports.LinearToneMapping = LinearToneMapping;
  35095. exports.Loader = Loader;
  35096. exports.LoaderUtils = LoaderUtils;
  35097. exports.LoadingManager = LoadingManager;
  35098. exports.LogLuvEncoding = LogLuvEncoding;
  35099. exports.LoopOnce = LoopOnce;
  35100. exports.LoopPingPong = LoopPingPong;
  35101. exports.LoopRepeat = LoopRepeat;
  35102. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  35103. exports.LuminanceFormat = LuminanceFormat;
  35104. exports.MOUSE = MOUSE;
  35105. exports.Material = Material;
  35106. exports.MaterialLoader = MaterialLoader;
  35107. exports.Math = _Math;
  35108. exports.Matrix3 = Matrix3;
  35109. exports.Matrix4 = Matrix4;
  35110. exports.MaxEquation = MaxEquation;
  35111. exports.Mesh = Mesh;
  35112. exports.MeshBasicMaterial = MeshBasicMaterial;
  35113. exports.MeshDepthMaterial = MeshDepthMaterial;
  35114. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  35115. exports.MeshFaceMaterial = MeshFaceMaterial;
  35116. exports.MeshLambertMaterial = MeshLambertMaterial;
  35117. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  35118. exports.MeshNormalMaterial = MeshNormalMaterial;
  35119. exports.MeshPhongMaterial = MeshPhongMaterial;
  35120. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  35121. exports.MeshStandardMaterial = MeshStandardMaterial;
  35122. exports.MeshToonMaterial = MeshToonMaterial;
  35123. exports.MinEquation = MinEquation;
  35124. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  35125. exports.MixOperation = MixOperation;
  35126. exports.MultiMaterial = MultiMaterial;
  35127. exports.MultiplyBlending = MultiplyBlending;
  35128. exports.MultiplyOperation = MultiplyOperation;
  35129. exports.NearestFilter = NearestFilter;
  35130. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  35131. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  35132. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  35133. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  35134. exports.NeverDepth = NeverDepth;
  35135. exports.NeverStencilFunc = NeverStencilFunc;
  35136. exports.NoBlending = NoBlending;
  35137. exports.NoColors = NoColors;
  35138. exports.NoToneMapping = NoToneMapping;
  35139. exports.NormalBlending = NormalBlending;
  35140. exports.NotEqualDepth = NotEqualDepth;
  35141. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  35142. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  35143. exports.Object3D = Object3D;
  35144. exports.ObjectLoader = ObjectLoader;
  35145. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  35146. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  35147. exports.OctahedronGeometry = OctahedronGeometry;
  35148. exports.OneFactor = OneFactor;
  35149. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  35150. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  35151. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  35152. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  35153. exports.OrthographicCamera = OrthographicCamera;
  35154. exports.PCFShadowMap = PCFShadowMap;
  35155. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  35156. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  35157. exports.ParametricGeometry = ParametricGeometry;
  35158. exports.Particle = Particle;
  35159. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  35160. exports.ParticleSystem = ParticleSystem;
  35161. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  35162. exports.Path = Path;
  35163. exports.PerspectiveCamera = PerspectiveCamera;
  35164. exports.Plane = Plane;
  35165. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  35166. exports.PlaneGeometry = PlaneGeometry;
  35167. exports.PlaneHelper = PlaneHelper;
  35168. exports.PointCloud = PointCloud;
  35169. exports.PointCloudMaterial = PointCloudMaterial;
  35170. exports.PointLight = PointLight;
  35171. exports.PointLightHelper = PointLightHelper;
  35172. exports.Points = Points;
  35173. exports.PointsMaterial = PointsMaterial;
  35174. exports.PolarGridHelper = PolarGridHelper;
  35175. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  35176. exports.PolyhedronGeometry = PolyhedronGeometry;
  35177. exports.PositionalAudio = PositionalAudio;
  35178. exports.PositionalAudioHelper = PositionalAudioHelper;
  35179. exports.PropertyBinding = PropertyBinding;
  35180. exports.PropertyMixer = PropertyMixer;
  35181. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  35182. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  35183. exports.Quaternion = Quaternion;
  35184. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  35185. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  35186. exports.REVISION = REVISION;
  35187. exports.RGBADepthPacking = RGBADepthPacking;
  35188. exports.RGBAFormat = RGBAFormat;
  35189. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  35190. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  35191. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  35192. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  35193. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  35194. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  35195. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  35196. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  35197. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  35198. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  35199. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  35200. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  35201. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  35202. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  35203. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  35204. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  35205. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  35206. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  35207. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  35208. exports.RGBDEncoding = RGBDEncoding;
  35209. exports.RGBEEncoding = RGBEEncoding;
  35210. exports.RGBEFormat = RGBEFormat;
  35211. exports.RGBFormat = RGBFormat;
  35212. exports.RGBM16Encoding = RGBM16Encoding;
  35213. exports.RGBM7Encoding = RGBM7Encoding;
  35214. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  35215. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  35216. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  35217. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  35218. exports.RawShaderMaterial = RawShaderMaterial;
  35219. exports.Ray = Ray;
  35220. exports.Raycaster = Raycaster;
  35221. exports.RectAreaLight = RectAreaLight;
  35222. exports.RectAreaLightHelper = RectAreaLightHelper;
  35223. exports.RedFormat = RedFormat;
  35224. exports.ReinhardToneMapping = ReinhardToneMapping;
  35225. exports.RepeatWrapping = RepeatWrapping;
  35226. exports.ReplaceStencilOp = ReplaceStencilOp;
  35227. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  35228. exports.RingBufferGeometry = RingBufferGeometry;
  35229. exports.RingGeometry = RingGeometry;
  35230. exports.Scene = Scene;
  35231. exports.SceneUtils = SceneUtils;
  35232. exports.ShaderChunk = ShaderChunk;
  35233. exports.ShaderLib = ShaderLib;
  35234. exports.ShaderMaterial = ShaderMaterial;
  35235. exports.ShadowMaterial = ShadowMaterial;
  35236. exports.Shape = Shape;
  35237. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  35238. exports.ShapeGeometry = ShapeGeometry;
  35239. exports.ShapePath = ShapePath;
  35240. exports.ShapeUtils = ShapeUtils;
  35241. exports.ShortType = ShortType;
  35242. exports.Skeleton = Skeleton;
  35243. exports.SkeletonHelper = SkeletonHelper;
  35244. exports.SkinnedMesh = SkinnedMesh;
  35245. exports.SmoothShading = SmoothShading;
  35246. exports.Sphere = Sphere;
  35247. exports.SphereBufferGeometry = SphereBufferGeometry;
  35248. exports.SphereGeometry = SphereGeometry;
  35249. exports.Spherical = Spherical;
  35250. exports.SphericalHarmonics3 = SphericalHarmonics3;
  35251. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  35252. exports.Spline = Spline;
  35253. exports.SplineCurve = SplineCurve;
  35254. exports.SplineCurve3 = SplineCurve3;
  35255. exports.SpotLight = SpotLight;
  35256. exports.SpotLightHelper = SpotLightHelper;
  35257. exports.SpotLightShadow = SpotLightShadow;
  35258. exports.Sprite = Sprite;
  35259. exports.SpriteMaterial = SpriteMaterial;
  35260. exports.SrcAlphaFactor = SrcAlphaFactor;
  35261. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  35262. exports.SrcColorFactor = SrcColorFactor;
  35263. exports.StereoCamera = StereoCamera;
  35264. exports.StringKeyframeTrack = StringKeyframeTrack;
  35265. exports.SubtractEquation = SubtractEquation;
  35266. exports.SubtractiveBlending = SubtractiveBlending;
  35267. exports.TOUCH = TOUCH;
  35268. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  35269. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  35270. exports.TetrahedronGeometry = TetrahedronGeometry;
  35271. exports.TextBufferGeometry = TextBufferGeometry;
  35272. exports.TextGeometry = TextGeometry;
  35273. exports.Texture = Texture;
  35274. exports.TextureLoader = TextureLoader;
  35275. exports.TorusBufferGeometry = TorusBufferGeometry;
  35276. exports.TorusGeometry = TorusGeometry;
  35277. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  35278. exports.TorusKnotGeometry = TorusKnotGeometry;
  35279. exports.Triangle = Triangle;
  35280. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  35281. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  35282. exports.TrianglesDrawMode = TrianglesDrawMode;
  35283. exports.TubeBufferGeometry = TubeBufferGeometry;
  35284. exports.TubeGeometry = TubeGeometry;
  35285. exports.UVMapping = UVMapping;
  35286. exports.Uint16Attribute = Uint16Attribute;
  35287. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  35288. exports.Uint32Attribute = Uint32Attribute;
  35289. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  35290. exports.Uint8Attribute = Uint8Attribute;
  35291. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  35292. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  35293. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  35294. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  35295. exports.Uniform = Uniform;
  35296. exports.UniformsLib = UniformsLib;
  35297. exports.UniformsUtils = UniformsUtils;
  35298. exports.UnsignedByteType = UnsignedByteType;
  35299. exports.UnsignedInt248Type = UnsignedInt248Type;
  35300. exports.UnsignedIntType = UnsignedIntType;
  35301. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  35302. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  35303. exports.UnsignedShort565Type = UnsignedShort565Type;
  35304. exports.UnsignedShortType = UnsignedShortType;
  35305. exports.VSMShadowMap = VSMShadowMap;
  35306. exports.Vector2 = Vector2;
  35307. exports.Vector3 = Vector3;
  35308. exports.Vector4 = Vector4;
  35309. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  35310. exports.Vertex = Vertex;
  35311. exports.VertexColors = VertexColors;
  35312. exports.VertexNormalsHelper = VertexNormalsHelper;
  35313. exports.VideoTexture = VideoTexture;
  35314. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  35315. exports.WebGLRenderTarget = WebGLRenderTarget;
  35316. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  35317. exports.WebGLRenderer = WebGLRenderer;
  35318. exports.WebGLUtils = WebGLUtils;
  35319. exports.WireframeGeometry = WireframeGeometry;
  35320. exports.WireframeHelper = WireframeHelper;
  35321. exports.WrapAroundEnding = WrapAroundEnding;
  35322. exports.XHRLoader = XHRLoader;
  35323. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  35324. exports.ZeroFactor = ZeroFactor;
  35325. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  35326. exports.ZeroStencilOp = ZeroStencilOp;
  35327. exports.sRGBEncoding = sRGBEncoding;
  35328. Object.defineProperty(exports, '__esModule', { value: true });
  35329. }));
  35330. },{}],58:[function(_dereq_,module,exports){
  35331. /**
  35332. * @author Don McCurdy / https://www.donmccurdy.com
  35333. */
  35334. THREE.DRACOLoader = function ( manager ) {
  35335. THREE.Loader.call( this, manager );
  35336. this.decoderPath = '';
  35337. this.decoderConfig = {};
  35338. this.decoderBinary = null;
  35339. this.decoderPending = null;
  35340. this.workerLimit = 4;
  35341. this.workerPool = [];
  35342. this.workerNextTaskID = 1;
  35343. this.workerSourceURL = '';
  35344. this.defaultAttributeIDs = {
  35345. position: 'POSITION',
  35346. normal: 'NORMAL',
  35347. color: 'COLOR',
  35348. uv: 'TEX_COORD'
  35349. };
  35350. this.defaultAttributeTypes = {
  35351. position: 'Float32Array',
  35352. normal: 'Float32Array',
  35353. color: 'Float32Array',
  35354. uv: 'Float32Array'
  35355. };
  35356. };
  35357. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  35358. constructor: THREE.DRACOLoader,
  35359. setDecoderPath: function ( path ) {
  35360. this.decoderPath = path;
  35361. return this;
  35362. },
  35363. setDecoderConfig: function ( config ) {
  35364. this.decoderConfig = config;
  35365. return this;
  35366. },
  35367. setWorkerLimit: function ( workerLimit ) {
  35368. this.workerLimit = workerLimit;
  35369. return this;
  35370. },
  35371. /** @deprecated */
  35372. setVerbosity: function () {
  35373. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  35374. },
  35375. /** @deprecated */
  35376. setDrawMode: function () {
  35377. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  35378. },
  35379. /** @deprecated */
  35380. setSkipDequantization: function () {
  35381. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  35382. },
  35383. load: function ( url, onLoad, onProgress, onError ) {
  35384. var loader = new THREE.FileLoader( this.manager );
  35385. loader.setPath( this.path );
  35386. loader.setResponseType( 'arraybuffer' );
  35387. if ( this.crossOrigin === 'use-credentials' ) {
  35388. loader.setWithCredentials( true );
  35389. }
  35390. loader.load( url, ( buffer ) => {
  35391. var taskConfig = {
  35392. attributeIDs: this.defaultAttributeIDs,
  35393. attributeTypes: this.defaultAttributeTypes,
  35394. useUniqueIDs: false
  35395. };
  35396. this.decodeGeometry( buffer, taskConfig )
  35397. .then( onLoad )
  35398. .catch( onError );
  35399. }, onProgress, onError );
  35400. },
  35401. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  35402. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  35403. var taskConfig = {
  35404. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  35405. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  35406. useUniqueIDs: !! attributeIDs
  35407. };
  35408. this.decodeGeometry( buffer, taskConfig ).then( callback );
  35409. },
  35410. decodeGeometry: function ( buffer, taskConfig ) {
  35411. var worker;
  35412. var taskID = this.workerNextTaskID ++;
  35413. var taskCost = buffer.byteLength;
  35414. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  35415. // references (rather than names) to typed array constructors. These must be
  35416. // serialized before sending them to the worker.
  35417. for ( var attribute in taskConfig.attributeTypes ) {
  35418. var type = taskConfig.attributeTypes[ attribute ];
  35419. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  35420. taskConfig.attributeTypes[ attribute ] = type.name;
  35421. }
  35422. }
  35423. // Obtain a worker and assign a task, and construct a geometry instance
  35424. // when the task completes.
  35425. var geometryPending = this._getWorker( taskID, taskCost )
  35426. .then( ( _worker ) => {
  35427. worker = _worker;
  35428. return new Promise( ( resolve, reject ) => {
  35429. worker._callbacks[ taskID ] = { resolve, reject };
  35430. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  35431. // this.debug();
  35432. } );
  35433. } )
  35434. .then( ( message ) => this._createGeometry( message.geometry ) );
  35435. // Remove task from the task list.
  35436. geometryPending
  35437. .finally( () => {
  35438. if ( worker && taskID ) {
  35439. this._releaseTask( worker, taskID );
  35440. // this.debug();
  35441. }
  35442. } );
  35443. return geometryPending;
  35444. },
  35445. _createGeometry: function ( geometryData ) {
  35446. var geometry = new THREE.BufferGeometry();
  35447. if ( geometryData.index ) {
  35448. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  35449. }
  35450. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  35451. var attribute = geometryData.attributes[ i ];
  35452. var name = attribute.name;
  35453. var array = attribute.array;
  35454. var itemSize = attribute.itemSize;
  35455. geometry.addAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  35456. }
  35457. return geometry;
  35458. },
  35459. _loadLibrary: function ( url, responseType ) {
  35460. var loader = new THREE.FileLoader( this.manager );
  35461. loader.setPath( this.decoderPath );
  35462. loader.setResponseType( responseType );
  35463. return new Promise( ( resolve, reject ) => {
  35464. loader.load( url, resolve, undefined, reject );
  35465. } );
  35466. },
  35467. _initDecoder: function () {
  35468. if ( this.decoderPending ) return this.decoderPending;
  35469. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  35470. var librariesPending = [];
  35471. if ( useJS ) {
  35472. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  35473. } else {
  35474. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  35475. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  35476. }
  35477. this.decoderPending = Promise.all( librariesPending )
  35478. .then( ( libraries ) => {
  35479. var jsContent = libraries[ 0 ];
  35480. if ( ! useJS ) {
  35481. this.decoderConfig.wasmBinary = libraries[ 1 ];
  35482. }
  35483. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  35484. var body = [
  35485. '/* draco decoder */',
  35486. jsContent,
  35487. '',
  35488. '/* worker */',
  35489. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  35490. ].join( '\n' );
  35491. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  35492. } );
  35493. return this.decoderPending;
  35494. },
  35495. _getWorker: function ( taskID, taskCost ) {
  35496. return this._initDecoder().then( () => {
  35497. if ( this.workerPool.length < this.workerLimit ) {
  35498. var worker = new Worker( this.workerSourceURL );
  35499. worker._callbacks = {};
  35500. worker._taskCosts = {};
  35501. worker._taskLoad = 0;
  35502. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  35503. worker.onmessage = function ( e ) {
  35504. var message = e.data;
  35505. switch ( message.type ) {
  35506. case 'decode':
  35507. worker._callbacks[ message.id ].resolve( message );
  35508. break;
  35509. case 'error':
  35510. worker._callbacks[ message.id ].reject( message );
  35511. break;
  35512. default:
  35513. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  35514. }
  35515. };
  35516. this.workerPool.push( worker );
  35517. } else {
  35518. this.workerPool.sort( function ( a, b ) {
  35519. return a._taskLoad > b._taskLoad ? - 1 : 1;
  35520. } );
  35521. }
  35522. var worker = this.workerPool[ this.workerPool.length - 1 ];
  35523. worker._taskCosts[ taskID ] = taskCost;
  35524. worker._taskLoad += taskCost;
  35525. return worker;
  35526. } );
  35527. },
  35528. _releaseTask: function ( worker, taskID ) {
  35529. worker._taskLoad -= worker._taskCosts[ taskID ];
  35530. delete worker._callbacks[ taskID ];
  35531. delete worker._taskCosts[ taskID ];
  35532. },
  35533. debug: function () {
  35534. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  35535. },
  35536. dispose: function () {
  35537. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  35538. this.workerPool[ i ].terminate();
  35539. }
  35540. this.workerPool.length = 0;
  35541. return this;
  35542. }
  35543. } );
  35544. /* WEB WORKER */
  35545. THREE.DRACOLoader.DRACOWorker = function () {
  35546. var decoderConfig;
  35547. var decoderPending;
  35548. onmessage = function ( e ) {
  35549. var message = e.data;
  35550. switch ( message.type ) {
  35551. case 'init':
  35552. decoderConfig = message.decoderConfig;
  35553. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  35554. decoderConfig.onModuleLoaded = function ( draco ) {
  35555. // Module is Promise-like. Wrap before resolving to avoid loop.
  35556. resolve( { draco: draco } );
  35557. };
  35558. DracoDecoderModule( decoderConfig );
  35559. } );
  35560. break;
  35561. case 'decode':
  35562. var buffer = message.buffer;
  35563. var taskConfig = message.taskConfig;
  35564. decoderPending.then( ( module ) => {
  35565. var draco = module.draco;
  35566. var decoder = new draco.Decoder();
  35567. var decoderBuffer = new draco.DecoderBuffer();
  35568. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  35569. try {
  35570. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  35571. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  35572. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  35573. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  35574. } catch ( error ) {
  35575. console.error( error );
  35576. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  35577. } finally {
  35578. draco.destroy( decoderBuffer );
  35579. draco.destroy( decoder );
  35580. }
  35581. } );
  35582. break;
  35583. }
  35584. };
  35585. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  35586. var attributeIDs = taskConfig.attributeIDs;
  35587. var attributeTypes = taskConfig.attributeTypes;
  35588. var dracoGeometry;
  35589. var decodingStatus;
  35590. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  35591. if ( geometryType === draco.TRIANGULAR_MESH ) {
  35592. dracoGeometry = new draco.Mesh();
  35593. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  35594. } else if ( geometryType === draco.POINT_CLOUD ) {
  35595. dracoGeometry = new draco.PointCloud();
  35596. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  35597. } else {
  35598. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  35599. }
  35600. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  35601. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  35602. }
  35603. var geometry = { index: null, attributes: [] };
  35604. // Gather all vertex attributes.
  35605. for ( var attributeName in attributeIDs ) {
  35606. var attributeType = self[ attributeTypes[ attributeName ] ];
  35607. var attribute;
  35608. var attributeID;
  35609. // A Draco file may be created with default vertex attributes, whose attribute IDs
  35610. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  35611. // a Draco file may contain a custom set of attributes, identified by known unique
  35612. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  35613. if ( taskConfig.useUniqueIDs ) {
  35614. attributeID = attributeIDs[ attributeName ];
  35615. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  35616. } else {
  35617. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  35618. if ( attributeID === -1 ) continue;
  35619. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  35620. }
  35621. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  35622. }
  35623. // Add index.
  35624. if ( geometryType === draco.TRIANGULAR_MESH ) {
  35625. // Generate mesh faces.
  35626. var numFaces = dracoGeometry.num_faces();
  35627. var numIndices = numFaces * 3;
  35628. var index = new Uint32Array( numIndices );
  35629. var indexArray = new draco.DracoInt32Array();
  35630. for ( var i = 0; i < numFaces; ++ i ) {
  35631. decoder.GetFaceFromMesh( dracoGeometry, i, indexArray );
  35632. for ( var j = 0; j < 3; ++ j ) {
  35633. index[ i * 3 + j ] = indexArray.GetValue( j );
  35634. }
  35635. }
  35636. geometry.index = { array: index, itemSize: 1 };
  35637. draco.destroy( indexArray );
  35638. }
  35639. draco.destroy( dracoGeometry );
  35640. return geometry;
  35641. }
  35642. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  35643. var numComponents = attribute.num_components();
  35644. var numPoints = dracoGeometry.num_points();
  35645. var numValues = numPoints * numComponents;
  35646. var dracoArray;
  35647. var array;
  35648. switch ( attributeType ) {
  35649. case Float32Array:
  35650. dracoArray = new draco.DracoFloat32Array();
  35651. decoder.GetAttributeFloatForAllPoints( dracoGeometry, attribute, dracoArray );
  35652. array = new Float32Array( numValues );
  35653. break;
  35654. case Int8Array:
  35655. dracoArray = new draco.DracoInt8Array();
  35656. decoder.GetAttributeInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  35657. array = new Int8Array( numValues );
  35658. break;
  35659. case Int16Array:
  35660. dracoArray = new draco.DracoInt16Array();
  35661. decoder.GetAttributeInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  35662. array = new Int16Array( numValues );
  35663. break;
  35664. case Int32Array:
  35665. dracoArray = new draco.DracoInt32Array();
  35666. decoder.GetAttributeInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  35667. array = new Int32Array( numValues );
  35668. break;
  35669. case Uint8Array:
  35670. dracoArray = new draco.DracoUInt8Array();
  35671. decoder.GetAttributeUInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  35672. array = new Uint8Array( numValues );
  35673. break;
  35674. case Uint16Array:
  35675. dracoArray = new draco.DracoUInt16Array();
  35676. decoder.GetAttributeUInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  35677. array = new Uint16Array( numValues );
  35678. break;
  35679. case Uint32Array:
  35680. dracoArray = new draco.DracoUInt32Array();
  35681. decoder.GetAttributeUInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  35682. array = new Uint32Array( numValues );
  35683. break;
  35684. default:
  35685. throw new Error( 'THREE.DRACOLoader: Unexpected attribute type.' );
  35686. }
  35687. for ( var i = 0; i < numValues; i ++ ) {
  35688. array[ i ] = dracoArray.GetValue( i );
  35689. }
  35690. draco.destroy( dracoArray );
  35691. return {
  35692. name: attributeName,
  35693. array: array,
  35694. itemSize: numComponents
  35695. };
  35696. }
  35697. };
  35698. /** Deprecated static methods */
  35699. /** @deprecated */
  35700. THREE.DRACOLoader.setDecoderPath = function () {
  35701. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  35702. };
  35703. /** @deprecated */
  35704. THREE.DRACOLoader.setDecoderConfig = function () {
  35705. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  35706. };
  35707. /** @deprecated */
  35708. THREE.DRACOLoader.releaseDecoderModule = function () {
  35709. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  35710. };
  35711. /** @deprecated */
  35712. THREE.DRACOLoader.getDecoderModule = function () {
  35713. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  35714. };
  35715. },{}],59:[function(_dereq_,module,exports){
  35716. /**
  35717. * @author Rich Tibbett / https://github.com/richtr
  35718. * @author mrdoob / http://mrdoob.com/
  35719. * @author Tony Parisi / http://www.tonyparisi.com/
  35720. * @author Takahiro / https://github.com/takahirox
  35721. * @author Don McCurdy / https://www.donmccurdy.com
  35722. */
  35723. THREE.GLTFLoader = ( function () {
  35724. function GLTFLoader( manager ) {
  35725. THREE.Loader.call( this, manager );
  35726. this.dracoLoader = null;
  35727. this.ddsLoader = null;
  35728. }
  35729. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  35730. constructor: GLTFLoader,
  35731. load: function ( url, onLoad, onProgress, onError ) {
  35732. var scope = this;
  35733. var resourcePath;
  35734. if ( this.resourcePath !== '' ) {
  35735. resourcePath = this.resourcePath;
  35736. } else if ( this.path !== '' ) {
  35737. resourcePath = this.path;
  35738. } else {
  35739. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  35740. }
  35741. // Tells the LoadingManager to track an extra item, which resolves after
  35742. // the model is fully loaded. This means the count of items loaded will
  35743. // be incorrect, but ensures manager.onLoad() does not fire early.
  35744. scope.manager.itemStart( url );
  35745. var _onError = function ( e ) {
  35746. if ( onError ) {
  35747. onError( e );
  35748. } else {
  35749. console.error( e );
  35750. }
  35751. scope.manager.itemError( url );
  35752. scope.manager.itemEnd( url );
  35753. };
  35754. var loader = new THREE.FileLoader( scope.manager );
  35755. loader.setPath( this.path );
  35756. loader.setResponseType( 'arraybuffer' );
  35757. if ( scope.crossOrigin === 'use-credentials' ) {
  35758. loader.setWithCredentials( true );
  35759. }
  35760. loader.load( url, function ( data ) {
  35761. try {
  35762. scope.parse( data, resourcePath, function ( gltf ) {
  35763. onLoad( gltf );
  35764. scope.manager.itemEnd( url );
  35765. }, _onError );
  35766. } catch ( e ) {
  35767. _onError( e );
  35768. }
  35769. }, onProgress, _onError );
  35770. },
  35771. setDRACOLoader: function ( dracoLoader ) {
  35772. this.dracoLoader = dracoLoader;
  35773. return this;
  35774. },
  35775. setDDSLoader: function ( ddsLoader ) {
  35776. this.ddsLoader = ddsLoader;
  35777. return this;
  35778. },
  35779. parse: function ( data, path, onLoad, onError ) {
  35780. var content;
  35781. var extensions = {};
  35782. if ( typeof data === 'string' ) {
  35783. content = data;
  35784. } else {
  35785. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  35786. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  35787. try {
  35788. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  35789. } catch ( error ) {
  35790. if ( onError ) onError( error );
  35791. return;
  35792. }
  35793. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  35794. } else {
  35795. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  35796. }
  35797. }
  35798. var json = JSON.parse( content );
  35799. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  35800. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  35801. return;
  35802. }
  35803. if ( json.extensionsUsed ) {
  35804. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  35805. var extensionName = json.extensionsUsed[ i ];
  35806. var extensionsRequired = json.extensionsRequired || [];
  35807. switch ( extensionName ) {
  35808. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  35809. extensions[ extensionName ] = new GLTFLightsExtension( json );
  35810. break;
  35811. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  35812. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  35813. break;
  35814. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  35815. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  35816. break;
  35817. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  35818. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  35819. break;
  35820. case EXTENSIONS.MSFT_TEXTURE_DDS:
  35821. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader );
  35822. break;
  35823. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  35824. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension();
  35825. break;
  35826. default:
  35827. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  35828. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  35829. }
  35830. }
  35831. }
  35832. }
  35833. var parser = new GLTFParser( json, extensions, {
  35834. path: path || this.resourcePath || '',
  35835. crossOrigin: this.crossOrigin,
  35836. manager: this.manager
  35837. } );
  35838. parser.parse( onLoad, onError );
  35839. }
  35840. } );
  35841. /* GLTFREGISTRY */
  35842. function GLTFRegistry() {
  35843. var objects = {};
  35844. return {
  35845. get: function ( key ) {
  35846. return objects[ key ];
  35847. },
  35848. add: function ( key, object ) {
  35849. objects[ key ] = object;
  35850. },
  35851. remove: function ( key ) {
  35852. delete objects[ key ];
  35853. },
  35854. removeAll: function () {
  35855. objects = {};
  35856. }
  35857. };
  35858. }
  35859. /*********************************/
  35860. /********** EXTENSIONS ***********/
  35861. /*********************************/
  35862. var EXTENSIONS = {
  35863. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  35864. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  35865. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  35866. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  35867. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  35868. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  35869. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  35870. };
  35871. /**
  35872. * DDS Texture Extension
  35873. *
  35874. * Specification:
  35875. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  35876. *
  35877. */
  35878. function GLTFTextureDDSExtension( ddsLoader ) {
  35879. if ( ! ddsLoader ) {
  35880. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  35881. }
  35882. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  35883. this.ddsLoader = ddsLoader;
  35884. }
  35885. /**
  35886. * Lights Extension
  35887. *
  35888. * Specification: PENDING
  35889. */
  35890. function GLTFLightsExtension( json ) {
  35891. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  35892. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  35893. this.lightDefs = extension.lights || [];
  35894. }
  35895. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  35896. var lightDef = this.lightDefs[ lightIndex ];
  35897. var lightNode;
  35898. var color = new THREE.Color( 0xffffff );
  35899. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  35900. var range = lightDef.range !== undefined ? lightDef.range : 0;
  35901. switch ( lightDef.type ) {
  35902. case 'directional':
  35903. lightNode = new THREE.DirectionalLight( color );
  35904. lightNode.target.position.set( 0, 0, - 1 );
  35905. lightNode.add( lightNode.target );
  35906. break;
  35907. case 'point':
  35908. lightNode = new THREE.PointLight( color );
  35909. lightNode.distance = range;
  35910. break;
  35911. case 'spot':
  35912. lightNode = new THREE.SpotLight( color );
  35913. lightNode.distance = range;
  35914. // Handle spotlight properties.
  35915. lightDef.spot = lightDef.spot || {};
  35916. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  35917. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  35918. lightNode.angle = lightDef.spot.outerConeAngle;
  35919. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  35920. lightNode.target.position.set( 0, 0, - 1 );
  35921. lightNode.add( lightNode.target );
  35922. break;
  35923. default:
  35924. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  35925. }
  35926. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  35927. // here, because node-level parsing will only override position if explicitly specified.
  35928. lightNode.position.set( 0, 0, 0 );
  35929. lightNode.decay = 2;
  35930. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  35931. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  35932. return Promise.resolve( lightNode );
  35933. };
  35934. /**
  35935. * Unlit Materials Extension (pending)
  35936. *
  35937. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  35938. */
  35939. function GLTFMaterialsUnlitExtension() {
  35940. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  35941. }
  35942. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  35943. return THREE.MeshBasicMaterial;
  35944. };
  35945. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  35946. var pending = [];
  35947. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35948. materialParams.opacity = 1.0;
  35949. var metallicRoughness = materialDef.pbrMetallicRoughness;
  35950. if ( metallicRoughness ) {
  35951. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35952. var array = metallicRoughness.baseColorFactor;
  35953. materialParams.color.fromArray( array );
  35954. materialParams.opacity = array[ 3 ];
  35955. }
  35956. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35957. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  35958. }
  35959. }
  35960. return Promise.all( pending );
  35961. };
  35962. /* BINARY EXTENSION */
  35963. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  35964. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  35965. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  35966. function GLTFBinaryExtension( data ) {
  35967. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  35968. this.content = null;
  35969. this.body = null;
  35970. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  35971. this.header = {
  35972. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  35973. version: headerView.getUint32( 4, true ),
  35974. length: headerView.getUint32( 8, true )
  35975. };
  35976. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  35977. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  35978. } else if ( this.header.version < 2.0 ) {
  35979. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  35980. }
  35981. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  35982. var chunkIndex = 0;
  35983. while ( chunkIndex < chunkView.byteLength ) {
  35984. var chunkLength = chunkView.getUint32( chunkIndex, true );
  35985. chunkIndex += 4;
  35986. var chunkType = chunkView.getUint32( chunkIndex, true );
  35987. chunkIndex += 4;
  35988. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  35989. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  35990. this.content = THREE.LoaderUtils.decodeText( contentArray );
  35991. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  35992. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  35993. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  35994. }
  35995. // Clients must ignore chunks with unknown types.
  35996. chunkIndex += chunkLength;
  35997. }
  35998. if ( this.content === null ) {
  35999. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  36000. }
  36001. }
  36002. /**
  36003. * DRACO Mesh Compression Extension
  36004. *
  36005. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  36006. */
  36007. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  36008. if ( ! dracoLoader ) {
  36009. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  36010. }
  36011. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  36012. this.json = json;
  36013. this.dracoLoader = dracoLoader;
  36014. }
  36015. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  36016. var json = this.json;
  36017. var dracoLoader = this.dracoLoader;
  36018. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  36019. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  36020. var threeAttributeMap = {};
  36021. var attributeNormalizedMap = {};
  36022. var attributeTypeMap = {};
  36023. for ( var attributeName in gltfAttributeMap ) {
  36024. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  36025. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  36026. }
  36027. for ( attributeName in primitive.attributes ) {
  36028. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  36029. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  36030. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  36031. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  36032. attributeTypeMap[ threeAttributeName ] = componentType;
  36033. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  36034. }
  36035. }
  36036. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  36037. return new Promise( function ( resolve ) {
  36038. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  36039. for ( var attributeName in geometry.attributes ) {
  36040. var attribute = geometry.attributes[ attributeName ];
  36041. var normalized = attributeNormalizedMap[ attributeName ];
  36042. if ( normalized !== undefined ) attribute.normalized = normalized;
  36043. }
  36044. resolve( geometry );
  36045. }, threeAttributeMap, attributeTypeMap );
  36046. } );
  36047. } );
  36048. };
  36049. /**
  36050. * Texture Transform Extension
  36051. *
  36052. * Specification:
  36053. */
  36054. function GLTFTextureTransformExtension() {
  36055. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  36056. }
  36057. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  36058. texture = texture.clone();
  36059. if ( transform.offset !== undefined ) {
  36060. texture.offset.fromArray( transform.offset );
  36061. }
  36062. if ( transform.rotation !== undefined ) {
  36063. texture.rotation = transform.rotation;
  36064. }
  36065. if ( transform.scale !== undefined ) {
  36066. texture.repeat.fromArray( transform.scale );
  36067. }
  36068. if ( transform.texCoord !== undefined ) {
  36069. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  36070. }
  36071. texture.needsUpdate = true;
  36072. return texture;
  36073. };
  36074. /**
  36075. * Specular-Glossiness Extension
  36076. *
  36077. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  36078. */
  36079. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  36080. return {
  36081. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  36082. specularGlossinessParams: [
  36083. 'color',
  36084. 'map',
  36085. 'lightMap',
  36086. 'lightMapIntensity',
  36087. 'aoMap',
  36088. 'aoMapIntensity',
  36089. 'emissive',
  36090. 'emissiveIntensity',
  36091. 'emissiveMap',
  36092. 'bumpMap',
  36093. 'bumpScale',
  36094. 'normalMap',
  36095. 'displacementMap',
  36096. 'displacementScale',
  36097. 'displacementBias',
  36098. 'specularMap',
  36099. 'specular',
  36100. 'glossinessMap',
  36101. 'glossiness',
  36102. 'alphaMap',
  36103. 'envMap',
  36104. 'envMapIntensity',
  36105. 'refractionRatio',
  36106. ],
  36107. getMaterialType: function () {
  36108. return THREE.ShaderMaterial;
  36109. },
  36110. extendParams: function ( materialParams, materialDef, parser ) {
  36111. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  36112. var shader = THREE.ShaderLib[ 'standard' ];
  36113. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  36114. var specularMapParsFragmentChunk = [
  36115. '#ifdef USE_SPECULARMAP',
  36116. ' uniform sampler2D specularMap;',
  36117. '#endif'
  36118. ].join( '\n' );
  36119. var glossinessMapParsFragmentChunk = [
  36120. '#ifdef USE_GLOSSINESSMAP',
  36121. ' uniform sampler2D glossinessMap;',
  36122. '#endif'
  36123. ].join( '\n' );
  36124. var specularMapFragmentChunk = [
  36125. 'vec3 specularFactor = specular;',
  36126. '#ifdef USE_SPECULARMAP',
  36127. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  36128. ' texelSpecular = sRGBToLinear( texelSpecular );',
  36129. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  36130. ' specularFactor *= texelSpecular.rgb;',
  36131. '#endif'
  36132. ].join( '\n' );
  36133. var glossinessMapFragmentChunk = [
  36134. 'float glossinessFactor = glossiness;',
  36135. '#ifdef USE_GLOSSINESSMAP',
  36136. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  36137. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  36138. ' glossinessFactor *= texelGlossiness.a;',
  36139. '#endif'
  36140. ].join( '\n' );
  36141. var lightPhysicalFragmentChunk = [
  36142. 'PhysicalMaterial material;',
  36143. 'material.diffuseColor = diffuseColor.rgb;',
  36144. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  36145. 'material.specularColor = specularFactor.rgb;',
  36146. ].join( '\n' );
  36147. var fragmentShader = shader.fragmentShader
  36148. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  36149. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  36150. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  36151. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  36152. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  36153. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  36154. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  36155. delete uniforms.roughness;
  36156. delete uniforms.metalness;
  36157. delete uniforms.roughnessMap;
  36158. delete uniforms.metalnessMap;
  36159. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  36160. uniforms.glossiness = { value: 0.5 };
  36161. uniforms.specularMap = { value: null };
  36162. uniforms.glossinessMap = { value: null };
  36163. materialParams.vertexShader = shader.vertexShader;
  36164. materialParams.fragmentShader = fragmentShader;
  36165. materialParams.uniforms = uniforms;
  36166. materialParams.defines = { 'STANDARD': '' };
  36167. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  36168. materialParams.opacity = 1.0;
  36169. var pending = [];
  36170. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  36171. var array = pbrSpecularGlossiness.diffuseFactor;
  36172. materialParams.color.fromArray( array );
  36173. materialParams.opacity = array[ 3 ];
  36174. }
  36175. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  36176. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  36177. }
  36178. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  36179. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  36180. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  36181. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  36182. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  36183. }
  36184. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  36185. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  36186. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  36187. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  36188. }
  36189. return Promise.all( pending );
  36190. },
  36191. createMaterial: function ( params ) {
  36192. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  36193. var material = new THREE.ShaderMaterial( {
  36194. defines: params.defines,
  36195. vertexShader: params.vertexShader,
  36196. fragmentShader: params.fragmentShader,
  36197. uniforms: params.uniforms,
  36198. fog: true,
  36199. lights: true,
  36200. opacity: params.opacity,
  36201. transparent: params.transparent
  36202. } );
  36203. material.isGLTFSpecularGlossinessMaterial = true;
  36204. material.color = params.color;
  36205. material.map = params.map === undefined ? null : params.map;
  36206. material.lightMap = null;
  36207. material.lightMapIntensity = 1.0;
  36208. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  36209. material.aoMapIntensity = 1.0;
  36210. material.emissive = params.emissive;
  36211. material.emissiveIntensity = 1.0;
  36212. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  36213. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  36214. material.bumpScale = 1;
  36215. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  36216. if ( params.normalScale ) material.normalScale = params.normalScale;
  36217. material.displacementMap = null;
  36218. material.displacementScale = 1;
  36219. material.displacementBias = 0;
  36220. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  36221. material.specular = params.specular;
  36222. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  36223. material.glossiness = params.glossiness;
  36224. material.alphaMap = null;
  36225. material.envMap = params.envMap === undefined ? null : params.envMap;
  36226. material.envMapIntensity = 1.0;
  36227. material.refractionRatio = 0.98;
  36228. material.extensions.derivatives = true;
  36229. return material;
  36230. },
  36231. /**
  36232. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  36233. * copy only properties it knows about or inherits, and misses many properties that would
  36234. * normally be defined by MeshStandardMaterial.
  36235. *
  36236. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  36237. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  36238. * AND also updating `.onBeforeRender` on the parent mesh.
  36239. *
  36240. * @param {THREE.ShaderMaterial} source
  36241. * @return {THREE.ShaderMaterial}
  36242. */
  36243. cloneMaterial: function ( source ) {
  36244. var target = source.clone();
  36245. target.isGLTFSpecularGlossinessMaterial = true;
  36246. var params = this.specularGlossinessParams;
  36247. for ( var i = 0, il = params.length; i < il; i ++ ) {
  36248. var value = source[ params[ i ] ];
  36249. target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value;
  36250. }
  36251. return target;
  36252. },
  36253. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  36254. refreshUniforms: function ( renderer, scene, camera, geometry, material ) {
  36255. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  36256. return;
  36257. }
  36258. var uniforms = material.uniforms;
  36259. var defines = material.defines;
  36260. uniforms.opacity.value = material.opacity;
  36261. uniforms.diffuse.value.copy( material.color );
  36262. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  36263. uniforms.map.value = material.map;
  36264. uniforms.specularMap.value = material.specularMap;
  36265. uniforms.alphaMap.value = material.alphaMap;
  36266. uniforms.lightMap.value = material.lightMap;
  36267. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  36268. uniforms.aoMap.value = material.aoMap;
  36269. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  36270. // uv repeat and offset setting priorities
  36271. // 1. color map
  36272. // 2. specular map
  36273. // 3. normal map
  36274. // 4. bump map
  36275. // 5. alpha map
  36276. // 6. emissive map
  36277. var uvScaleMap;
  36278. if ( material.map ) {
  36279. uvScaleMap = material.map;
  36280. } else if ( material.specularMap ) {
  36281. uvScaleMap = material.specularMap;
  36282. } else if ( material.displacementMap ) {
  36283. uvScaleMap = material.displacementMap;
  36284. } else if ( material.normalMap ) {
  36285. uvScaleMap = material.normalMap;
  36286. } else if ( material.bumpMap ) {
  36287. uvScaleMap = material.bumpMap;
  36288. } else if ( material.glossinessMap ) {
  36289. uvScaleMap = material.glossinessMap;
  36290. } else if ( material.alphaMap ) {
  36291. uvScaleMap = material.alphaMap;
  36292. } else if ( material.emissiveMap ) {
  36293. uvScaleMap = material.emissiveMap;
  36294. }
  36295. if ( uvScaleMap !== undefined ) {
  36296. // backwards compatibility
  36297. if ( uvScaleMap.isWebGLRenderTarget ) {
  36298. uvScaleMap = uvScaleMap.texture;
  36299. }
  36300. if ( uvScaleMap.matrixAutoUpdate === true ) {
  36301. uvScaleMap.updateMatrix();
  36302. }
  36303. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  36304. }
  36305. if ( material.envMap ) {
  36306. uniforms.envMap.value = material.envMap;
  36307. uniforms.envMapIntensity.value = material.envMapIntensity;
  36308. // don't flip CubeTexture envMaps, flip everything else:
  36309. // WebGLRenderTargetCube will be flipped for backwards compatibility
  36310. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  36311. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  36312. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  36313. uniforms.reflectivity.value = material.reflectivity;
  36314. uniforms.refractionRatio.value = material.refractionRatio;
  36315. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  36316. }
  36317. uniforms.specular.value.copy( material.specular );
  36318. uniforms.glossiness.value = material.glossiness;
  36319. uniforms.glossinessMap.value = material.glossinessMap;
  36320. uniforms.emissiveMap.value = material.emissiveMap;
  36321. uniforms.bumpMap.value = material.bumpMap;
  36322. uniforms.normalMap.value = material.normalMap;
  36323. uniforms.displacementMap.value = material.displacementMap;
  36324. uniforms.displacementScale.value = material.displacementScale;
  36325. uniforms.displacementBias.value = material.displacementBias;
  36326. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  36327. defines.USE_GLOSSINESSMAP = '';
  36328. // set USE_ROUGHNESSMAP to enable vUv
  36329. defines.USE_ROUGHNESSMAP = '';
  36330. }
  36331. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  36332. delete defines.USE_GLOSSINESSMAP;
  36333. delete defines.USE_ROUGHNESSMAP;
  36334. }
  36335. }
  36336. };
  36337. }
  36338. /*********************************/
  36339. /********** INTERPOLATION ********/
  36340. /*********************************/
  36341. // Spline Interpolation
  36342. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  36343. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  36344. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  36345. }
  36346. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  36347. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  36348. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  36349. // Copies a sample value to the result buffer. See description of glTF
  36350. // CUBICSPLINE values layout in interpolate_() function below.
  36351. var result = this.resultBuffer,
  36352. values = this.sampleValues,
  36353. valueSize = this.valueSize,
  36354. offset = index * valueSize * 3 + valueSize;
  36355. for ( var i = 0; i !== valueSize; i ++ ) {
  36356. result[ i ] = values[ offset + i ];
  36357. }
  36358. return result;
  36359. };
  36360. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36361. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36362. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  36363. var result = this.resultBuffer;
  36364. var values = this.sampleValues;
  36365. var stride = this.valueSize;
  36366. var stride2 = stride * 2;
  36367. var stride3 = stride * 3;
  36368. var td = t1 - t0;
  36369. var p = ( t - t0 ) / td;
  36370. var pp = p * p;
  36371. var ppp = pp * p;
  36372. var offset1 = i1 * stride3;
  36373. var offset0 = offset1 - stride3;
  36374. var s2 = - 2 * ppp + 3 * pp;
  36375. var s3 = ppp - pp;
  36376. var s0 = 1 - s2;
  36377. var s1 = s3 - pp + p;
  36378. // Layout of keyframe output values for CUBICSPLINE animations:
  36379. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  36380. for ( var i = 0; i !== stride; i ++ ) {
  36381. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  36382. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  36383. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  36384. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  36385. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  36386. }
  36387. return result;
  36388. };
  36389. /*********************************/
  36390. /********** INTERNALS ************/
  36391. /*********************************/
  36392. /* CONSTANTS */
  36393. var WEBGL_CONSTANTS = {
  36394. FLOAT: 5126,
  36395. //FLOAT_MAT2: 35674,
  36396. FLOAT_MAT3: 35675,
  36397. FLOAT_MAT4: 35676,
  36398. FLOAT_VEC2: 35664,
  36399. FLOAT_VEC3: 35665,
  36400. FLOAT_VEC4: 35666,
  36401. LINEAR: 9729,
  36402. REPEAT: 10497,
  36403. SAMPLER_2D: 35678,
  36404. POINTS: 0,
  36405. LINES: 1,
  36406. LINE_LOOP: 2,
  36407. LINE_STRIP: 3,
  36408. TRIANGLES: 4,
  36409. TRIANGLE_STRIP: 5,
  36410. TRIANGLE_FAN: 6,
  36411. UNSIGNED_BYTE: 5121,
  36412. UNSIGNED_SHORT: 5123
  36413. };
  36414. var WEBGL_COMPONENT_TYPES = {
  36415. 5120: Int8Array,
  36416. 5121: Uint8Array,
  36417. 5122: Int16Array,
  36418. 5123: Uint16Array,
  36419. 5125: Uint32Array,
  36420. 5126: Float32Array
  36421. };
  36422. var WEBGL_FILTERS = {
  36423. 9728: THREE.NearestFilter,
  36424. 9729: THREE.LinearFilter,
  36425. 9984: THREE.NearestMipmapNearestFilter,
  36426. 9985: THREE.LinearMipmapNearestFilter,
  36427. 9986: THREE.NearestMipmapLinearFilter,
  36428. 9987: THREE.LinearMipmapLinearFilter
  36429. };
  36430. var WEBGL_WRAPPINGS = {
  36431. 33071: THREE.ClampToEdgeWrapping,
  36432. 33648: THREE.MirroredRepeatWrapping,
  36433. 10497: THREE.RepeatWrapping
  36434. };
  36435. var WEBGL_TYPE_SIZES = {
  36436. 'SCALAR': 1,
  36437. 'VEC2': 2,
  36438. 'VEC3': 3,
  36439. 'VEC4': 4,
  36440. 'MAT2': 4,
  36441. 'MAT3': 9,
  36442. 'MAT4': 16
  36443. };
  36444. var ATTRIBUTES = {
  36445. POSITION: 'position',
  36446. NORMAL: 'normal',
  36447. TANGENT: 'tangent',
  36448. TEXCOORD_0: 'uv',
  36449. TEXCOORD_1: 'uv2',
  36450. COLOR_0: 'color',
  36451. WEIGHTS_0: 'skinWeight',
  36452. JOINTS_0: 'skinIndex',
  36453. };
  36454. var PATH_PROPERTIES = {
  36455. scale: 'scale',
  36456. translation: 'position',
  36457. rotation: 'quaternion',
  36458. weights: 'morphTargetInfluences'
  36459. };
  36460. var INTERPOLATION = {
  36461. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  36462. // keyframe track will be initialized with a default interpolation type, then modified.
  36463. LINEAR: THREE.InterpolateLinear,
  36464. STEP: THREE.InterpolateDiscrete
  36465. };
  36466. var ALPHA_MODES = {
  36467. OPAQUE: 'OPAQUE',
  36468. MASK: 'MASK',
  36469. BLEND: 'BLEND'
  36470. };
  36471. var MIME_TYPE_FORMATS = {
  36472. 'image/png': THREE.RGBAFormat,
  36473. 'image/jpeg': THREE.RGBFormat
  36474. };
  36475. /* UTILITY FUNCTIONS */
  36476. function resolveURL( url, path ) {
  36477. // Invalid URL
  36478. if ( typeof url !== 'string' || url === '' ) return '';
  36479. // Host Relative URL
  36480. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  36481. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  36482. }
  36483. // Absolute URL http://,https://,//
  36484. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  36485. // Data URI
  36486. if ( /^data:.*,.*$/i.test( url ) ) return url;
  36487. // Blob URL
  36488. if ( /^blob:.*$/i.test( url ) ) return url;
  36489. // Relative URL
  36490. return path + url;
  36491. }
  36492. var defaultMaterial;
  36493. /**
  36494. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  36495. */
  36496. function createDefaultMaterial() {
  36497. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  36498. color: 0xFFFFFF,
  36499. emissive: 0x000000,
  36500. metalness: 1,
  36501. roughness: 1,
  36502. transparent: false,
  36503. depthTest: true,
  36504. side: THREE.FrontSide
  36505. } );
  36506. return defaultMaterial;
  36507. }
  36508. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  36509. // Add unknown glTF extensions to an object's userData.
  36510. for ( var name in objectDef.extensions ) {
  36511. if ( knownExtensions[ name ] === undefined ) {
  36512. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  36513. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  36514. }
  36515. }
  36516. }
  36517. /**
  36518. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  36519. * @param {GLTF.definition} gltfDef
  36520. */
  36521. function assignExtrasToUserData( object, gltfDef ) {
  36522. if ( gltfDef.extras !== undefined ) {
  36523. if ( typeof gltfDef.extras === 'object' ) {
  36524. Object.assign( object.userData, gltfDef.extras );
  36525. } else {
  36526. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  36527. }
  36528. }
  36529. }
  36530. /**
  36531. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  36532. *
  36533. * @param {THREE.BufferGeometry} geometry
  36534. * @param {Array<GLTF.Target>} targets
  36535. * @param {GLTFParser} parser
  36536. * @return {Promise<THREE.BufferGeometry>}
  36537. */
  36538. function addMorphTargets( geometry, targets, parser ) {
  36539. var hasMorphPosition = false;
  36540. var hasMorphNormal = false;
  36541. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36542. var target = targets[ i ];
  36543. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  36544. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  36545. if ( hasMorphPosition && hasMorphNormal ) break;
  36546. }
  36547. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  36548. var pendingPositionAccessors = [];
  36549. var pendingNormalAccessors = [];
  36550. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36551. var target = targets[ i ];
  36552. if ( hasMorphPosition ) {
  36553. var pendingAccessor = target.POSITION !== undefined
  36554. ? parser.getDependency( 'accessor', target.POSITION )
  36555. : geometry.attributes.position;
  36556. pendingPositionAccessors.push( pendingAccessor );
  36557. }
  36558. if ( hasMorphNormal ) {
  36559. var pendingAccessor = target.NORMAL !== undefined
  36560. ? parser.getDependency( 'accessor', target.NORMAL )
  36561. : geometry.attributes.normal;
  36562. pendingNormalAccessors.push( pendingAccessor );
  36563. }
  36564. }
  36565. return Promise.all( [
  36566. Promise.all( pendingPositionAccessors ),
  36567. Promise.all( pendingNormalAccessors )
  36568. ] ).then( function ( accessors ) {
  36569. var morphPositions = accessors[ 0 ];
  36570. var morphNormals = accessors[ 1 ];
  36571. // Clone morph target accessors before modifying them.
  36572. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  36573. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  36574. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  36575. }
  36576. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  36577. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  36578. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  36579. }
  36580. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36581. var target = targets[ i ];
  36582. var attributeName = 'morphTarget' + i;
  36583. if ( hasMorphPosition ) {
  36584. // Three.js morph position is absolute value. The formula is
  36585. // basePosition
  36586. // + weight0 * ( morphPosition0 - basePosition )
  36587. // + weight1 * ( morphPosition1 - basePosition )
  36588. // ...
  36589. // while the glTF one is relative
  36590. // basePosition
  36591. // + weight0 * glTFmorphPosition0
  36592. // + weight1 * glTFmorphPosition1
  36593. // ...
  36594. // then we need to convert from relative to absolute here.
  36595. if ( target.POSITION !== undefined ) {
  36596. var positionAttribute = morphPositions[ i ];
  36597. positionAttribute.name = attributeName;
  36598. var position = geometry.attributes.position;
  36599. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  36600. positionAttribute.setXYZ(
  36601. j,
  36602. positionAttribute.getX( j ) + position.getX( j ),
  36603. positionAttribute.getY( j ) + position.getY( j ),
  36604. positionAttribute.getZ( j ) + position.getZ( j )
  36605. );
  36606. }
  36607. }
  36608. }
  36609. if ( hasMorphNormal ) {
  36610. // see target.POSITION's comment
  36611. if ( target.NORMAL !== undefined ) {
  36612. var normalAttribute = morphNormals[ i ];
  36613. normalAttribute.name = attributeName;
  36614. var normal = geometry.attributes.normal;
  36615. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  36616. normalAttribute.setXYZ(
  36617. j,
  36618. normalAttribute.getX( j ) + normal.getX( j ),
  36619. normalAttribute.getY( j ) + normal.getY( j ),
  36620. normalAttribute.getZ( j ) + normal.getZ( j )
  36621. );
  36622. }
  36623. }
  36624. }
  36625. }
  36626. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  36627. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  36628. return geometry;
  36629. } );
  36630. }
  36631. /**
  36632. * @param {THREE.Mesh} mesh
  36633. * @param {GLTF.Mesh} meshDef
  36634. */
  36635. function updateMorphTargets( mesh, meshDef ) {
  36636. mesh.updateMorphTargets();
  36637. if ( meshDef.weights !== undefined ) {
  36638. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  36639. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  36640. }
  36641. }
  36642. // .extras has user-defined data, so check that .extras.targetNames is an array.
  36643. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  36644. var targetNames = meshDef.extras.targetNames;
  36645. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  36646. mesh.morphTargetDictionary = {};
  36647. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  36648. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  36649. }
  36650. } else {
  36651. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  36652. }
  36653. }
  36654. }
  36655. function createPrimitiveKey( primitiveDef ) {
  36656. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  36657. var geometryKey;
  36658. if ( dracoExtension ) {
  36659. geometryKey = 'draco:' + dracoExtension.bufferView
  36660. + ':' + dracoExtension.indices
  36661. + ':' + createAttributesKey( dracoExtension.attributes );
  36662. } else {
  36663. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  36664. }
  36665. return geometryKey;
  36666. }
  36667. function createAttributesKey( attributes ) {
  36668. var attributesKey = '';
  36669. var keys = Object.keys( attributes ).sort();
  36670. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  36671. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  36672. }
  36673. return attributesKey;
  36674. }
  36675. function cloneBufferAttribute( attribute ) {
  36676. if ( attribute.isInterleavedBufferAttribute ) {
  36677. var count = attribute.count;
  36678. var itemSize = attribute.itemSize;
  36679. var array = attribute.array.slice( 0, count * itemSize );
  36680. for ( var i = 0, j = 0; i < count; ++ i ) {
  36681. array[ j ++ ] = attribute.getX( i );
  36682. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  36683. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  36684. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  36685. }
  36686. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  36687. }
  36688. return attribute.clone();
  36689. }
  36690. /* GLTF PARSER */
  36691. function GLTFParser( json, extensions, options ) {
  36692. this.json = json || {};
  36693. this.extensions = extensions || {};
  36694. this.options = options || {};
  36695. // loader object cache
  36696. this.cache = new GLTFRegistry();
  36697. // BufferGeometry caching
  36698. this.primitiveCache = {};
  36699. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  36700. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  36701. this.fileLoader = new THREE.FileLoader( this.options.manager );
  36702. this.fileLoader.setResponseType( 'arraybuffer' );
  36703. if ( this.options.crossOrigin === 'use-credentials' ) {
  36704. this.fileLoader.setWithCredentials( true );
  36705. }
  36706. }
  36707. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  36708. var parser = this;
  36709. var json = this.json;
  36710. var extensions = this.extensions;
  36711. // Clear the loader cache
  36712. this.cache.removeAll();
  36713. // Mark the special nodes/meshes in json for efficient parse
  36714. this.markDefs();
  36715. Promise.all( [
  36716. this.getDependencies( 'scene' ),
  36717. this.getDependencies( 'animation' ),
  36718. this.getDependencies( 'camera' ),
  36719. ] ).then( function ( dependencies ) {
  36720. var result = {
  36721. scene: dependencies[ 0 ][ json.scene || 0 ],
  36722. scenes: dependencies[ 0 ],
  36723. animations: dependencies[ 1 ],
  36724. cameras: dependencies[ 2 ],
  36725. asset: json.asset,
  36726. parser: parser,
  36727. userData: {}
  36728. };
  36729. addUnknownExtensionsToUserData( extensions, result, json );
  36730. assignExtrasToUserData( result, json );
  36731. onLoad( result );
  36732. } ).catch( onError );
  36733. };
  36734. /**
  36735. * Marks the special nodes/meshes in json for efficient parse.
  36736. */
  36737. GLTFParser.prototype.markDefs = function () {
  36738. var nodeDefs = this.json.nodes || [];
  36739. var skinDefs = this.json.skins || [];
  36740. var meshDefs = this.json.meshes || [];
  36741. var meshReferences = {};
  36742. var meshUses = {};
  36743. // Nothing in the node definition indicates whether it is a Bone or an
  36744. // Object3D. Use the skins' joint references to mark bones.
  36745. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  36746. var joints = skinDefs[ skinIndex ].joints;
  36747. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  36748. nodeDefs[ joints[ i ] ].isBone = true;
  36749. }
  36750. }
  36751. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  36752. // avoid having more than one THREE.Mesh with the same name, count
  36753. // references and rename instances below.
  36754. //
  36755. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  36756. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  36757. var nodeDef = nodeDefs[ nodeIndex ];
  36758. if ( nodeDef.mesh !== undefined ) {
  36759. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  36760. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  36761. }
  36762. meshReferences[ nodeDef.mesh ] ++;
  36763. // Nothing in the mesh definition indicates whether it is
  36764. // a SkinnedMesh or Mesh. Use the node's mesh reference
  36765. // to mark SkinnedMesh if node has skin.
  36766. if ( nodeDef.skin !== undefined ) {
  36767. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  36768. }
  36769. }
  36770. }
  36771. this.json.meshReferences = meshReferences;
  36772. this.json.meshUses = meshUses;
  36773. };
  36774. /**
  36775. * Requests the specified dependency asynchronously, with caching.
  36776. * @param {string} type
  36777. * @param {number} index
  36778. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  36779. */
  36780. GLTFParser.prototype.getDependency = function ( type, index ) {
  36781. var cacheKey = type + ':' + index;
  36782. var dependency = this.cache.get( cacheKey );
  36783. if ( ! dependency ) {
  36784. switch ( type ) {
  36785. case 'scene':
  36786. dependency = this.loadScene( index );
  36787. break;
  36788. case 'node':
  36789. dependency = this.loadNode( index );
  36790. break;
  36791. case 'mesh':
  36792. dependency = this.loadMesh( index );
  36793. break;
  36794. case 'accessor':
  36795. dependency = this.loadAccessor( index );
  36796. break;
  36797. case 'bufferView':
  36798. dependency = this.loadBufferView( index );
  36799. break;
  36800. case 'buffer':
  36801. dependency = this.loadBuffer( index );
  36802. break;
  36803. case 'material':
  36804. dependency = this.loadMaterial( index );
  36805. break;
  36806. case 'texture':
  36807. dependency = this.loadTexture( index );
  36808. break;
  36809. case 'skin':
  36810. dependency = this.loadSkin( index );
  36811. break;
  36812. case 'animation':
  36813. dependency = this.loadAnimation( index );
  36814. break;
  36815. case 'camera':
  36816. dependency = this.loadCamera( index );
  36817. break;
  36818. case 'light':
  36819. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  36820. break;
  36821. default:
  36822. throw new Error( 'Unknown type: ' + type );
  36823. }
  36824. this.cache.add( cacheKey, dependency );
  36825. }
  36826. return dependency;
  36827. };
  36828. /**
  36829. * Requests all dependencies of the specified type asynchronously, with caching.
  36830. * @param {string} type
  36831. * @return {Promise<Array<Object>>}
  36832. */
  36833. GLTFParser.prototype.getDependencies = function ( type ) {
  36834. var dependencies = this.cache.get( type );
  36835. if ( ! dependencies ) {
  36836. var parser = this;
  36837. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  36838. dependencies = Promise.all( defs.map( function ( def, index ) {
  36839. return parser.getDependency( type, index );
  36840. } ) );
  36841. this.cache.add( type, dependencies );
  36842. }
  36843. return dependencies;
  36844. };
  36845. /**
  36846. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  36847. * @param {number} bufferIndex
  36848. * @return {Promise<ArrayBuffer>}
  36849. */
  36850. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  36851. var bufferDef = this.json.buffers[ bufferIndex ];
  36852. var loader = this.fileLoader;
  36853. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  36854. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  36855. }
  36856. // If present, GLB container is required to be the first buffer.
  36857. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  36858. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  36859. }
  36860. var options = this.options;
  36861. return new Promise( function ( resolve, reject ) {
  36862. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  36863. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  36864. } );
  36865. } );
  36866. };
  36867. /**
  36868. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  36869. * @param {number} bufferViewIndex
  36870. * @return {Promise<ArrayBuffer>}
  36871. */
  36872. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  36873. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  36874. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  36875. var byteLength = bufferViewDef.byteLength || 0;
  36876. var byteOffset = bufferViewDef.byteOffset || 0;
  36877. return buffer.slice( byteOffset, byteOffset + byteLength );
  36878. } );
  36879. };
  36880. /**
  36881. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  36882. * @param {number} accessorIndex
  36883. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  36884. */
  36885. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  36886. var parser = this;
  36887. var json = this.json;
  36888. var accessorDef = this.json.accessors[ accessorIndex ];
  36889. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  36890. // Ignore empty accessors, which may be used to declare runtime
  36891. // information about attributes coming from another source (e.g. Draco
  36892. // compression extension).
  36893. return Promise.resolve( null );
  36894. }
  36895. var pendingBufferViews = [];
  36896. if ( accessorDef.bufferView !== undefined ) {
  36897. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  36898. } else {
  36899. pendingBufferViews.push( null );
  36900. }
  36901. if ( accessorDef.sparse !== undefined ) {
  36902. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  36903. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  36904. }
  36905. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  36906. var bufferView = bufferViews[ 0 ];
  36907. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  36908. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  36909. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  36910. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  36911. var itemBytes = elementBytes * itemSize;
  36912. var byteOffset = accessorDef.byteOffset || 0;
  36913. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  36914. var normalized = accessorDef.normalized === true;
  36915. var array, bufferAttribute;
  36916. // The buffer is not interleaved if the stride is the item size in bytes.
  36917. if ( byteStride && byteStride !== itemBytes ) {
  36918. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  36919. // This makes sure that IBA.count reflects accessor.count properly
  36920. var ibSlice = Math.floor( byteOffset / byteStride );
  36921. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  36922. var ib = parser.cache.get( ibCacheKey );
  36923. if ( ! ib ) {
  36924. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  36925. // Integer parameters to IB/IBA are in array elements, not bytes.
  36926. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  36927. parser.cache.add( ibCacheKey, ib );
  36928. }
  36929. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  36930. } else {
  36931. if ( bufferView === null ) {
  36932. array = new TypedArray( accessorDef.count * itemSize );
  36933. } else {
  36934. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  36935. }
  36936. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  36937. }
  36938. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  36939. if ( accessorDef.sparse !== undefined ) {
  36940. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  36941. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  36942. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  36943. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  36944. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  36945. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  36946. if ( bufferView !== null ) {
  36947. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  36948. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  36949. }
  36950. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  36951. var index = sparseIndices[ i ];
  36952. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  36953. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  36954. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  36955. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  36956. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  36957. }
  36958. }
  36959. return bufferAttribute;
  36960. } );
  36961. };
  36962. /**
  36963. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  36964. * @param {number} textureIndex
  36965. * @return {Promise<THREE.Texture>}
  36966. */
  36967. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  36968. var parser = this;
  36969. var json = this.json;
  36970. var options = this.options;
  36971. var textureLoader = this.textureLoader;
  36972. var URL = window.URL || window.webkitURL;
  36973. var textureDef = json.textures[ textureIndex ];
  36974. var textureExtensions = textureDef.extensions || {};
  36975. var source;
  36976. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  36977. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  36978. } else {
  36979. source = json.images[ textureDef.source ];
  36980. }
  36981. var sourceURI = source.uri;
  36982. var isObjectURL = false;
  36983. if ( source.bufferView !== undefined ) {
  36984. // Load binary image data from bufferView, if provided.
  36985. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  36986. isObjectURL = true;
  36987. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  36988. sourceURI = URL.createObjectURL( blob );
  36989. return sourceURI;
  36990. } );
  36991. }
  36992. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  36993. // Load Texture resource.
  36994. var loader = options.manager.getHandler( sourceURI );
  36995. if ( ! loader ) {
  36996. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  36997. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  36998. : textureLoader;
  36999. }
  37000. return new Promise( function ( resolve, reject ) {
  37001. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  37002. } );
  37003. } ).then( function ( texture ) {
  37004. // Clean up resources and configure Texture.
  37005. if ( isObjectURL === true ) {
  37006. URL.revokeObjectURL( sourceURI );
  37007. }
  37008. texture.flipY = false;
  37009. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  37010. // Ignore unknown mime types, like DDS files.
  37011. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  37012. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  37013. }
  37014. var samplers = json.samplers || {};
  37015. var sampler = samplers[ textureDef.sampler ] || {};
  37016. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  37017. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  37018. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  37019. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  37020. return texture;
  37021. } );
  37022. };
  37023. /**
  37024. * Asynchronously assigns a texture to the given material parameters.
  37025. * @param {Object} materialParams
  37026. * @param {string} mapName
  37027. * @param {Object} mapDef
  37028. * @return {Promise}
  37029. */
  37030. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  37031. var parser = this;
  37032. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  37033. if ( ! texture.isCompressedTexture ) {
  37034. switch ( mapName ) {
  37035. case 'aoMap':
  37036. case 'emissiveMap':
  37037. case 'metalnessMap':
  37038. case 'normalMap':
  37039. case 'roughnessMap':
  37040. texture.format = THREE.RGBFormat;
  37041. break;
  37042. }
  37043. }
  37044. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  37045. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  37046. if ( transform ) {
  37047. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  37048. }
  37049. }
  37050. materialParams[ mapName ] = texture;
  37051. } );
  37052. };
  37053. /**
  37054. * Assigns final material to a Mesh, Line, or Points instance. The instance
  37055. * already has a material (generated from the glTF material options alone)
  37056. * but reuse of the same glTF material may require multiple threejs materials
  37057. * to accomodate different primitive types, defines, etc. New materials will
  37058. * be created if necessary, and reused from a cache.
  37059. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  37060. */
  37061. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  37062. var geometry = mesh.geometry;
  37063. var material = mesh.material;
  37064. var extensions = this.extensions;
  37065. var useVertexTangents = geometry.attributes.tangent !== undefined;
  37066. var useVertexColors = geometry.attributes.color !== undefined;
  37067. var useFlatShading = geometry.attributes.normal === undefined;
  37068. var useSkinning = mesh.isSkinnedMesh === true;
  37069. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  37070. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  37071. if ( mesh.isPoints ) {
  37072. var cacheKey = 'PointsMaterial:' + material.uuid;
  37073. var pointsMaterial = this.cache.get( cacheKey );
  37074. if ( ! pointsMaterial ) {
  37075. pointsMaterial = new THREE.PointsMaterial();
  37076. THREE.Material.prototype.copy.call( pointsMaterial, material );
  37077. pointsMaterial.color.copy( material.color );
  37078. pointsMaterial.map = material.map;
  37079. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  37080. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  37081. this.cache.add( cacheKey, pointsMaterial );
  37082. }
  37083. material = pointsMaterial;
  37084. } else if ( mesh.isLine ) {
  37085. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  37086. var lineMaterial = this.cache.get( cacheKey );
  37087. if ( ! lineMaterial ) {
  37088. lineMaterial = new THREE.LineBasicMaterial();
  37089. THREE.Material.prototype.copy.call( lineMaterial, material );
  37090. lineMaterial.color.copy( material.color );
  37091. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  37092. this.cache.add( cacheKey, lineMaterial );
  37093. }
  37094. material = lineMaterial;
  37095. }
  37096. // Clone the material if it will be modified
  37097. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  37098. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  37099. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  37100. if ( useSkinning ) cacheKey += 'skinning:';
  37101. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  37102. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  37103. if ( useFlatShading ) cacheKey += 'flat-shading:';
  37104. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  37105. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  37106. var cachedMaterial = this.cache.get( cacheKey );
  37107. if ( ! cachedMaterial ) {
  37108. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  37109. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  37110. : material.clone();
  37111. if ( useSkinning ) cachedMaterial.skinning = true;
  37112. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  37113. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  37114. if ( useFlatShading ) cachedMaterial.flatShading = true;
  37115. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  37116. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  37117. this.cache.add( cacheKey, cachedMaterial );
  37118. }
  37119. material = cachedMaterial;
  37120. }
  37121. // workarounds for mesh and geometry
  37122. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  37123. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  37124. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  37125. }
  37126. if ( material.isGLTFSpecularGlossinessMaterial ) {
  37127. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  37128. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  37129. }
  37130. mesh.material = material;
  37131. };
  37132. /**
  37133. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  37134. * @param {number} materialIndex
  37135. * @return {Promise<THREE.Material>}
  37136. */
  37137. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  37138. var parser = this;
  37139. var json = this.json;
  37140. var extensions = this.extensions;
  37141. var materialDef = json.materials[ materialIndex ];
  37142. var materialType;
  37143. var materialParams = {};
  37144. var materialExtensions = materialDef.extensions || {};
  37145. var pending = [];
  37146. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  37147. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  37148. materialType = sgExtension.getMaterialType();
  37149. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  37150. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  37151. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  37152. materialType = kmuExtension.getMaterialType();
  37153. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  37154. } else {
  37155. // Specification:
  37156. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  37157. materialType = THREE.MeshStandardMaterial;
  37158. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  37159. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37160. materialParams.opacity = 1.0;
  37161. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37162. var array = metallicRoughness.baseColorFactor;
  37163. materialParams.color.fromArray( array );
  37164. materialParams.opacity = array[ 3 ];
  37165. }
  37166. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37167. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37168. }
  37169. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  37170. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  37171. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  37172. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37173. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37174. }
  37175. }
  37176. if ( materialDef.doubleSided === true ) {
  37177. materialParams.side = THREE.DoubleSide;
  37178. }
  37179. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  37180. if ( alphaMode === ALPHA_MODES.BLEND ) {
  37181. materialParams.transparent = true;
  37182. } else {
  37183. materialParams.transparent = false;
  37184. if ( alphaMode === ALPHA_MODES.MASK ) {
  37185. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  37186. }
  37187. }
  37188. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37189. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  37190. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  37191. if ( materialDef.normalTexture.scale !== undefined ) {
  37192. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  37193. }
  37194. }
  37195. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37196. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  37197. if ( materialDef.occlusionTexture.strength !== undefined ) {
  37198. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  37199. }
  37200. }
  37201. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37202. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  37203. }
  37204. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37205. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  37206. }
  37207. return Promise.all( pending ).then( function () {
  37208. var material;
  37209. if ( materialType === THREE.ShaderMaterial ) {
  37210. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  37211. } else {
  37212. material = new materialType( materialParams );
  37213. }
  37214. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  37215. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  37216. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  37217. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  37218. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  37219. assignExtrasToUserData( material, materialDef );
  37220. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  37221. return material;
  37222. } );
  37223. };
  37224. /**
  37225. * @param {THREE.BufferGeometry} geometry
  37226. * @param {GLTF.Primitive} primitiveDef
  37227. * @param {GLTFParser} parser
  37228. * @return {Promise<THREE.BufferGeometry>}
  37229. */
  37230. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  37231. var attributes = primitiveDef.attributes;
  37232. var pending = [];
  37233. function assignAttributeAccessor( accessorIndex, attributeName ) {
  37234. return parser.getDependency( 'accessor', accessorIndex )
  37235. .then( function ( accessor ) {
  37236. geometry.addAttribute( attributeName, accessor );
  37237. } );
  37238. }
  37239. for ( var gltfAttributeName in attributes ) {
  37240. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  37241. // Skip attributes already provided by e.g. Draco extension.
  37242. if ( threeAttributeName in geometry.attributes ) continue;
  37243. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  37244. }
  37245. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  37246. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  37247. geometry.setIndex( accessor );
  37248. } );
  37249. pending.push( accessor );
  37250. }
  37251. assignExtrasToUserData( geometry, primitiveDef );
  37252. return Promise.all( pending ).then( function () {
  37253. return primitiveDef.targets !== undefined
  37254. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  37255. : geometry;
  37256. } );
  37257. }
  37258. /**
  37259. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  37260. *
  37261. * Creates BufferGeometries from primitives.
  37262. *
  37263. * @param {Array<GLTF.Primitive>} primitives
  37264. * @return {Promise<Array<THREE.BufferGeometry>>}
  37265. */
  37266. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  37267. var parser = this;
  37268. var extensions = this.extensions;
  37269. var cache = this.primitiveCache;
  37270. function createDracoPrimitive( primitive ) {
  37271. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  37272. .decodePrimitive( primitive, parser )
  37273. .then( function ( geometry ) {
  37274. return addPrimitiveAttributes( geometry, primitive, parser );
  37275. } );
  37276. }
  37277. var pending = [];
  37278. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  37279. var primitive = primitives[ i ];
  37280. var cacheKey = createPrimitiveKey( primitive );
  37281. // See if we've already created this geometry
  37282. var cached = cache[ cacheKey ];
  37283. if ( cached ) {
  37284. // Use the cached geometry if it exists
  37285. pending.push( cached.promise );
  37286. } else {
  37287. var geometryPromise;
  37288. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  37289. // Use DRACO geometry if available
  37290. geometryPromise = createDracoPrimitive( primitive );
  37291. } else {
  37292. // Otherwise create a new geometry
  37293. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  37294. }
  37295. // Cache this geometry
  37296. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  37297. pending.push( geometryPromise );
  37298. }
  37299. }
  37300. return Promise.all( pending );
  37301. };
  37302. /**
  37303. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  37304. * @param {number} meshIndex
  37305. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  37306. */
  37307. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  37308. var parser = this;
  37309. var json = this.json;
  37310. var meshDef = json.meshes[ meshIndex ];
  37311. var primitives = meshDef.primitives;
  37312. var pending = [];
  37313. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  37314. var material = primitives[ i ].material === undefined
  37315. ? createDefaultMaterial()
  37316. : this.getDependency( 'material', primitives[ i ].material );
  37317. pending.push( material );
  37318. }
  37319. return Promise.all( pending ).then( function ( originalMaterials ) {
  37320. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  37321. var meshes = [];
  37322. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  37323. var geometry = geometries[ i ];
  37324. var primitive = primitives[ i ];
  37325. // 1. create Mesh
  37326. var mesh;
  37327. var material = originalMaterials[ i ];
  37328. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  37329. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  37330. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  37331. primitive.mode === undefined ) {
  37332. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  37333. mesh = meshDef.isSkinnedMesh === true
  37334. ? new THREE.SkinnedMesh( geometry, material )
  37335. : new THREE.Mesh( geometry, material );
  37336. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  37337. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  37338. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  37339. mesh.normalizeSkinWeights();
  37340. }
  37341. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  37342. mesh.drawMode = THREE.TriangleStripDrawMode;
  37343. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  37344. mesh.drawMode = THREE.TriangleFanDrawMode;
  37345. }
  37346. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  37347. mesh = new THREE.LineSegments( geometry, material );
  37348. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  37349. mesh = new THREE.Line( geometry, material );
  37350. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  37351. mesh = new THREE.LineLoop( geometry, material );
  37352. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  37353. mesh = new THREE.Points( geometry, material );
  37354. } else {
  37355. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  37356. }
  37357. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  37358. updateMorphTargets( mesh, meshDef );
  37359. }
  37360. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  37361. if ( geometries.length > 1 ) mesh.name += '_' + i;
  37362. assignExtrasToUserData( mesh, meshDef );
  37363. parser.assignFinalMaterial( mesh );
  37364. meshes.push( mesh );
  37365. }
  37366. if ( meshes.length === 1 ) {
  37367. return meshes[ 0 ];
  37368. }
  37369. var group = new THREE.Group();
  37370. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  37371. group.add( meshes[ i ] );
  37372. }
  37373. return group;
  37374. } );
  37375. } );
  37376. };
  37377. /**
  37378. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  37379. * @param {number} cameraIndex
  37380. * @return {Promise<THREE.Camera>}
  37381. */
  37382. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  37383. var camera;
  37384. var cameraDef = this.json.cameras[ cameraIndex ];
  37385. var params = cameraDef[ cameraDef.type ];
  37386. if ( ! params ) {
  37387. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  37388. return;
  37389. }
  37390. if ( cameraDef.type === 'perspective' ) {
  37391. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  37392. } else if ( cameraDef.type === 'orthographic' ) {
  37393. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  37394. }
  37395. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  37396. assignExtrasToUserData( camera, cameraDef );
  37397. return Promise.resolve( camera );
  37398. };
  37399. /**
  37400. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  37401. * @param {number} skinIndex
  37402. * @return {Promise<Object>}
  37403. */
  37404. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  37405. var skinDef = this.json.skins[ skinIndex ];
  37406. var skinEntry = { joints: skinDef.joints };
  37407. if ( skinDef.inverseBindMatrices === undefined ) {
  37408. return Promise.resolve( skinEntry );
  37409. }
  37410. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  37411. skinEntry.inverseBindMatrices = accessor;
  37412. return skinEntry;
  37413. } );
  37414. };
  37415. /**
  37416. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  37417. * @param {number} animationIndex
  37418. * @return {Promise<THREE.AnimationClip>}
  37419. */
  37420. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  37421. var json = this.json;
  37422. var animationDef = json.animations[ animationIndex ];
  37423. var pendingNodes = [];
  37424. var pendingInputAccessors = [];
  37425. var pendingOutputAccessors = [];
  37426. var pendingSamplers = [];
  37427. var pendingTargets = [];
  37428. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  37429. var channel = animationDef.channels[ i ];
  37430. var sampler = animationDef.samplers[ channel.sampler ];
  37431. var target = channel.target;
  37432. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  37433. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  37434. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  37435. pendingNodes.push( this.getDependency( 'node', name ) );
  37436. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  37437. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  37438. pendingSamplers.push( sampler );
  37439. pendingTargets.push( target );
  37440. }
  37441. return Promise.all( [
  37442. Promise.all( pendingNodes ),
  37443. Promise.all( pendingInputAccessors ),
  37444. Promise.all( pendingOutputAccessors ),
  37445. Promise.all( pendingSamplers ),
  37446. Promise.all( pendingTargets )
  37447. ] ).then( function ( dependencies ) {
  37448. var nodes = dependencies[ 0 ];
  37449. var inputAccessors = dependencies[ 1 ];
  37450. var outputAccessors = dependencies[ 2 ];
  37451. var samplers = dependencies[ 3 ];
  37452. var targets = dependencies[ 4 ];
  37453. var tracks = [];
  37454. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  37455. var node = nodes[ i ];
  37456. var inputAccessor = inputAccessors[ i ];
  37457. var outputAccessor = outputAccessors[ i ];
  37458. var sampler = samplers[ i ];
  37459. var target = targets[ i ];
  37460. if ( node === undefined ) continue;
  37461. node.updateMatrix();
  37462. node.matrixAutoUpdate = true;
  37463. var TypedKeyframeTrack;
  37464. switch ( PATH_PROPERTIES[ target.path ] ) {
  37465. case PATH_PROPERTIES.weights:
  37466. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  37467. break;
  37468. case PATH_PROPERTIES.rotation:
  37469. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  37470. break;
  37471. case PATH_PROPERTIES.position:
  37472. case PATH_PROPERTIES.scale:
  37473. default:
  37474. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  37475. break;
  37476. }
  37477. var targetName = node.name ? node.name : node.uuid;
  37478. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  37479. var targetNames = [];
  37480. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  37481. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  37482. node.traverse( function ( object ) {
  37483. if ( object.isMesh === true && object.morphTargetInfluences ) {
  37484. targetNames.push( object.name ? object.name : object.uuid );
  37485. }
  37486. } );
  37487. } else {
  37488. targetNames.push( targetName );
  37489. }
  37490. var outputArray = outputAccessor.array;
  37491. if ( outputAccessor.normalized ) {
  37492. var scale;
  37493. if ( outputArray.constructor === Int8Array ) {
  37494. scale = 1 / 127;
  37495. } else if ( outputArray.constructor === Uint8Array ) {
  37496. scale = 1 / 255;
  37497. } else if ( outputArray.constructor == Int16Array ) {
  37498. scale = 1 / 32767;
  37499. } else if ( outputArray.constructor === Uint16Array ) {
  37500. scale = 1 / 65535;
  37501. } else {
  37502. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  37503. }
  37504. var scaled = new Float32Array( outputArray.length );
  37505. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  37506. scaled[ j ] = outputArray[ j ] * scale;
  37507. }
  37508. outputArray = scaled;
  37509. }
  37510. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  37511. var track = new TypedKeyframeTrack(
  37512. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  37513. inputAccessor.array,
  37514. outputArray,
  37515. interpolation
  37516. );
  37517. // Override interpolation with custom factory method.
  37518. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  37519. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  37520. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  37521. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  37522. // must be divided by three to get the interpolant's sampleSize argument.
  37523. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  37524. };
  37525. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  37526. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  37527. }
  37528. tracks.push( track );
  37529. }
  37530. }
  37531. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  37532. return new THREE.AnimationClip( name, undefined, tracks );
  37533. } );
  37534. };
  37535. /**
  37536. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  37537. * @param {number} nodeIndex
  37538. * @return {Promise<THREE.Object3D>}
  37539. */
  37540. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  37541. var json = this.json;
  37542. var extensions = this.extensions;
  37543. var parser = this;
  37544. var meshReferences = json.meshReferences;
  37545. var meshUses = json.meshUses;
  37546. var nodeDef = json.nodes[ nodeIndex ];
  37547. return ( function () {
  37548. var pending = [];
  37549. if ( nodeDef.mesh !== undefined ) {
  37550. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  37551. var node;
  37552. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  37553. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  37554. node = mesh.clone();
  37555. node.name += '_instance_' + instanceNum;
  37556. // onBeforeRender copy for Specular-Glossiness
  37557. node.onBeforeRender = mesh.onBeforeRender;
  37558. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  37559. node.children[ i ].name += '_instance_' + instanceNum;
  37560. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  37561. }
  37562. } else {
  37563. node = mesh;
  37564. }
  37565. // if weights are provided on the node, override weights on the mesh.
  37566. if ( nodeDef.weights !== undefined ) {
  37567. node.traverse( function ( o ) {
  37568. if ( ! o.isMesh ) return;
  37569. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  37570. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  37571. }
  37572. } );
  37573. }
  37574. return node;
  37575. } ) );
  37576. }
  37577. if ( nodeDef.camera !== undefined ) {
  37578. pending.push( parser.getDependency( 'camera', nodeDef.camera ) );
  37579. }
  37580. if ( nodeDef.extensions
  37581. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  37582. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  37583. pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) );
  37584. }
  37585. return Promise.all( pending );
  37586. }() ).then( function ( objects ) {
  37587. var node;
  37588. // .isBone isn't in glTF spec. See .markDefs
  37589. if ( nodeDef.isBone === true ) {
  37590. node = new THREE.Bone();
  37591. } else if ( objects.length > 1 ) {
  37592. node = new THREE.Group();
  37593. } else if ( objects.length === 1 ) {
  37594. node = objects[ 0 ];
  37595. } else {
  37596. node = new THREE.Object3D();
  37597. }
  37598. if ( node !== objects[ 0 ] ) {
  37599. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  37600. node.add( objects[ i ] );
  37601. }
  37602. }
  37603. if ( nodeDef.name !== undefined ) {
  37604. node.userData.name = nodeDef.name;
  37605. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  37606. }
  37607. assignExtrasToUserData( node, nodeDef );
  37608. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  37609. if ( nodeDef.matrix !== undefined ) {
  37610. var matrix = new THREE.Matrix4();
  37611. matrix.fromArray( nodeDef.matrix );
  37612. node.applyMatrix( matrix );
  37613. } else {
  37614. if ( nodeDef.translation !== undefined ) {
  37615. node.position.fromArray( nodeDef.translation );
  37616. }
  37617. if ( nodeDef.rotation !== undefined ) {
  37618. node.quaternion.fromArray( nodeDef.rotation );
  37619. }
  37620. if ( nodeDef.scale !== undefined ) {
  37621. node.scale.fromArray( nodeDef.scale );
  37622. }
  37623. }
  37624. return node;
  37625. } );
  37626. };
  37627. /**
  37628. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  37629. * @param {number} sceneIndex
  37630. * @return {Promise<THREE.Scene>}
  37631. */
  37632. GLTFParser.prototype.loadScene = function () {
  37633. // scene node hierachy builder
  37634. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  37635. var nodeDef = json.nodes[ nodeId ];
  37636. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  37637. if ( nodeDef.skin === undefined ) return node;
  37638. // build skeleton here as well
  37639. var skinEntry;
  37640. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  37641. skinEntry = skin;
  37642. var pendingJoints = [];
  37643. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  37644. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  37645. }
  37646. return Promise.all( pendingJoints );
  37647. } ).then( function ( jointNodes ) {
  37648. node.traverse( function ( mesh ) {
  37649. if ( ! mesh.isMesh ) return;
  37650. var bones = [];
  37651. var boneInverses = [];
  37652. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  37653. var jointNode = jointNodes[ j ];
  37654. if ( jointNode ) {
  37655. bones.push( jointNode );
  37656. var mat = new THREE.Matrix4();
  37657. if ( skinEntry.inverseBindMatrices !== undefined ) {
  37658. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  37659. }
  37660. boneInverses.push( mat );
  37661. } else {
  37662. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  37663. }
  37664. }
  37665. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  37666. } );
  37667. return node;
  37668. } );
  37669. } ).then( function ( node ) {
  37670. // build node hierachy
  37671. parentObject.add( node );
  37672. var pending = [];
  37673. if ( nodeDef.children ) {
  37674. var children = nodeDef.children;
  37675. for ( var i = 0, il = children.length; i < il; i ++ ) {
  37676. var child = children[ i ];
  37677. pending.push( buildNodeHierachy( child, node, json, parser ) );
  37678. }
  37679. }
  37680. return Promise.all( pending );
  37681. } );
  37682. }
  37683. return function loadScene( sceneIndex ) {
  37684. var json = this.json;
  37685. var extensions = this.extensions;
  37686. var sceneDef = this.json.scenes[ sceneIndex ];
  37687. var parser = this;
  37688. var scene = new THREE.Scene();
  37689. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  37690. assignExtrasToUserData( scene, sceneDef );
  37691. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  37692. var nodeIds = sceneDef.nodes || [];
  37693. var pending = [];
  37694. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  37695. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  37696. }
  37697. return Promise.all( pending ).then( function () {
  37698. return scene;
  37699. } );
  37700. };
  37701. }();
  37702. return GLTFLoader;
  37703. } )();
  37704. },{}],60:[function(_dereq_,module,exports){
  37705. /**
  37706. * Loads a Wavefront .mtl file specifying materials
  37707. *
  37708. * @author angelxuanchang
  37709. */
  37710. THREE.MTLLoader = function ( manager ) {
  37711. THREE.Loader.call( this, manager );
  37712. };
  37713. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  37714. constructor: THREE.MTLLoader,
  37715. /**
  37716. * Loads and parses a MTL asset from a URL.
  37717. *
  37718. * @param {String} url - URL to the MTL file.
  37719. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  37720. * @param {Function} [onProgress] - Callback for download progress.
  37721. * @param {Function} [onError] - Callback for download errors.
  37722. *
  37723. * @see setPath setResourcePath
  37724. *
  37725. * @note In order for relative texture references to resolve correctly
  37726. * you must call setResourcePath() explicitly prior to load.
  37727. */
  37728. load: function ( url, onLoad, onProgress, onError ) {
  37729. var scope = this;
  37730. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  37731. var loader = new THREE.FileLoader( this.manager );
  37732. loader.setPath( this.path );
  37733. loader.load( url, function ( text ) {
  37734. onLoad( scope.parse( text, path ) );
  37735. }, onProgress, onError );
  37736. },
  37737. setMaterialOptions: function ( value ) {
  37738. this.materialOptions = value;
  37739. return this;
  37740. },
  37741. /**
  37742. * Parses a MTL file.
  37743. *
  37744. * @param {String} text - Content of MTL file
  37745. * @return {THREE.MTLLoader.MaterialCreator}
  37746. *
  37747. * @see setPath setResourcePath
  37748. *
  37749. * @note In order for relative texture references to resolve correctly
  37750. * you must call setResourcePath() explicitly prior to parse.
  37751. */
  37752. parse: function ( text, path ) {
  37753. var lines = text.split( '\n' );
  37754. var info = {};
  37755. var delimiter_pattern = /\s+/;
  37756. var materialsInfo = {};
  37757. for ( var i = 0; i < lines.length; i ++ ) {
  37758. var line = lines[ i ];
  37759. line = line.trim();
  37760. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  37761. // Blank line or comment ignore
  37762. continue;
  37763. }
  37764. var pos = line.indexOf( ' ' );
  37765. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  37766. key = key.toLowerCase();
  37767. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  37768. value = value.trim();
  37769. if ( key === 'newmtl' ) {
  37770. // New material
  37771. info = { name: value };
  37772. materialsInfo[ value ] = info;
  37773. } else {
  37774. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  37775. var ss = value.split( delimiter_pattern, 3 );
  37776. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  37777. } else {
  37778. info[ key ] = value;
  37779. }
  37780. }
  37781. }
  37782. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  37783. materialCreator.setCrossOrigin( this.crossOrigin );
  37784. materialCreator.setManager( this.manager );
  37785. materialCreator.setMaterials( materialsInfo );
  37786. return materialCreator;
  37787. }
  37788. } );
  37789. /**
  37790. * Create a new THREE-MTLLoader.MaterialCreator
  37791. * @param baseUrl - Url relative to which textures are loaded
  37792. * @param options - Set of options on how to construct the materials
  37793. * side: Which side to apply the material
  37794. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  37795. * wrap: What type of wrapping to apply for textures
  37796. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  37797. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  37798. * Default: false, assumed to be already normalized
  37799. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  37800. * Default: false
  37801. * @constructor
  37802. */
  37803. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  37804. this.baseUrl = baseUrl || '';
  37805. this.options = options;
  37806. this.materialsInfo = {};
  37807. this.materials = {};
  37808. this.materialsArray = [];
  37809. this.nameLookup = {};
  37810. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  37811. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  37812. };
  37813. THREE.MTLLoader.MaterialCreator.prototype = {
  37814. constructor: THREE.MTLLoader.MaterialCreator,
  37815. crossOrigin: 'anonymous',
  37816. setCrossOrigin: function ( value ) {
  37817. this.crossOrigin = value;
  37818. return this;
  37819. },
  37820. setManager: function ( value ) {
  37821. this.manager = value;
  37822. },
  37823. setMaterials: function ( materialsInfo ) {
  37824. this.materialsInfo = this.convert( materialsInfo );
  37825. this.materials = {};
  37826. this.materialsArray = [];
  37827. this.nameLookup = {};
  37828. },
  37829. convert: function ( materialsInfo ) {
  37830. if ( ! this.options ) return materialsInfo;
  37831. var converted = {};
  37832. for ( var mn in materialsInfo ) {
  37833. // Convert materials info into normalized form based on options
  37834. var mat = materialsInfo[ mn ];
  37835. var covmat = {};
  37836. converted[ mn ] = covmat;
  37837. for ( var prop in mat ) {
  37838. var save = true;
  37839. var value = mat[ prop ];
  37840. var lprop = prop.toLowerCase();
  37841. switch ( lprop ) {
  37842. case 'kd':
  37843. case 'ka':
  37844. case 'ks':
  37845. // Diffuse color (color under white light) using RGB values
  37846. if ( this.options && this.options.normalizeRGB ) {
  37847. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  37848. }
  37849. if ( this.options && this.options.ignoreZeroRGBs ) {
  37850. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  37851. // ignore
  37852. save = false;
  37853. }
  37854. }
  37855. break;
  37856. default:
  37857. break;
  37858. }
  37859. if ( save ) {
  37860. covmat[ lprop ] = value;
  37861. }
  37862. }
  37863. }
  37864. return converted;
  37865. },
  37866. preload: function () {
  37867. for ( var mn in this.materialsInfo ) {
  37868. this.create( mn );
  37869. }
  37870. },
  37871. getIndex: function ( materialName ) {
  37872. return this.nameLookup[ materialName ];
  37873. },
  37874. getAsArray: function () {
  37875. var index = 0;
  37876. for ( var mn in this.materialsInfo ) {
  37877. this.materialsArray[ index ] = this.create( mn );
  37878. this.nameLookup[ mn ] = index;
  37879. index ++;
  37880. }
  37881. return this.materialsArray;
  37882. },
  37883. create: function ( materialName ) {
  37884. if ( this.materials[ materialName ] === undefined ) {
  37885. this.createMaterial_( materialName );
  37886. }
  37887. return this.materials[ materialName ];
  37888. },
  37889. createMaterial_: function ( materialName ) {
  37890. // Create material
  37891. var scope = this;
  37892. var mat = this.materialsInfo[ materialName ];
  37893. var params = {
  37894. name: materialName,
  37895. side: this.side
  37896. };
  37897. function resolveURL( baseUrl, url ) {
  37898. if ( typeof url !== 'string' || url === '' )
  37899. return '';
  37900. // Absolute URL
  37901. if ( /^https?:\/\//i.test( url ) ) return url;
  37902. return baseUrl + url;
  37903. }
  37904. function setMapForType( mapType, value ) {
  37905. if ( params[ mapType ] ) return; // Keep the first encountered texture
  37906. var texParams = scope.getTextureParams( value, params );
  37907. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  37908. map.repeat.copy( texParams.scale );
  37909. map.offset.copy( texParams.offset );
  37910. map.wrapS = scope.wrap;
  37911. map.wrapT = scope.wrap;
  37912. params[ mapType ] = map;
  37913. }
  37914. for ( var prop in mat ) {
  37915. var value = mat[ prop ];
  37916. var n;
  37917. if ( value === '' ) continue;
  37918. switch ( prop.toLowerCase() ) {
  37919. // Ns is material specular exponent
  37920. case 'kd':
  37921. // Diffuse color (color under white light) using RGB values
  37922. params.color = new THREE.Color().fromArray( value );
  37923. break;
  37924. case 'ks':
  37925. // Specular color (color when light is reflected from shiny surface) using RGB values
  37926. params.specular = new THREE.Color().fromArray( value );
  37927. break;
  37928. case 'ke':
  37929. // Emissive using RGB values
  37930. params.emissive = new THREE.Color().fromArray( value );
  37931. break;
  37932. case 'map_kd':
  37933. // Diffuse texture map
  37934. setMapForType( "map", value );
  37935. break;
  37936. case 'map_ks':
  37937. // Specular map
  37938. setMapForType( "specularMap", value );
  37939. break;
  37940. case 'map_ke':
  37941. // Emissive map
  37942. setMapForType( "emissiveMap", value );
  37943. break;
  37944. case 'norm':
  37945. setMapForType( "normalMap", value );
  37946. break;
  37947. case 'map_bump':
  37948. case 'bump':
  37949. // Bump texture map
  37950. setMapForType( "bumpMap", value );
  37951. break;
  37952. case 'map_d':
  37953. // Alpha map
  37954. setMapForType( "alphaMap", value );
  37955. params.transparent = true;
  37956. break;
  37957. case 'ns':
  37958. // The specular exponent (defines the focus of the specular highlight)
  37959. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  37960. params.shininess = parseFloat( value );
  37961. break;
  37962. case 'd':
  37963. n = parseFloat( value );
  37964. if ( n < 1 ) {
  37965. params.opacity = n;
  37966. params.transparent = true;
  37967. }
  37968. break;
  37969. case 'tr':
  37970. n = parseFloat( value );
  37971. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  37972. if ( n > 0 ) {
  37973. params.opacity = 1 - n;
  37974. params.transparent = true;
  37975. }
  37976. break;
  37977. default:
  37978. break;
  37979. }
  37980. }
  37981. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  37982. return this.materials[ materialName ];
  37983. },
  37984. getTextureParams: function ( value, matParams ) {
  37985. var texParams = {
  37986. scale: new THREE.Vector2( 1, 1 ),
  37987. offset: new THREE.Vector2( 0, 0 )
  37988. };
  37989. var items = value.split( /\s+/ );
  37990. var pos;
  37991. pos = items.indexOf( '-bm' );
  37992. if ( pos >= 0 ) {
  37993. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  37994. items.splice( pos, 2 );
  37995. }
  37996. pos = items.indexOf( '-s' );
  37997. if ( pos >= 0 ) {
  37998. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  37999. items.splice( pos, 4 ); // we expect 3 parameters here!
  38000. }
  38001. pos = items.indexOf( '-o' );
  38002. if ( pos >= 0 ) {
  38003. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  38004. items.splice( pos, 4 ); // we expect 3 parameters here!
  38005. }
  38006. texParams.url = items.join( ' ' ).trim();
  38007. return texParams;
  38008. },
  38009. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  38010. var texture;
  38011. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  38012. var loader = manager.getHandler( url );
  38013. if ( loader === null ) {
  38014. loader = new THREE.TextureLoader( manager );
  38015. }
  38016. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  38017. texture = loader.load( url, onLoad, onProgress, onError );
  38018. if ( mapping !== undefined ) texture.mapping = mapping;
  38019. return texture;
  38020. }
  38021. };
  38022. },{}],61:[function(_dereq_,module,exports){
  38023. /**
  38024. * @author mrdoob / http://mrdoob.com/
  38025. */
  38026. THREE.OBJLoader = ( function () {
  38027. // o object_name | g group_name
  38028. var object_pattern = /^[og]\s*(.+)?/;
  38029. // mtllib file_reference
  38030. var material_library_pattern = /^mtllib /;
  38031. // usemtl material_name
  38032. var material_use_pattern = /^usemtl /;
  38033. function ParserState() {
  38034. var state = {
  38035. objects: [],
  38036. object: {},
  38037. vertices: [],
  38038. normals: [],
  38039. colors: [],
  38040. uvs: [],
  38041. materialLibraries: [],
  38042. startObject: function ( name, fromDeclaration ) {
  38043. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  38044. // file. We need to use it for the first parsed g/o to keep things in sync.
  38045. if ( this.object && this.object.fromDeclaration === false ) {
  38046. this.object.name = name;
  38047. this.object.fromDeclaration = ( fromDeclaration !== false );
  38048. return;
  38049. }
  38050. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  38051. if ( this.object && typeof this.object._finalize === 'function' ) {
  38052. this.object._finalize( true );
  38053. }
  38054. this.object = {
  38055. name: name || '',
  38056. fromDeclaration: ( fromDeclaration !== false ),
  38057. geometry: {
  38058. vertices: [],
  38059. normals: [],
  38060. colors: [],
  38061. uvs: []
  38062. },
  38063. materials: [],
  38064. smooth: true,
  38065. startMaterial: function ( name, libraries ) {
  38066. var previous = this._finalize( false );
  38067. // New usemtl declaration overwrites an inherited material, except if faces were declared
  38068. // after the material, then it must be preserved for proper MultiMaterial continuation.
  38069. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  38070. this.materials.splice( previous.index, 1 );
  38071. }
  38072. var material = {
  38073. index: this.materials.length,
  38074. name: name || '',
  38075. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  38076. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  38077. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  38078. groupEnd: - 1,
  38079. groupCount: - 1,
  38080. inherited: false,
  38081. clone: function ( index ) {
  38082. var cloned = {
  38083. index: ( typeof index === 'number' ? index : this.index ),
  38084. name: this.name,
  38085. mtllib: this.mtllib,
  38086. smooth: this.smooth,
  38087. groupStart: 0,
  38088. groupEnd: - 1,
  38089. groupCount: - 1,
  38090. inherited: false
  38091. };
  38092. cloned.clone = this.clone.bind( cloned );
  38093. return cloned;
  38094. }
  38095. };
  38096. this.materials.push( material );
  38097. return material;
  38098. },
  38099. currentMaterial: function () {
  38100. if ( this.materials.length > 0 ) {
  38101. return this.materials[ this.materials.length - 1 ];
  38102. }
  38103. return undefined;
  38104. },
  38105. _finalize: function ( end ) {
  38106. var lastMultiMaterial = this.currentMaterial();
  38107. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  38108. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  38109. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  38110. lastMultiMaterial.inherited = false;
  38111. }
  38112. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  38113. if ( end && this.materials.length > 1 ) {
  38114. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  38115. if ( this.materials[ mi ].groupCount <= 0 ) {
  38116. this.materials.splice( mi, 1 );
  38117. }
  38118. }
  38119. }
  38120. // Guarantee at least one empty material, this makes the creation later more straight forward.
  38121. if ( end && this.materials.length === 0 ) {
  38122. this.materials.push( {
  38123. name: '',
  38124. smooth: this.smooth
  38125. } );
  38126. }
  38127. return lastMultiMaterial;
  38128. }
  38129. };
  38130. // Inherit previous objects material.
  38131. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  38132. // If a usemtl declaration is encountered while this new object is being parsed, it will
  38133. // overwrite the inherited material. Exception being that there was already face declarations
  38134. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  38135. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  38136. var declared = previousMaterial.clone( 0 );
  38137. declared.inherited = true;
  38138. this.object.materials.push( declared );
  38139. }
  38140. this.objects.push( this.object );
  38141. },
  38142. finalize: function () {
  38143. if ( this.object && typeof this.object._finalize === 'function' ) {
  38144. this.object._finalize( true );
  38145. }
  38146. },
  38147. parseVertexIndex: function ( value, len ) {
  38148. var index = parseInt( value, 10 );
  38149. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38150. },
  38151. parseNormalIndex: function ( value, len ) {
  38152. var index = parseInt( value, 10 );
  38153. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38154. },
  38155. parseUVIndex: function ( value, len ) {
  38156. var index = parseInt( value, 10 );
  38157. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  38158. },
  38159. addVertex: function ( a, b, c ) {
  38160. var src = this.vertices;
  38161. var dst = this.object.geometry.vertices;
  38162. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38163. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38164. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38165. },
  38166. addVertexPoint: function ( a ) {
  38167. var src = this.vertices;
  38168. var dst = this.object.geometry.vertices;
  38169. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38170. },
  38171. addVertexLine: function ( a ) {
  38172. var src = this.vertices;
  38173. var dst = this.object.geometry.vertices;
  38174. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38175. },
  38176. addNormal: function ( a, b, c ) {
  38177. var src = this.normals;
  38178. var dst = this.object.geometry.normals;
  38179. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38180. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38181. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38182. },
  38183. addColor: function ( a, b, c ) {
  38184. var src = this.colors;
  38185. var dst = this.object.geometry.colors;
  38186. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38187. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38188. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38189. },
  38190. addUV: function ( a, b, c ) {
  38191. var src = this.uvs;
  38192. var dst = this.object.geometry.uvs;
  38193. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38194. dst.push( src[ b + 0 ], src[ b + 1 ] );
  38195. dst.push( src[ c + 0 ], src[ c + 1 ] );
  38196. },
  38197. addUVLine: function ( a ) {
  38198. var src = this.uvs;
  38199. var dst = this.object.geometry.uvs;
  38200. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38201. },
  38202. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  38203. var vLen = this.vertices.length;
  38204. var ia = this.parseVertexIndex( a, vLen );
  38205. var ib = this.parseVertexIndex( b, vLen );
  38206. var ic = this.parseVertexIndex( c, vLen );
  38207. this.addVertex( ia, ib, ic );
  38208. if ( ua !== undefined && ua !== '' ) {
  38209. var uvLen = this.uvs.length;
  38210. ia = this.parseUVIndex( ua, uvLen );
  38211. ib = this.parseUVIndex( ub, uvLen );
  38212. ic = this.parseUVIndex( uc, uvLen );
  38213. this.addUV( ia, ib, ic );
  38214. }
  38215. if ( na !== undefined && na !== '' ) {
  38216. // Normals are many times the same. If so, skip function call and parseInt.
  38217. var nLen = this.normals.length;
  38218. ia = this.parseNormalIndex( na, nLen );
  38219. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  38220. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  38221. this.addNormal( ia, ib, ic );
  38222. }
  38223. if ( this.colors.length > 0 ) {
  38224. this.addColor( ia, ib, ic );
  38225. }
  38226. },
  38227. addPointGeometry: function ( vertices ) {
  38228. this.object.geometry.type = 'Points';
  38229. var vLen = this.vertices.length;
  38230. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38231. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  38232. }
  38233. },
  38234. addLineGeometry: function ( vertices, uvs ) {
  38235. this.object.geometry.type = 'Line';
  38236. var vLen = this.vertices.length;
  38237. var uvLen = this.uvs.length;
  38238. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38239. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  38240. }
  38241. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  38242. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  38243. }
  38244. }
  38245. };
  38246. state.startObject( '', false );
  38247. return state;
  38248. }
  38249. //
  38250. function OBJLoader( manager ) {
  38251. THREE.Loader.call( this, manager );
  38252. this.materials = null;
  38253. }
  38254. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  38255. constructor: OBJLoader,
  38256. load: function ( url, onLoad, onProgress, onError ) {
  38257. var scope = this;
  38258. var loader = new THREE.FileLoader( scope.manager );
  38259. loader.setPath( this.path );
  38260. loader.load( url, function ( text ) {
  38261. onLoad( scope.parse( text ) );
  38262. }, onProgress, onError );
  38263. },
  38264. setMaterials: function ( materials ) {
  38265. this.materials = materials;
  38266. return this;
  38267. },
  38268. parse: function ( text ) {
  38269. console.time( 'OBJLoader' );
  38270. var state = new ParserState();
  38271. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  38272. // This is faster than String.split with regex that splits on both
  38273. text = text.replace( /\r\n/g, '\n' );
  38274. }
  38275. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  38276. // join lines separated by a line continuation character (\)
  38277. text = text.replace( /\\\n/g, '' );
  38278. }
  38279. var lines = text.split( '\n' );
  38280. var line = '', lineFirstChar = '';
  38281. var lineLength = 0;
  38282. var result = [];
  38283. // Faster to just trim left side of the line. Use if available.
  38284. var trimLeft = ( typeof ''.trimLeft === 'function' );
  38285. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  38286. line = lines[ i ];
  38287. line = trimLeft ? line.trimLeft() : line.trim();
  38288. lineLength = line.length;
  38289. if ( lineLength === 0 ) continue;
  38290. lineFirstChar = line.charAt( 0 );
  38291. // @todo invoke passed in handler if any
  38292. if ( lineFirstChar === '#' ) continue;
  38293. if ( lineFirstChar === 'v' ) {
  38294. var data = line.split( /\s+/ );
  38295. switch ( data[ 0 ] ) {
  38296. case 'v':
  38297. state.vertices.push(
  38298. parseFloat( data[ 1 ] ),
  38299. parseFloat( data[ 2 ] ),
  38300. parseFloat( data[ 3 ] )
  38301. );
  38302. if ( data.length >= 7 ) {
  38303. state.colors.push(
  38304. parseFloat( data[ 4 ] ),
  38305. parseFloat( data[ 5 ] ),
  38306. parseFloat( data[ 6 ] )
  38307. );
  38308. }
  38309. break;
  38310. case 'vn':
  38311. state.normals.push(
  38312. parseFloat( data[ 1 ] ),
  38313. parseFloat( data[ 2 ] ),
  38314. parseFloat( data[ 3 ] )
  38315. );
  38316. break;
  38317. case 'vt':
  38318. state.uvs.push(
  38319. parseFloat( data[ 1 ] ),
  38320. parseFloat( data[ 2 ] )
  38321. );
  38322. break;
  38323. }
  38324. } else if ( lineFirstChar === 'f' ) {
  38325. var lineData = line.substr( 1 ).trim();
  38326. var vertexData = lineData.split( /\s+/ );
  38327. var faceVertices = [];
  38328. // Parse the face vertex data into an easy to work with format
  38329. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  38330. var vertex = vertexData[ j ];
  38331. if ( vertex.length > 0 ) {
  38332. var vertexParts = vertex.split( '/' );
  38333. faceVertices.push( vertexParts );
  38334. }
  38335. }
  38336. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  38337. var v1 = faceVertices[ 0 ];
  38338. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  38339. var v2 = faceVertices[ j ];
  38340. var v3 = faceVertices[ j + 1 ];
  38341. state.addFace(
  38342. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  38343. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  38344. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  38345. );
  38346. }
  38347. } else if ( lineFirstChar === 'l' ) {
  38348. var lineParts = line.substring( 1 ).trim().split( " " );
  38349. var lineVertices = [], lineUVs = [];
  38350. if ( line.indexOf( "/" ) === - 1 ) {
  38351. lineVertices = lineParts;
  38352. } else {
  38353. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  38354. var parts = lineParts[ li ].split( "/" );
  38355. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  38356. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  38357. }
  38358. }
  38359. state.addLineGeometry( lineVertices, lineUVs );
  38360. } else if ( lineFirstChar === 'p' ) {
  38361. var lineData = line.substr( 1 ).trim();
  38362. var pointData = lineData.split( " " );
  38363. state.addPointGeometry( pointData );
  38364. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  38365. // o object_name
  38366. // or
  38367. // g group_name
  38368. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  38369. // var name = result[ 0 ].substr( 1 ).trim();
  38370. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  38371. state.startObject( name );
  38372. } else if ( material_use_pattern.test( line ) ) {
  38373. // material
  38374. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  38375. } else if ( material_library_pattern.test( line ) ) {
  38376. // mtl file
  38377. state.materialLibraries.push( line.substring( 7 ).trim() );
  38378. } else if ( lineFirstChar === 's' ) {
  38379. result = line.split( ' ' );
  38380. // smooth shading
  38381. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  38382. // but does not define a usemtl for each face set.
  38383. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  38384. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  38385. // where explicit usemtl defines geometry groups.
  38386. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  38387. /*
  38388. * http://paulbourke.net/dataformats/obj/
  38389. * or
  38390. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  38391. *
  38392. * From chapter "Grouping" Syntax explanation "s group_number":
  38393. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  38394. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  38395. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  38396. * than 0."
  38397. */
  38398. if ( result.length > 1 ) {
  38399. var value = result[ 1 ].trim().toLowerCase();
  38400. state.object.smooth = ( value !== '0' && value !== 'off' );
  38401. } else {
  38402. // ZBrush can produce "s" lines #11707
  38403. state.object.smooth = true;
  38404. }
  38405. var material = state.object.currentMaterial();
  38406. if ( material ) material.smooth = state.object.smooth;
  38407. } else {
  38408. // Handle null terminated files without exception
  38409. if ( line === '\0' ) continue;
  38410. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  38411. }
  38412. }
  38413. state.finalize();
  38414. var container = new THREE.Group();
  38415. container.materialLibraries = [].concat( state.materialLibraries );
  38416. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  38417. var object = state.objects[ i ];
  38418. var geometry = object.geometry;
  38419. var materials = object.materials;
  38420. var isLine = ( geometry.type === 'Line' );
  38421. var isPoints = ( geometry.type === 'Points' );
  38422. var hasVertexColors = false;
  38423. // Skip o/g line declarations that did not follow with any faces
  38424. if ( geometry.vertices.length === 0 ) continue;
  38425. var buffergeometry = new THREE.BufferGeometry();
  38426. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  38427. if ( geometry.normals.length > 0 ) {
  38428. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  38429. } else {
  38430. buffergeometry.computeVertexNormals();
  38431. }
  38432. if ( geometry.colors.length > 0 ) {
  38433. hasVertexColors = true;
  38434. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  38435. }
  38436. if ( geometry.uvs.length > 0 ) {
  38437. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  38438. }
  38439. // Create materials
  38440. var createdMaterials = [];
  38441. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  38442. var sourceMaterial = materials[ mi ];
  38443. var material = undefined;
  38444. if ( this.materials !== null ) {
  38445. material = this.materials.create( sourceMaterial.name );
  38446. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  38447. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  38448. var materialLine = new THREE.LineBasicMaterial();
  38449. THREE.Material.prototype.copy.call( materialLine, material );
  38450. materialLine.color.copy( material.color );
  38451. materialLine.lights = false;
  38452. material = materialLine;
  38453. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  38454. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  38455. THREE.Material.prototype.copy.call( materialPoints, material );
  38456. materialPoints.color.copy( material.color );
  38457. materialPoints.map = material.map;
  38458. materialPoints.lights = false;
  38459. material = materialPoints;
  38460. }
  38461. }
  38462. if ( ! material ) {
  38463. if ( isLine ) {
  38464. material = new THREE.LineBasicMaterial();
  38465. } else if ( isPoints ) {
  38466. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  38467. } else {
  38468. material = new THREE.MeshPhongMaterial();
  38469. }
  38470. material.name = sourceMaterial.name;
  38471. }
  38472. material.flatShading = sourceMaterial.smooth ? false : true;
  38473. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  38474. createdMaterials.push( material );
  38475. }
  38476. // Create mesh
  38477. var mesh;
  38478. if ( createdMaterials.length > 1 ) {
  38479. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  38480. var sourceMaterial = materials[ mi ];
  38481. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  38482. }
  38483. if ( isLine ) {
  38484. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  38485. } else if ( isPoints ) {
  38486. mesh = new THREE.Points( buffergeometry, createdMaterials );
  38487. } else {
  38488. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  38489. }
  38490. } else {
  38491. if ( isLine ) {
  38492. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  38493. } else if ( isPoints ) {
  38494. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  38495. } else {
  38496. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  38497. }
  38498. }
  38499. mesh.name = object.name;
  38500. container.add( mesh );
  38501. }
  38502. console.timeEnd( 'OBJLoader' );
  38503. return container;
  38504. }
  38505. } );
  38506. return OBJLoader;
  38507. } )();
  38508. },{}],62:[function(_dereq_,module,exports){
  38509. var createLayout = _dereq_('layout-bmfont-text')
  38510. var inherits = _dereq_('inherits')
  38511. var createIndices = _dereq_('quad-indices')
  38512. var buffer = _dereq_('three-buffer-vertex-data')
  38513. var assign = _dereq_('object-assign')
  38514. var vertices = _dereq_('./lib/vertices')
  38515. var utils = _dereq_('./lib/utils')
  38516. var Base = THREE.BufferGeometry
  38517. module.exports = function createTextGeometry (opt) {
  38518. return new TextGeometry(opt)
  38519. }
  38520. function TextGeometry (opt) {
  38521. Base.call(this)
  38522. if (typeof opt === 'string') {
  38523. opt = { text: opt }
  38524. }
  38525. // use these as default values for any subsequent
  38526. // calls to update()
  38527. this._opt = assign({}, opt)
  38528. // also do an initial setup...
  38529. if (opt) this.update(opt)
  38530. }
  38531. inherits(TextGeometry, Base)
  38532. TextGeometry.prototype.update = function (opt) {
  38533. if (typeof opt === 'string') {
  38534. opt = { text: opt }
  38535. }
  38536. // use constructor defaults
  38537. opt = assign({}, this._opt, opt)
  38538. if (!opt.font) {
  38539. throw new TypeError('must specify a { font } in options')
  38540. }
  38541. this.layout = createLayout(opt)
  38542. // get vec2 texcoords
  38543. var flipY = opt.flipY !== false
  38544. // the desired BMFont data
  38545. var font = opt.font
  38546. // determine texture size from font file
  38547. var texWidth = font.common.scaleW
  38548. var texHeight = font.common.scaleH
  38549. // get visible glyphs
  38550. var glyphs = this.layout.glyphs.filter(function (glyph) {
  38551. var bitmap = glyph.data
  38552. return bitmap.width * bitmap.height > 0
  38553. })
  38554. // provide visible glyphs for convenience
  38555. this.visibleGlyphs = glyphs
  38556. // get common vertex data
  38557. var positions = vertices.positions(glyphs)
  38558. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  38559. var indices = createIndices({
  38560. clockwise: true,
  38561. type: 'uint16',
  38562. count: glyphs.length
  38563. })
  38564. // update vertex data
  38565. buffer.index(this, indices, 1, 'uint16')
  38566. buffer.attr(this, 'position', positions, 2)
  38567. buffer.attr(this, 'uv', uvs, 2)
  38568. // update multipage data
  38569. if (!opt.multipage && 'page' in this.attributes) {
  38570. // disable multipage rendering
  38571. this.removeAttribute('page')
  38572. } else if (opt.multipage) {
  38573. var pages = vertices.pages(glyphs)
  38574. // enable multipage rendering
  38575. buffer.attr(this, 'page', pages, 1)
  38576. }
  38577. }
  38578. TextGeometry.prototype.computeBoundingSphere = function () {
  38579. if (this.boundingSphere === null) {
  38580. this.boundingSphere = new THREE.Sphere()
  38581. }
  38582. var positions = this.attributes.position.array
  38583. var itemSize = this.attributes.position.itemSize
  38584. if (!positions || !itemSize || positions.length < 2) {
  38585. this.boundingSphere.radius = 0
  38586. this.boundingSphere.center.set(0, 0, 0)
  38587. return
  38588. }
  38589. utils.computeSphere(positions, this.boundingSphere)
  38590. if (isNaN(this.boundingSphere.radius)) {
  38591. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  38592. 'Computed radius is NaN. The ' +
  38593. '"position" attribute is likely to have NaN values.')
  38594. }
  38595. }
  38596. TextGeometry.prototype.computeBoundingBox = function () {
  38597. if (this.boundingBox === null) {
  38598. this.boundingBox = new THREE.Box3()
  38599. }
  38600. var bbox = this.boundingBox
  38601. var positions = this.attributes.position.array
  38602. var itemSize = this.attributes.position.itemSize
  38603. if (!positions || !itemSize || positions.length < 2) {
  38604. bbox.makeEmpty()
  38605. return
  38606. }
  38607. utils.computeBox(positions, bbox)
  38608. }
  38609. },{"./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){
  38610. var itemSize = 2
  38611. var box = { min: [0, 0], max: [0, 0] }
  38612. function bounds (positions) {
  38613. var count = positions.length / itemSize
  38614. box.min[0] = positions[0]
  38615. box.min[1] = positions[1]
  38616. box.max[0] = positions[0]
  38617. box.max[1] = positions[1]
  38618. for (var i = 0; i < count; i++) {
  38619. var x = positions[i * itemSize + 0]
  38620. var y = positions[i * itemSize + 1]
  38621. box.min[0] = Math.min(x, box.min[0])
  38622. box.min[1] = Math.min(y, box.min[1])
  38623. box.max[0] = Math.max(x, box.max[0])
  38624. box.max[1] = Math.max(y, box.max[1])
  38625. }
  38626. }
  38627. module.exports.computeBox = function (positions, output) {
  38628. bounds(positions)
  38629. output.min.set(box.min[0], box.min[1], 0)
  38630. output.max.set(box.max[0], box.max[1], 0)
  38631. }
  38632. module.exports.computeSphere = function (positions, output) {
  38633. bounds(positions)
  38634. var minX = box.min[0]
  38635. var minY = box.min[1]
  38636. var maxX = box.max[0]
  38637. var maxY = box.max[1]
  38638. var width = maxX - minX
  38639. var height = maxY - minY
  38640. var length = Math.sqrt(width * width + height * height)
  38641. output.center.set(minX + width / 2, minY + height / 2, 0)
  38642. output.radius = length / 2
  38643. }
  38644. },{}],64:[function(_dereq_,module,exports){
  38645. module.exports.pages = function pages (glyphs) {
  38646. var pages = new Float32Array(glyphs.length * 4 * 1)
  38647. var i = 0
  38648. glyphs.forEach(function (glyph) {
  38649. var id = glyph.data.page || 0
  38650. pages[i++] = id
  38651. pages[i++] = id
  38652. pages[i++] = id
  38653. pages[i++] = id
  38654. })
  38655. return pages
  38656. }
  38657. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  38658. var uvs = new Float32Array(glyphs.length * 4 * 2)
  38659. var i = 0
  38660. glyphs.forEach(function (glyph) {
  38661. var bitmap = glyph.data
  38662. var bw = (bitmap.x + bitmap.width)
  38663. var bh = (bitmap.y + bitmap.height)
  38664. // top left position
  38665. var u0 = bitmap.x / texWidth
  38666. var v1 = bitmap.y / texHeight
  38667. var u1 = bw / texWidth
  38668. var v0 = bh / texHeight
  38669. if (flipY) {
  38670. v1 = (texHeight - bitmap.y) / texHeight
  38671. v0 = (texHeight - bh) / texHeight
  38672. }
  38673. // BL
  38674. uvs[i++] = u0
  38675. uvs[i++] = v1
  38676. // TL
  38677. uvs[i++] = u0
  38678. uvs[i++] = v0
  38679. // TR
  38680. uvs[i++] = u1
  38681. uvs[i++] = v0
  38682. // BR
  38683. uvs[i++] = u1
  38684. uvs[i++] = v1
  38685. })
  38686. return uvs
  38687. }
  38688. module.exports.positions = function positions (glyphs) {
  38689. var positions = new Float32Array(glyphs.length * 4 * 2)
  38690. var i = 0
  38691. glyphs.forEach(function (glyph) {
  38692. var bitmap = glyph.data
  38693. // bottom left position
  38694. var x = glyph.position[0] + bitmap.xoffset
  38695. var y = glyph.position[1] + bitmap.yoffset
  38696. // quad size
  38697. var w = bitmap.width
  38698. var h = bitmap.height
  38699. // BL
  38700. positions[i++] = x
  38701. positions[i++] = y
  38702. // TL
  38703. positions[i++] = x
  38704. positions[i++] = y + h
  38705. // TR
  38706. positions[i++] = x + w
  38707. positions[i++] = y + h
  38708. // BR
  38709. positions[i++] = x + w
  38710. positions[i++] = y
  38711. })
  38712. return positions
  38713. }
  38714. },{}],65:[function(_dereq_,module,exports){
  38715. var flatten = _dereq_('flatten-vertex-data')
  38716. var warned = false;
  38717. module.exports.attr = setAttribute
  38718. module.exports.index = setIndex
  38719. function setIndex (geometry, data, itemSize, dtype) {
  38720. if (typeof itemSize !== 'number') itemSize = 1
  38721. if (typeof dtype !== 'string') dtype = 'uint16'
  38722. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  38723. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  38724. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  38725. if (newAttrib) {
  38726. if (isR69) geometry.addAttribute('index', newAttrib)
  38727. else geometry.index = newAttrib
  38728. }
  38729. }
  38730. function setAttribute (geometry, key, data, itemSize, dtype) {
  38731. if (typeof itemSize !== 'number') itemSize = 3
  38732. if (typeof dtype !== 'string') dtype = 'float32'
  38733. if (Array.isArray(data) &&
  38734. Array.isArray(data[0]) &&
  38735. data[0].length !== itemSize) {
  38736. throw new Error('Nested vertex array has unexpected size; expected ' +
  38737. itemSize + ' but found ' + data[0].length)
  38738. }
  38739. var attrib = geometry.getAttribute(key)
  38740. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  38741. if (newAttrib) {
  38742. geometry.addAttribute(key, newAttrib)
  38743. }
  38744. }
  38745. function updateAttribute (attrib, data, itemSize, dtype) {
  38746. data = data || []
  38747. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  38748. // create a new array with desired type
  38749. data = flatten(data, dtype)
  38750. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  38751. if (!attrib || needsNewBuffer) {
  38752. // We are on an old version of ThreeJS which can't
  38753. // support growing / shrinking buffers, so we need
  38754. // to build a new buffer
  38755. if (needsNewBuffer && !warned) {
  38756. warned = true
  38757. console.warn([
  38758. 'A WebGL buffer is being updated with a new size or itemSize, ',
  38759. 'however this version of ThreeJS only supports fixed-size buffers.',
  38760. '\nThe old buffer may still be kept in memory.\n',
  38761. 'To avoid memory leaks, it is recommended that you dispose ',
  38762. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  38763. 'See here for discussion:\n',
  38764. 'https://github.com/mrdoob/three.js/pull/9631'
  38765. ].join(''))
  38766. }
  38767. // Build a new attribute
  38768. attrib = new THREE.BufferAttribute(data, itemSize);
  38769. }
  38770. attrib.itemSize = itemSize
  38771. attrib.needsUpdate = true
  38772. // New versions of ThreeJS suggest using setArray
  38773. // to change the data. It will use bufferData internally,
  38774. // so you can change the array size without any issues
  38775. if (typeof attrib.setArray === 'function') {
  38776. attrib.setArray(data)
  38777. }
  38778. return attrib
  38779. } else {
  38780. // copy data into the existing array
  38781. flatten(data, attrib.array)
  38782. attrib.needsUpdate = true
  38783. return null
  38784. }
  38785. }
  38786. // Test whether the attribute needs to be re-created,
  38787. // returns false if we can re-use it as-is.
  38788. function rebuildAttribute (attrib, data, itemSize) {
  38789. if (attrib.itemSize !== itemSize) return true
  38790. if (!attrib.array) return true
  38791. var attribLength = attrib.array.length
  38792. if (Array.isArray(data) && Array.isArray(data[0])) {
  38793. // [ [ x, y, z ] ]
  38794. return attribLength !== data.length * itemSize
  38795. } else {
  38796. // [ x, y, z ]
  38797. return attribLength !== data.length
  38798. }
  38799. return false
  38800. }
  38801. },{"flatten-vertex-data":23}],66:[function(_dereq_,module,exports){
  38802. (function (setImmediate,clearImmediate){
  38803. var nextTick = _dereq_('process/browser.js').nextTick;
  38804. var apply = Function.prototype.apply;
  38805. var slice = Array.prototype.slice;
  38806. var immediateIds = {};
  38807. var nextImmediateId = 0;
  38808. // DOM APIs, for completeness
  38809. exports.setTimeout = function() {
  38810. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  38811. };
  38812. exports.setInterval = function() {
  38813. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  38814. };
  38815. exports.clearTimeout =
  38816. exports.clearInterval = function(timeout) { timeout.close(); };
  38817. function Timeout(id, clearFn) {
  38818. this._id = id;
  38819. this._clearFn = clearFn;
  38820. }
  38821. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  38822. Timeout.prototype.close = function() {
  38823. this._clearFn.call(window, this._id);
  38824. };
  38825. // Does not start the time, just sets up the members needed.
  38826. exports.enroll = function(item, msecs) {
  38827. clearTimeout(item._idleTimeoutId);
  38828. item._idleTimeout = msecs;
  38829. };
  38830. exports.unenroll = function(item) {
  38831. clearTimeout(item._idleTimeoutId);
  38832. item._idleTimeout = -1;
  38833. };
  38834. exports._unrefActive = exports.active = function(item) {
  38835. clearTimeout(item._idleTimeoutId);
  38836. var msecs = item._idleTimeout;
  38837. if (msecs >= 0) {
  38838. item._idleTimeoutId = setTimeout(function onTimeout() {
  38839. if (item._onTimeout)
  38840. item._onTimeout();
  38841. }, msecs);
  38842. }
  38843. };
  38844. // That's not how node.js implements it but the exposed api is the same.
  38845. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  38846. var id = nextImmediateId++;
  38847. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  38848. immediateIds[id] = true;
  38849. nextTick(function onNextTick() {
  38850. if (immediateIds[id]) {
  38851. // fn.call() is faster so we optimize for the common use-case
  38852. // @see http://jsperf.com/call-apply-segu
  38853. if (args) {
  38854. fn.apply(null, args);
  38855. } else {
  38856. fn.call(null);
  38857. }
  38858. // Prevent ids from leaking
  38859. exports.clearImmediate(id);
  38860. }
  38861. });
  38862. return id;
  38863. };
  38864. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  38865. delete immediateIds[id];
  38866. };
  38867. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  38868. },{"process/browser.js":49,"timers":66}],67:[function(_dereq_,module,exports){
  38869. (function (global){
  38870. /**
  38871. * @license
  38872. * webvr-polyfill
  38873. * Copyright (c) 2015-2017 Google
  38874. * Licensed under the Apache License, Version 2.0 (the "License");
  38875. * you may not use this file except in compliance with the License.
  38876. * You may obtain a copy of the License at
  38877. *
  38878. * http://www.apache.org/licenses/LICENSE-2.0
  38879. *
  38880. * Unless required by applicable law or agreed to in writing, software
  38881. * distributed under the License is distributed on an "AS IS" BASIS,
  38882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38883. * See the License for the specific language governing permissions and
  38884. * limitations under the License.
  38885. */
  38886. /**
  38887. * @license
  38888. * cardboard-vr-display
  38889. * Copyright (c) 2015-2017 Google
  38890. * Licensed under the Apache License, Version 2.0 (the "License");
  38891. * you may not use this file except in compliance with the License.
  38892. * You may obtain a copy of the License at
  38893. *
  38894. * http://www.apache.org/licenses/LICENSE-2.0
  38895. *
  38896. * Unless required by applicable law or agreed to in writing, software
  38897. * distributed under the License is distributed on an "AS IS" BASIS,
  38898. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38899. * See the License for the specific language governing permissions and
  38900. * limitations under the License.
  38901. */
  38902. /**
  38903. * @license
  38904. * webvr-polyfill-dpdb
  38905. * Copyright (c) 2017 Google
  38906. * Licensed under the Apache License, Version 2.0 (the "License");
  38907. * you may not use this file except in compliance with the License.
  38908. * You may obtain a copy of the License at
  38909. *
  38910. * http://www.apache.org/licenses/LICENSE-2.0
  38911. *
  38912. * Unless required by applicable law or agreed to in writing, software
  38913. * distributed under the License is distributed on an "AS IS" BASIS,
  38914. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38915. * See the License for the specific language governing permissions and
  38916. * limitations under the License.
  38917. */
  38918. /**
  38919. * @license
  38920. * wglu-preserve-state
  38921. * Copyright (c) 2016, Brandon Jones.
  38922. *
  38923. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38924. * of this software and associated documentation files (the "Software"), to deal
  38925. * in the Software without restriction, including without limitation the rights
  38926. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38927. * copies of the Software, and to permit persons to whom the Software is
  38928. * furnished to do so, subject to the following conditions:
  38929. *
  38930. * The above copyright notice and this permission notice shall be included in
  38931. * all copies or substantial portions of the Software.
  38932. *
  38933. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38934. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38935. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38936. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38937. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38938. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38939. * THE SOFTWARE.
  38940. */
  38941. /**
  38942. * @license
  38943. * nosleep.js
  38944. * Copyright (c) 2017, Rich Tibbett
  38945. *
  38946. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38947. * of this software and associated documentation files (the "Software"), to deal
  38948. * in the Software without restriction, including without limitation the rights
  38949. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38950. * copies of the Software, and to permit persons to whom the Software is
  38951. * furnished to do so, subject to the following conditions:
  38952. *
  38953. * The above copyright notice and this permission notice shall be included in
  38954. * all copies or substantial portions of the Software.
  38955. *
  38956. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38957. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38958. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38959. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38960. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38961. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38962. * THE SOFTWARE.
  38963. */
  38964. (function (global, factory) {
  38965. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  38966. typeof define === 'function' && define.amd ? define(factory) :
  38967. (global.WebVRPolyfill = factory());
  38968. }(this, (function () { 'use strict';
  38969. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  38970. function unwrapExports (x) {
  38971. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  38972. }
  38973. function createCommonjsModule(fn, module) {
  38974. return module = { exports: {} }, fn(module, module.exports), module.exports;
  38975. }
  38976. var isMobile = function isMobile() {
  38977. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  38978. );
  38979. };
  38980. var copyArray = function copyArray(source, dest) {
  38981. for (var i = 0, n = source.length; i < n; i++) {
  38982. dest[i] = source[i];
  38983. }
  38984. };
  38985. var extend = function extend(dest, src) {
  38986. for (var key in src) {
  38987. if (src.hasOwnProperty(key)) {
  38988. dest[key] = src[key];
  38989. }
  38990. }
  38991. return dest;
  38992. };
  38993. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  38994. /**
  38995. * @license
  38996. * cardboard-vr-display
  38997. * Copyright (c) 2015-2017 Google
  38998. * Licensed under the Apache License, Version 2.0 (the "License");
  38999. * you may not use this file except in compliance with the License.
  39000. * You may obtain a copy of the License at
  39001. *
  39002. * http://www.apache.org/licenses/LICENSE-2.0
  39003. *
  39004. * Unless required by applicable law or agreed to in writing, software
  39005. * distributed under the License is distributed on an "AS IS" BASIS,
  39006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39007. * See the License for the specific language governing permissions and
  39008. * limitations under the License.
  39009. */
  39010. /**
  39011. * @license
  39012. * gl-preserve-state
  39013. * Copyright (c) 2016, Brandon Jones.
  39014. *
  39015. * Permission is hereby granted, free of charge, to any person obtaining a copy
  39016. * of this software and associated documentation files (the "Software"), to deal
  39017. * in the Software without restriction, including without limitation the rights
  39018. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  39019. * copies of the Software, and to permit persons to whom the Software is
  39020. * furnished to do so, subject to the following conditions:
  39021. *
  39022. * The above copyright notice and this permission notice shall be included in
  39023. * all copies or substantial portions of the Software.
  39024. *
  39025. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39026. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39027. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39028. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39029. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  39030. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  39031. * THE SOFTWARE.
  39032. */
  39033. /**
  39034. * @license
  39035. * webvr-polyfill-dpdb
  39036. * Copyright (c) 2015-2017 Google
  39037. * Licensed under the Apache License, Version 2.0 (the "License");
  39038. * you may not use this file except in compliance with the License.
  39039. * You may obtain a copy of the License at
  39040. *
  39041. * http://www.apache.org/licenses/LICENSE-2.0
  39042. *
  39043. * Unless required by applicable law or agreed to in writing, software
  39044. * distributed under the License is distributed on an "AS IS" BASIS,
  39045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39046. * See the License for the specific language governing permissions and
  39047. * limitations under the License.
  39048. */
  39049. /**
  39050. * @license
  39051. * nosleep.js
  39052. * Copyright (c) 2017, Rich Tibbett
  39053. *
  39054. * Permission is hereby granted, free of charge, to any person obtaining a copy
  39055. * of this software and associated documentation files (the "Software"), to deal
  39056. * in the Software without restriction, including without limitation the rights
  39057. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  39058. * copies of the Software, and to permit persons to whom the Software is
  39059. * furnished to do so, subject to the following conditions:
  39060. *
  39061. * The above copyright notice and this permission notice shall be included in
  39062. * all copies or substantial portions of the Software.
  39063. *
  39064. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39065. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39066. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39067. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39068. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  39069. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  39070. * THE SOFTWARE.
  39071. */
  39072. (function (global, factory) {
  39073. module.exports = factory();
  39074. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  39075. if (!(instance instanceof Constructor)) {
  39076. throw new TypeError("Cannot call a class as a function");
  39077. }
  39078. };
  39079. var createClass = function () {
  39080. function defineProperties(target, props) {
  39081. for (var i = 0; i < props.length; i++) {
  39082. var descriptor = props[i];
  39083. descriptor.enumerable = descriptor.enumerable || false;
  39084. descriptor.configurable = true;
  39085. if ("value" in descriptor) descriptor.writable = true;
  39086. Object.defineProperty(target, descriptor.key, descriptor);
  39087. }
  39088. }
  39089. return function (Constructor, protoProps, staticProps) {
  39090. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  39091. if (staticProps) defineProperties(Constructor, staticProps);
  39092. return Constructor;
  39093. };
  39094. }();
  39095. var slicedToArray = function () {
  39096. function sliceIterator(arr, i) {
  39097. var _arr = [];
  39098. var _n = true;
  39099. var _d = false;
  39100. var _e = undefined;
  39101. try {
  39102. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  39103. _arr.push(_s.value);
  39104. if (i && _arr.length === i) break;
  39105. }
  39106. } catch (err) {
  39107. _d = true;
  39108. _e = err;
  39109. } finally {
  39110. try {
  39111. if (!_n && _i["return"]) _i["return"]();
  39112. } finally {
  39113. if (_d) throw _e;
  39114. }
  39115. }
  39116. return _arr;
  39117. }
  39118. return function (arr, i) {
  39119. if (Array.isArray(arr)) {
  39120. return arr;
  39121. } else if (Symbol.iterator in Object(arr)) {
  39122. return sliceIterator(arr, i);
  39123. } else {
  39124. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  39125. }
  39126. };
  39127. }();
  39128. var MIN_TIMESTEP = 0.001;
  39129. var MAX_TIMESTEP = 1;
  39130. var dataUri = function dataUri(mimeType, svg) {
  39131. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  39132. };
  39133. var lerp = function lerp(a, b, t) {
  39134. return a + (b - a) * t;
  39135. };
  39136. var isIOS = function () {
  39137. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  39138. return function () {
  39139. return isIOS;
  39140. };
  39141. }();
  39142. var isWebViewAndroid = function () {
  39143. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  39144. return function () {
  39145. return isWebViewAndroid;
  39146. };
  39147. }();
  39148. var isSafari = function () {
  39149. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  39150. return function () {
  39151. return isSafari;
  39152. };
  39153. }();
  39154. var isFirefoxAndroid = function () {
  39155. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  39156. return function () {
  39157. return isFirefoxAndroid;
  39158. };
  39159. }();
  39160. var getChromeVersion = function () {
  39161. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  39162. var value = match ? parseInt(match[1], 10) : null;
  39163. return function () {
  39164. return value;
  39165. };
  39166. }();
  39167. var isChromeWithoutDeviceMotion = function () {
  39168. var value = false;
  39169. if (getChromeVersion() === 65) {
  39170. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  39171. if (match) {
  39172. var _match$1$split = match[1].split('.'),
  39173. _match$1$split2 = slicedToArray(_match$1$split, 4),
  39174. major = _match$1$split2[0],
  39175. minor = _match$1$split2[1],
  39176. branch = _match$1$split2[2],
  39177. build = _match$1$split2[3];
  39178. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  39179. }
  39180. }
  39181. return function () {
  39182. return value;
  39183. };
  39184. }();
  39185. var isR7 = function () {
  39186. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  39187. return function () {
  39188. return isR7;
  39189. };
  39190. }();
  39191. var isLandscapeMode = function isLandscapeMode() {
  39192. var rtn = window.orientation == 90 || window.orientation == -90;
  39193. return isR7() ? !rtn : rtn;
  39194. };
  39195. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  39196. if (isNaN(timestampDeltaS)) {
  39197. return false;
  39198. }
  39199. if (timestampDeltaS <= MIN_TIMESTEP) {
  39200. return false;
  39201. }
  39202. if (timestampDeltaS > MAX_TIMESTEP) {
  39203. return false;
  39204. }
  39205. return true;
  39206. };
  39207. var getScreenWidth = function getScreenWidth() {
  39208. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  39209. };
  39210. var getScreenHeight = function getScreenHeight() {
  39211. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  39212. };
  39213. var requestFullscreen = function requestFullscreen(element) {
  39214. if (isWebViewAndroid()) {
  39215. return false;
  39216. }
  39217. if (element.requestFullscreen) {
  39218. element.requestFullscreen();
  39219. } else if (element.webkitRequestFullscreen) {
  39220. element.webkitRequestFullscreen();
  39221. } else if (element.mozRequestFullScreen) {
  39222. element.mozRequestFullScreen();
  39223. } else if (element.msRequestFullscreen) {
  39224. element.msRequestFullscreen();
  39225. } else {
  39226. return false;
  39227. }
  39228. return true;
  39229. };
  39230. var exitFullscreen = function exitFullscreen() {
  39231. if (document.exitFullscreen) {
  39232. document.exitFullscreen();
  39233. } else if (document.webkitExitFullscreen) {
  39234. document.webkitExitFullscreen();
  39235. } else if (document.mozCancelFullScreen) {
  39236. document.mozCancelFullScreen();
  39237. } else if (document.msExitFullscreen) {
  39238. document.msExitFullscreen();
  39239. } else {
  39240. return false;
  39241. }
  39242. return true;
  39243. };
  39244. var getFullscreenElement = function getFullscreenElement() {
  39245. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  39246. };
  39247. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  39248. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  39249. gl.shaderSource(vertexShader, vertexSource);
  39250. gl.compileShader(vertexShader);
  39251. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  39252. gl.shaderSource(fragmentShader, fragmentSource);
  39253. gl.compileShader(fragmentShader);
  39254. var program = gl.createProgram();
  39255. gl.attachShader(program, vertexShader);
  39256. gl.attachShader(program, fragmentShader);
  39257. for (var attribName in attribLocationMap) {
  39258. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  39259. }gl.linkProgram(program);
  39260. gl.deleteShader(vertexShader);
  39261. gl.deleteShader(fragmentShader);
  39262. return program;
  39263. };
  39264. var getProgramUniforms = function getProgramUniforms(gl, program) {
  39265. var uniforms = {};
  39266. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  39267. var uniformName = '';
  39268. for (var i = 0; i < uniformCount; i++) {
  39269. var uniformInfo = gl.getActiveUniform(program, i);
  39270. uniformName = uniformInfo.name.replace('[0]', '');
  39271. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  39272. }
  39273. return uniforms;
  39274. };
  39275. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  39276. var lr = 1 / (left - right),
  39277. bt = 1 / (bottom - top),
  39278. nf = 1 / (near - far);
  39279. out[0] = -2 * lr;
  39280. out[1] = 0;
  39281. out[2] = 0;
  39282. out[3] = 0;
  39283. out[4] = 0;
  39284. out[5] = -2 * bt;
  39285. out[6] = 0;
  39286. out[7] = 0;
  39287. out[8] = 0;
  39288. out[9] = 0;
  39289. out[10] = 2 * nf;
  39290. out[11] = 0;
  39291. out[12] = (left + right) * lr;
  39292. out[13] = (top + bottom) * bt;
  39293. out[14] = (far + near) * nf;
  39294. out[15] = 1;
  39295. return out;
  39296. };
  39297. var isMobile = function isMobile() {
  39298. var check = false;
  39299. (function (a) {
  39300. 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;
  39301. })(navigator.userAgent || navigator.vendor || window.opera);
  39302. return check;
  39303. };
  39304. var extend = function extend(dest, src) {
  39305. for (var key in src) {
  39306. if (src.hasOwnProperty(key)) {
  39307. dest[key] = src[key];
  39308. }
  39309. }
  39310. return dest;
  39311. };
  39312. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  39313. if (isIOS()) {
  39314. var width = canvas.style.width;
  39315. var height = canvas.style.height;
  39316. canvas.style.width = parseInt(width) + 1 + 'px';
  39317. canvas.style.height = parseInt(height) + 'px';
  39318. setTimeout(function () {
  39319. canvas.style.width = width;
  39320. canvas.style.height = height;
  39321. }, 100);
  39322. }
  39323. window.canvas = canvas;
  39324. };
  39325. var frameDataFromPose = function () {
  39326. var piOver180 = Math.PI / 180.0;
  39327. var rad45 = Math.PI * 0.25;
  39328. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  39329. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  39330. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  39331. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  39332. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  39333. xScale = 2.0 / (leftTan + rightTan),
  39334. yScale = 2.0 / (upTan + downTan);
  39335. out[0] = xScale;
  39336. out[1] = 0.0;
  39337. out[2] = 0.0;
  39338. out[3] = 0.0;
  39339. out[4] = 0.0;
  39340. out[5] = yScale;
  39341. out[6] = 0.0;
  39342. out[7] = 0.0;
  39343. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  39344. out[9] = (upTan - downTan) * yScale * 0.5;
  39345. out[10] = far / (near - far);
  39346. out[11] = -1.0;
  39347. out[12] = 0.0;
  39348. out[13] = 0.0;
  39349. out[14] = far * near / (near - far);
  39350. out[15] = 0.0;
  39351. return out;
  39352. }
  39353. function mat4_fromRotationTranslation(out, q, v) {
  39354. var x = q[0],
  39355. y = q[1],
  39356. z = q[2],
  39357. w = q[3],
  39358. x2 = x + x,
  39359. y2 = y + y,
  39360. z2 = z + z,
  39361. xx = x * x2,
  39362. xy = x * y2,
  39363. xz = x * z2,
  39364. yy = y * y2,
  39365. yz = y * z2,
  39366. zz = z * z2,
  39367. wx = w * x2,
  39368. wy = w * y2,
  39369. wz = w * z2;
  39370. out[0] = 1 - (yy + zz);
  39371. out[1] = xy + wz;
  39372. out[2] = xz - wy;
  39373. out[3] = 0;
  39374. out[4] = xy - wz;
  39375. out[5] = 1 - (xx + zz);
  39376. out[6] = yz + wx;
  39377. out[7] = 0;
  39378. out[8] = xz + wy;
  39379. out[9] = yz - wx;
  39380. out[10] = 1 - (xx + yy);
  39381. out[11] = 0;
  39382. out[12] = v[0];
  39383. out[13] = v[1];
  39384. out[14] = v[2];
  39385. out[15] = 1;
  39386. return out;
  39387. }
  39388. function mat4_translate(out, a, v) {
  39389. var x = v[0],
  39390. y = v[1],
  39391. z = v[2],
  39392. a00,
  39393. a01,
  39394. a02,
  39395. a03,
  39396. a10,
  39397. a11,
  39398. a12,
  39399. a13,
  39400. a20,
  39401. a21,
  39402. a22,
  39403. a23;
  39404. if (a === out) {
  39405. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  39406. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  39407. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  39408. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  39409. } else {
  39410. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  39411. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  39412. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  39413. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  39414. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  39415. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  39416. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  39417. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  39418. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  39419. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  39420. }
  39421. return out;
  39422. }
  39423. function mat4_invert(out, a) {
  39424. var a00 = a[0],
  39425. a01 = a[1],
  39426. a02 = a[2],
  39427. a03 = a[3],
  39428. a10 = a[4],
  39429. a11 = a[5],
  39430. a12 = a[6],
  39431. a13 = a[7],
  39432. a20 = a[8],
  39433. a21 = a[9],
  39434. a22 = a[10],
  39435. a23 = a[11],
  39436. a30 = a[12],
  39437. a31 = a[13],
  39438. a32 = a[14],
  39439. a33 = a[15],
  39440. b00 = a00 * a11 - a01 * a10,
  39441. b01 = a00 * a12 - a02 * a10,
  39442. b02 = a00 * a13 - a03 * a10,
  39443. b03 = a01 * a12 - a02 * a11,
  39444. b04 = a01 * a13 - a03 * a11,
  39445. b05 = a02 * a13 - a03 * a12,
  39446. b06 = a20 * a31 - a21 * a30,
  39447. b07 = a20 * a32 - a22 * a30,
  39448. b08 = a20 * a33 - a23 * a30,
  39449. b09 = a21 * a32 - a22 * a31,
  39450. b10 = a21 * a33 - a23 * a31,
  39451. b11 = a22 * a33 - a23 * a32,
  39452. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  39453. if (!det) {
  39454. return null;
  39455. }
  39456. det = 1.0 / det;
  39457. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  39458. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  39459. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  39460. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  39461. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  39462. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  39463. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  39464. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  39465. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  39466. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  39467. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  39468. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  39469. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  39470. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  39471. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  39472. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  39473. return out;
  39474. }
  39475. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  39476. var defaultPosition = new Float32Array([0, 0, 0]);
  39477. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  39478. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  39479. var orientation = pose.orientation || defaultOrientation;
  39480. var position = pose.position || defaultPosition;
  39481. mat4_fromRotationTranslation(view, orientation, position);
  39482. if (offset) mat4_translate(view, view, offset);
  39483. mat4_invert(view, view);
  39484. }
  39485. return function (frameData, pose, vrDisplay) {
  39486. if (!frameData || !pose) return false;
  39487. frameData.pose = pose;
  39488. frameData.timestamp = pose.timestamp;
  39489. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  39490. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  39491. return true;
  39492. };
  39493. }();
  39494. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  39495. var isFramed = window.self !== window.top;
  39496. var refOrigin = getOriginFromUrl(document.referrer);
  39497. var thisOrigin = getOriginFromUrl(window.location.href);
  39498. return isFramed && refOrigin !== thisOrigin;
  39499. };
  39500. var getOriginFromUrl = function getOriginFromUrl(url) {
  39501. var domainIdx;
  39502. var protoSepIdx = url.indexOf("://");
  39503. if (protoSepIdx !== -1) {
  39504. domainIdx = protoSepIdx + 3;
  39505. } else {
  39506. domainIdx = 0;
  39507. }
  39508. var domainEndIdx = url.indexOf('/', domainIdx);
  39509. if (domainEndIdx === -1) {
  39510. domainEndIdx = url.length;
  39511. }
  39512. return url.substring(0, domainEndIdx);
  39513. };
  39514. var getQuaternionAngle = function getQuaternionAngle(quat) {
  39515. if (quat.w > 1) {
  39516. console.warn('getQuaternionAngle: w > 1');
  39517. return 0;
  39518. }
  39519. var angle = 2 * Math.acos(quat.w);
  39520. return angle;
  39521. };
  39522. var warnOnce = function () {
  39523. var observedWarnings = {};
  39524. return function (key, message) {
  39525. if (observedWarnings[key] === undefined) {
  39526. console.warn('webvr-polyfill: ' + message);
  39527. observedWarnings[key] = true;
  39528. }
  39529. };
  39530. }();
  39531. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  39532. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  39533. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  39534. };
  39535. function WGLUPreserveGLState(gl, bindings, callback) {
  39536. if (!bindings) {
  39537. callback(gl);
  39538. return;
  39539. }
  39540. var boundValues = [];
  39541. var activeTexture = null;
  39542. for (var i = 0; i < bindings.length; ++i) {
  39543. var binding = bindings[i];
  39544. switch (binding) {
  39545. case gl.TEXTURE_BINDING_2D:
  39546. case gl.TEXTURE_BINDING_CUBE_MAP:
  39547. var textureUnit = bindings[++i];
  39548. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  39549. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  39550. boundValues.push(null, null);
  39551. break;
  39552. }
  39553. if (!activeTexture) {
  39554. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  39555. }
  39556. gl.activeTexture(textureUnit);
  39557. boundValues.push(gl.getParameter(binding), null);
  39558. break;
  39559. case gl.ACTIVE_TEXTURE:
  39560. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  39561. boundValues.push(null);
  39562. break;
  39563. default:
  39564. boundValues.push(gl.getParameter(binding));
  39565. break;
  39566. }
  39567. }
  39568. callback(gl);
  39569. for (var i = 0; i < bindings.length; ++i) {
  39570. var binding = bindings[i];
  39571. var boundValue = boundValues[i];
  39572. switch (binding) {
  39573. case gl.ACTIVE_TEXTURE:
  39574. break;
  39575. case gl.ARRAY_BUFFER_BINDING:
  39576. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  39577. break;
  39578. case gl.COLOR_CLEAR_VALUE:
  39579. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39580. break;
  39581. case gl.COLOR_WRITEMASK:
  39582. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39583. break;
  39584. case gl.CURRENT_PROGRAM:
  39585. gl.useProgram(boundValue);
  39586. break;
  39587. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  39588. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  39589. break;
  39590. case gl.FRAMEBUFFER_BINDING:
  39591. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  39592. break;
  39593. case gl.RENDERBUFFER_BINDING:
  39594. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  39595. break;
  39596. case gl.TEXTURE_BINDING_2D:
  39597. var textureUnit = bindings[++i];
  39598. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  39599. break;
  39600. gl.activeTexture(textureUnit);
  39601. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  39602. break;
  39603. case gl.TEXTURE_BINDING_CUBE_MAP:
  39604. var textureUnit = bindings[++i];
  39605. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  39606. break;
  39607. gl.activeTexture(textureUnit);
  39608. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  39609. break;
  39610. case gl.VIEWPORT:
  39611. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39612. break;
  39613. case gl.BLEND:
  39614. case gl.CULL_FACE:
  39615. case gl.DEPTH_TEST:
  39616. case gl.SCISSOR_TEST:
  39617. case gl.STENCIL_TEST:
  39618. if (boundValue) {
  39619. gl.enable(binding);
  39620. } else {
  39621. gl.disable(binding);
  39622. }
  39623. break;
  39624. default:
  39625. console.log("No GL restore behavior for 0x" + binding.toString(16));
  39626. break;
  39627. }
  39628. if (activeTexture) {
  39629. gl.activeTexture(activeTexture);
  39630. }
  39631. }
  39632. }
  39633. var glPreserveState = WGLUPreserveGLState;
  39634. 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');
  39635. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  39636. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  39637. this.gl = gl;
  39638. this.cardboardUI = cardboardUI;
  39639. this.bufferScale = bufferScale;
  39640. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  39641. this.ctxAttribs = gl.getContextAttributes();
  39642. this.meshWidth = 20;
  39643. this.meshHeight = 20;
  39644. this.bufferWidth = gl.drawingBufferWidth;
  39645. this.bufferHeight = gl.drawingBufferHeight;
  39646. this.realBindFramebuffer = gl.bindFramebuffer;
  39647. this.realEnable = gl.enable;
  39648. this.realDisable = gl.disable;
  39649. this.realColorMask = gl.colorMask;
  39650. this.realClearColor = gl.clearColor;
  39651. this.realViewport = gl.viewport;
  39652. if (!isIOS()) {
  39653. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  39654. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  39655. }
  39656. this.isPatched = false;
  39657. this.lastBoundFramebuffer = null;
  39658. this.cullFace = false;
  39659. this.depthTest = false;
  39660. this.blend = false;
  39661. this.scissorTest = false;
  39662. this.stencilTest = false;
  39663. this.viewport = [0, 0, 0, 0];
  39664. this.colorMask = [true, true, true, true];
  39665. this.clearColor = [0, 0, 0, 0];
  39666. this.attribs = {
  39667. position: 0,
  39668. texCoord: 1
  39669. };
  39670. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  39671. this.uniforms = getProgramUniforms(gl, this.program);
  39672. this.viewportOffsetScale = new Float32Array(8);
  39673. this.setTextureBounds();
  39674. this.vertexBuffer = gl.createBuffer();
  39675. this.indexBuffer = gl.createBuffer();
  39676. this.indexCount = 0;
  39677. this.renderTarget = gl.createTexture();
  39678. this.framebuffer = gl.createFramebuffer();
  39679. this.depthStencilBuffer = null;
  39680. this.depthBuffer = null;
  39681. this.stencilBuffer = null;
  39682. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  39683. this.depthStencilBuffer = gl.createRenderbuffer();
  39684. } else if (this.ctxAttribs.depth) {
  39685. this.depthBuffer = gl.createRenderbuffer();
  39686. } else if (this.ctxAttribs.stencil) {
  39687. this.stencilBuffer = gl.createRenderbuffer();
  39688. }
  39689. this.patch();
  39690. this.onResize();
  39691. }
  39692. CardboardDistorter.prototype.destroy = function () {
  39693. var gl = this.gl;
  39694. this.unpatch();
  39695. gl.deleteProgram(this.program);
  39696. gl.deleteBuffer(this.vertexBuffer);
  39697. gl.deleteBuffer(this.indexBuffer);
  39698. gl.deleteTexture(this.renderTarget);
  39699. gl.deleteFramebuffer(this.framebuffer);
  39700. if (this.depthStencilBuffer) {
  39701. gl.deleteRenderbuffer(this.depthStencilBuffer);
  39702. }
  39703. if (this.depthBuffer) {
  39704. gl.deleteRenderbuffer(this.depthBuffer);
  39705. }
  39706. if (this.stencilBuffer) {
  39707. gl.deleteRenderbuffer(this.stencilBuffer);
  39708. }
  39709. if (this.cardboardUI) {
  39710. this.cardboardUI.destroy();
  39711. }
  39712. };
  39713. CardboardDistorter.prototype.onResize = function () {
  39714. var gl = this.gl;
  39715. var self = this;
  39716. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  39717. glPreserveState(gl, glState, function (gl) {
  39718. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  39719. if (self.scissorTest) {
  39720. self.realDisable.call(gl, gl.SCISSOR_TEST);
  39721. }
  39722. self.realColorMask.call(gl, true, true, true, true);
  39723. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  39724. self.realClearColor.call(gl, 0, 0, 0, 1);
  39725. gl.clear(gl.COLOR_BUFFER_BIT);
  39726. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  39727. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  39728. 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);
  39729. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  39730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  39731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  39732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  39733. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  39734. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  39735. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  39736. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  39737. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  39738. } else if (self.ctxAttribs.depth) {
  39739. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  39740. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  39741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  39742. } else if (self.ctxAttribs.stencil) {
  39743. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  39744. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  39745. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  39746. }
  39747. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  39748. console.error('Framebuffer incomplete!');
  39749. }
  39750. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  39751. if (self.scissorTest) {
  39752. self.realEnable.call(gl, gl.SCISSOR_TEST);
  39753. }
  39754. self.realColorMask.apply(gl, self.colorMask);
  39755. self.realViewport.apply(gl, self.viewport);
  39756. self.realClearColor.apply(gl, self.clearColor);
  39757. });
  39758. if (this.cardboardUI) {
  39759. this.cardboardUI.onResize();
  39760. }
  39761. };
  39762. CardboardDistorter.prototype.patch = function () {
  39763. if (this.isPatched) {
  39764. return;
  39765. }
  39766. var self = this;
  39767. var canvas = this.gl.canvas;
  39768. var gl = this.gl;
  39769. if (!isIOS()) {
  39770. canvas.width = getScreenWidth() * this.bufferScale;
  39771. canvas.height = getScreenHeight() * this.bufferScale;
  39772. Object.defineProperty(canvas, 'width', {
  39773. configurable: true,
  39774. enumerable: true,
  39775. get: function get() {
  39776. return self.bufferWidth;
  39777. },
  39778. set: function set(value) {
  39779. self.bufferWidth = value;
  39780. self.realCanvasWidth.set.call(canvas, value);
  39781. self.onResize();
  39782. }
  39783. });
  39784. Object.defineProperty(canvas, 'height', {
  39785. configurable: true,
  39786. enumerable: true,
  39787. get: function get() {
  39788. return self.bufferHeight;
  39789. },
  39790. set: function set(value) {
  39791. self.bufferHeight = value;
  39792. self.realCanvasHeight.set.call(canvas, value);
  39793. self.onResize();
  39794. }
  39795. });
  39796. }
  39797. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  39798. if (this.lastBoundFramebuffer == null) {
  39799. this.lastBoundFramebuffer = this.framebuffer;
  39800. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  39801. }
  39802. this.gl.bindFramebuffer = function (target, framebuffer) {
  39803. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  39804. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  39805. };
  39806. this.cullFace = gl.getParameter(gl.CULL_FACE);
  39807. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  39808. this.blend = gl.getParameter(gl.BLEND);
  39809. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  39810. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  39811. gl.enable = function (pname) {
  39812. switch (pname) {
  39813. case gl.CULL_FACE:
  39814. self.cullFace = true;break;
  39815. case gl.DEPTH_TEST:
  39816. self.depthTest = true;break;
  39817. case gl.BLEND:
  39818. self.blend = true;break;
  39819. case gl.SCISSOR_TEST:
  39820. self.scissorTest = true;break;
  39821. case gl.STENCIL_TEST:
  39822. self.stencilTest = true;break;
  39823. }
  39824. self.realEnable.call(gl, pname);
  39825. };
  39826. gl.disable = function (pname) {
  39827. switch (pname) {
  39828. case gl.CULL_FACE:
  39829. self.cullFace = false;break;
  39830. case gl.DEPTH_TEST:
  39831. self.depthTest = false;break;
  39832. case gl.BLEND:
  39833. self.blend = false;break;
  39834. case gl.SCISSOR_TEST:
  39835. self.scissorTest = false;break;
  39836. case gl.STENCIL_TEST:
  39837. self.stencilTest = false;break;
  39838. }
  39839. self.realDisable.call(gl, pname);
  39840. };
  39841. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  39842. gl.colorMask = function (r, g, b, a) {
  39843. self.colorMask[0] = r;
  39844. self.colorMask[1] = g;
  39845. self.colorMask[2] = b;
  39846. self.colorMask[3] = a;
  39847. self.realColorMask.call(gl, r, g, b, a);
  39848. };
  39849. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  39850. gl.clearColor = function (r, g, b, a) {
  39851. self.clearColor[0] = r;
  39852. self.clearColor[1] = g;
  39853. self.clearColor[2] = b;
  39854. self.clearColor[3] = a;
  39855. self.realClearColor.call(gl, r, g, b, a);
  39856. };
  39857. this.viewport = gl.getParameter(gl.VIEWPORT);
  39858. gl.viewport = function (x, y, w, h) {
  39859. self.viewport[0] = x;
  39860. self.viewport[1] = y;
  39861. self.viewport[2] = w;
  39862. self.viewport[3] = h;
  39863. self.realViewport.call(gl, x, y, w, h);
  39864. };
  39865. this.isPatched = true;
  39866. safariCssSizeWorkaround(canvas);
  39867. };
  39868. CardboardDistorter.prototype.unpatch = function () {
  39869. if (!this.isPatched) {
  39870. return;
  39871. }
  39872. var gl = this.gl;
  39873. var canvas = this.gl.canvas;
  39874. if (!isIOS()) {
  39875. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  39876. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  39877. }
  39878. canvas.width = this.bufferWidth;
  39879. canvas.height = this.bufferHeight;
  39880. gl.bindFramebuffer = this.realBindFramebuffer;
  39881. gl.enable = this.realEnable;
  39882. gl.disable = this.realDisable;
  39883. gl.colorMask = this.realColorMask;
  39884. gl.clearColor = this.realClearColor;
  39885. gl.viewport = this.realViewport;
  39886. if (this.lastBoundFramebuffer == this.framebuffer) {
  39887. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  39888. }
  39889. this.isPatched = false;
  39890. setTimeout(function () {
  39891. safariCssSizeWorkaround(canvas);
  39892. }, 1);
  39893. };
  39894. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  39895. if (!leftBounds) {
  39896. leftBounds = [0, 0, 0.5, 1];
  39897. }
  39898. if (!rightBounds) {
  39899. rightBounds = [0.5, 0, 0.5, 1];
  39900. }
  39901. this.viewportOffsetScale[0] = leftBounds[0];
  39902. this.viewportOffsetScale[1] = leftBounds[1];
  39903. this.viewportOffsetScale[2] = leftBounds[2];
  39904. this.viewportOffsetScale[3] = leftBounds[3];
  39905. this.viewportOffsetScale[4] = rightBounds[0];
  39906. this.viewportOffsetScale[5] = rightBounds[1];
  39907. this.viewportOffsetScale[6] = rightBounds[2];
  39908. this.viewportOffsetScale[7] = rightBounds[3];
  39909. };
  39910. CardboardDistorter.prototype.submitFrame = function () {
  39911. var gl = this.gl;
  39912. var self = this;
  39913. var glState = [];
  39914. if (!this.dirtySubmitFrameBindings) {
  39915. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  39916. }
  39917. glPreserveState(gl, glState, function (gl) {
  39918. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  39919. if (self.cullFace) {
  39920. self.realDisable.call(gl, gl.CULL_FACE);
  39921. }
  39922. if (self.depthTest) {
  39923. self.realDisable.call(gl, gl.DEPTH_TEST);
  39924. }
  39925. if (self.blend) {
  39926. self.realDisable.call(gl, gl.BLEND);
  39927. }
  39928. if (self.scissorTest) {
  39929. self.realDisable.call(gl, gl.SCISSOR_TEST);
  39930. }
  39931. if (self.stencilTest) {
  39932. self.realDisable.call(gl, gl.STENCIL_TEST);
  39933. }
  39934. self.realColorMask.call(gl, true, true, true, true);
  39935. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  39936. if (self.ctxAttribs.alpha || isIOS()) {
  39937. self.realClearColor.call(gl, 0, 0, 0, 1);
  39938. gl.clear(gl.COLOR_BUFFER_BIT);
  39939. }
  39940. gl.useProgram(self.program);
  39941. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  39942. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  39943. gl.enableVertexAttribArray(self.attribs.position);
  39944. gl.enableVertexAttribArray(self.attribs.texCoord);
  39945. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  39946. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  39947. gl.activeTexture(gl.TEXTURE0);
  39948. gl.uniform1i(self.uniforms.diffuse, 0);
  39949. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  39950. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  39951. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  39952. if (self.cardboardUI) {
  39953. self.cardboardUI.renderNoState();
  39954. }
  39955. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  39956. if (!self.ctxAttribs.preserveDrawingBuffer) {
  39957. self.realClearColor.call(gl, 0, 0, 0, 0);
  39958. gl.clear(gl.COLOR_BUFFER_BIT);
  39959. }
  39960. if (!self.dirtySubmitFrameBindings) {
  39961. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  39962. }
  39963. if (self.cullFace) {
  39964. self.realEnable.call(gl, gl.CULL_FACE);
  39965. }
  39966. if (self.depthTest) {
  39967. self.realEnable.call(gl, gl.DEPTH_TEST);
  39968. }
  39969. if (self.blend) {
  39970. self.realEnable.call(gl, gl.BLEND);
  39971. }
  39972. if (self.scissorTest) {
  39973. self.realEnable.call(gl, gl.SCISSOR_TEST);
  39974. }
  39975. if (self.stencilTest) {
  39976. self.realEnable.call(gl, gl.STENCIL_TEST);
  39977. }
  39978. self.realColorMask.apply(gl, self.colorMask);
  39979. self.realViewport.apply(gl, self.viewport);
  39980. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  39981. self.realClearColor.apply(gl, self.clearColor);
  39982. }
  39983. });
  39984. if (isIOS()) {
  39985. var canvas = gl.canvas;
  39986. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  39987. self.bufferWidth = canvas.width;
  39988. self.bufferHeight = canvas.height;
  39989. self.onResize();
  39990. }
  39991. }
  39992. };
  39993. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  39994. var gl = this.gl;
  39995. var self = this;
  39996. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  39997. glPreserveState(gl, glState, function (gl) {
  39998. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  39999. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  40000. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  40001. if (!self.indexCount) {
  40002. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  40003. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  40004. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  40005. self.indexCount = indices.length;
  40006. }
  40007. });
  40008. };
  40009. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  40010. var vertices = new Float32Array(2 * width * height * 5);
  40011. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  40012. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  40013. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  40014. var vidx = 0;
  40015. for (var e = 0; e < 2; e++) {
  40016. for (var j = 0; j < height; j++) {
  40017. for (var i = 0; i < width; i++, vidx++) {
  40018. var u = i / (width - 1);
  40019. var v = j / (height - 1);
  40020. var s = u;
  40021. var t = v;
  40022. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  40023. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  40024. var d = Math.sqrt(x * x + y * y);
  40025. var r = deviceInfo.distortion.distortInverse(d);
  40026. var p = x * r / d;
  40027. var q = y * r / d;
  40028. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  40029. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  40030. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  40031. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  40032. vertices[vidx * 5 + 0] = u;
  40033. vertices[vidx * 5 + 1] = v;
  40034. vertices[vidx * 5 + 2] = s;
  40035. vertices[vidx * 5 + 3] = t;
  40036. vertices[vidx * 5 + 4] = e;
  40037. }
  40038. }
  40039. var w = lensFrustum[2] - lensFrustum[0];
  40040. lensFrustum[0] = -(w + lensFrustum[0]);
  40041. lensFrustum[2] = w - lensFrustum[2];
  40042. w = noLensFrustum[2] - noLensFrustum[0];
  40043. noLensFrustum[0] = -(w + noLensFrustum[0]);
  40044. noLensFrustum[2] = w - noLensFrustum[2];
  40045. viewport.x = 1 - (viewport.x + viewport.width);
  40046. }
  40047. return vertices;
  40048. };
  40049. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  40050. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  40051. var halfwidth = width / 2;
  40052. var halfheight = height / 2;
  40053. var vidx = 0;
  40054. var iidx = 0;
  40055. for (var e = 0; e < 2; e++) {
  40056. for (var j = 0; j < height; j++) {
  40057. for (var i = 0; i < width; i++, vidx++) {
  40058. if (i == 0 || j == 0) continue;
  40059. if (i <= halfwidth == j <= halfheight) {
  40060. indices[iidx++] = vidx;
  40061. indices[iidx++] = vidx - width - 1;
  40062. indices[iidx++] = vidx - width;
  40063. indices[iidx++] = vidx - width - 1;
  40064. indices[iidx++] = vidx;
  40065. indices[iidx++] = vidx - 1;
  40066. } else {
  40067. indices[iidx++] = vidx - 1;
  40068. indices[iidx++] = vidx - width;
  40069. indices[iidx++] = vidx;
  40070. indices[iidx++] = vidx - width;
  40071. indices[iidx++] = vidx - 1;
  40072. indices[iidx++] = vidx - width - 1;
  40073. }
  40074. }
  40075. }
  40076. }
  40077. return indices;
  40078. };
  40079. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  40080. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  40081. if (descriptor.get === undefined || descriptor.set === undefined) {
  40082. descriptor.configurable = true;
  40083. descriptor.enumerable = true;
  40084. descriptor.get = function () {
  40085. return this.getAttribute(attrName);
  40086. };
  40087. descriptor.set = function (val) {
  40088. this.setAttribute(attrName, val);
  40089. };
  40090. }
  40091. return descriptor;
  40092. };
  40093. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  40094. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  40095. var DEG2RAD = Math.PI / 180.0;
  40096. var kAnglePerGearSection = 60;
  40097. var kOuterRimEndAngle = 12;
  40098. var kInnerRimBeginAngle = 20;
  40099. var kOuterRadius = 1;
  40100. var kMiddleRadius = 0.75;
  40101. var kInnerRadius = 0.3125;
  40102. var kCenterLineThicknessDp = 4;
  40103. var kButtonWidthDp = 28;
  40104. var kTouchSlopFactor = 1.5;
  40105. function CardboardUI(gl) {
  40106. this.gl = gl;
  40107. this.attribs = {
  40108. position: 0
  40109. };
  40110. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  40111. this.uniforms = getProgramUniforms(gl, this.program);
  40112. this.vertexBuffer = gl.createBuffer();
  40113. this.gearOffset = 0;
  40114. this.gearVertexCount = 0;
  40115. this.arrowOffset = 0;
  40116. this.arrowVertexCount = 0;
  40117. this.projMat = new Float32Array(16);
  40118. this.listener = null;
  40119. this.onResize();
  40120. }
  40121. CardboardUI.prototype.destroy = function () {
  40122. var gl = this.gl;
  40123. if (this.listener) {
  40124. gl.canvas.removeEventListener('click', this.listener, false);
  40125. }
  40126. gl.deleteProgram(this.program);
  40127. gl.deleteBuffer(this.vertexBuffer);
  40128. };
  40129. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  40130. var canvas = this.gl.canvas;
  40131. this.listener = function (event) {
  40132. var midline = canvas.clientWidth / 2;
  40133. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  40134. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  40135. optionsCallback(event);
  40136. }
  40137. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  40138. backCallback(event);
  40139. }
  40140. };
  40141. canvas.addEventListener('click', this.listener, false);
  40142. };
  40143. CardboardUI.prototype.onResize = function () {
  40144. var gl = this.gl;
  40145. var self = this;
  40146. var glState = [gl.ARRAY_BUFFER_BINDING];
  40147. glPreserveState(gl, glState, function (gl) {
  40148. var vertices = [];
  40149. var midline = gl.drawingBufferWidth / 2;
  40150. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  40151. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  40152. var dps = scalingRatio * window.devicePixelRatio;
  40153. var lineWidth = kCenterLineThicknessDp * dps / 2;
  40154. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  40155. var buttonScale = kButtonWidthDp * dps / 2;
  40156. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  40157. vertices.push(midline - lineWidth, buttonSize);
  40158. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  40159. vertices.push(midline + lineWidth, buttonSize);
  40160. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  40161. self.gearOffset = vertices.length / 2;
  40162. function addGearSegment(theta, r) {
  40163. var angle = (90 - theta) * DEG2RAD;
  40164. var x = Math.cos(angle);
  40165. var y = Math.sin(angle);
  40166. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  40167. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  40168. }
  40169. for (var i = 0; i <= 6; i++) {
  40170. var segmentTheta = i * kAnglePerGearSection;
  40171. addGearSegment(segmentTheta, kOuterRadius);
  40172. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  40173. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  40174. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  40175. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  40176. }
  40177. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  40178. self.arrowOffset = vertices.length / 2;
  40179. function addArrowVertex(x, y) {
  40180. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  40181. }
  40182. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  40183. addArrowVertex(0, buttonScale);
  40184. addArrowVertex(buttonScale, 0);
  40185. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  40186. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  40187. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  40188. addArrowVertex(0, buttonScale);
  40189. addArrowVertex(buttonScale, buttonScale * 2);
  40190. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  40191. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  40192. addArrowVertex(0, buttonScale);
  40193. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  40194. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  40195. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  40196. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  40197. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  40198. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  40199. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  40200. });
  40201. };
  40202. CardboardUI.prototype.render = function () {
  40203. var gl = this.gl;
  40204. var self = this;
  40205. 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];
  40206. glPreserveState(gl, glState, function (gl) {
  40207. gl.disable(gl.CULL_FACE);
  40208. gl.disable(gl.DEPTH_TEST);
  40209. gl.disable(gl.BLEND);
  40210. gl.disable(gl.SCISSOR_TEST);
  40211. gl.disable(gl.STENCIL_TEST);
  40212. gl.colorMask(true, true, true, true);
  40213. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  40214. self.renderNoState();
  40215. });
  40216. };
  40217. CardboardUI.prototype.renderNoState = function () {
  40218. var gl = this.gl;
  40219. gl.useProgram(this.program);
  40220. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  40221. gl.enableVertexAttribArray(this.attribs.position);
  40222. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  40223. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  40224. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  40225. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  40226. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  40227. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  40228. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  40229. };
  40230. function Distortion(coefficients) {
  40231. this.coefficients = coefficients;
  40232. }
  40233. Distortion.prototype.distortInverse = function (radius) {
  40234. var r0 = 0;
  40235. var r1 = 1;
  40236. var dr0 = radius - this.distort(r0);
  40237. while (Math.abs(r1 - r0) > 0.0001 ) {
  40238. var dr1 = radius - this.distort(r1);
  40239. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  40240. r0 = r1;
  40241. r1 = r2;
  40242. dr0 = dr1;
  40243. }
  40244. return r1;
  40245. };
  40246. Distortion.prototype.distort = function (radius) {
  40247. var r2 = radius * radius;
  40248. var ret = 0;
  40249. for (var i = 0; i < this.coefficients.length; i++) {
  40250. ret = r2 * (ret + this.coefficients[i]);
  40251. }
  40252. return (ret + 1) * radius;
  40253. };
  40254. var degToRad = Math.PI / 180;
  40255. var radToDeg = 180 / Math.PI;
  40256. var Vector3 = function Vector3(x, y, z) {
  40257. this.x = x || 0;
  40258. this.y = y || 0;
  40259. this.z = z || 0;
  40260. };
  40261. Vector3.prototype = {
  40262. constructor: Vector3,
  40263. set: function set(x, y, z) {
  40264. this.x = x;
  40265. this.y = y;
  40266. this.z = z;
  40267. return this;
  40268. },
  40269. copy: function copy(v) {
  40270. this.x = v.x;
  40271. this.y = v.y;
  40272. this.z = v.z;
  40273. return this;
  40274. },
  40275. length: function length() {
  40276. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  40277. },
  40278. normalize: function normalize() {
  40279. var scalar = this.length();
  40280. if (scalar !== 0) {
  40281. var invScalar = 1 / scalar;
  40282. this.multiplyScalar(invScalar);
  40283. } else {
  40284. this.x = 0;
  40285. this.y = 0;
  40286. this.z = 0;
  40287. }
  40288. return this;
  40289. },
  40290. multiplyScalar: function multiplyScalar(scalar) {
  40291. this.x *= scalar;
  40292. this.y *= scalar;
  40293. this.z *= scalar;
  40294. },
  40295. applyQuaternion: function applyQuaternion(q) {
  40296. var x = this.x;
  40297. var y = this.y;
  40298. var z = this.z;
  40299. var qx = q.x;
  40300. var qy = q.y;
  40301. var qz = q.z;
  40302. var qw = q.w;
  40303. var ix = qw * x + qy * z - qz * y;
  40304. var iy = qw * y + qz * x - qx * z;
  40305. var iz = qw * z + qx * y - qy * x;
  40306. var iw = -qx * x - qy * y - qz * z;
  40307. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  40308. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  40309. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  40310. return this;
  40311. },
  40312. dot: function dot(v) {
  40313. return this.x * v.x + this.y * v.y + this.z * v.z;
  40314. },
  40315. crossVectors: function crossVectors(a, b) {
  40316. var ax = a.x,
  40317. ay = a.y,
  40318. az = a.z;
  40319. var bx = b.x,
  40320. by = b.y,
  40321. bz = b.z;
  40322. this.x = ay * bz - az * by;
  40323. this.y = az * bx - ax * bz;
  40324. this.z = ax * by - ay * bx;
  40325. return this;
  40326. }
  40327. };
  40328. var Quaternion = function Quaternion(x, y, z, w) {
  40329. this.x = x || 0;
  40330. this.y = y || 0;
  40331. this.z = z || 0;
  40332. this.w = w !== undefined ? w : 1;
  40333. };
  40334. Quaternion.prototype = {
  40335. constructor: Quaternion,
  40336. set: function set(x, y, z, w) {
  40337. this.x = x;
  40338. this.y = y;
  40339. this.z = z;
  40340. this.w = w;
  40341. return this;
  40342. },
  40343. copy: function copy(quaternion) {
  40344. this.x = quaternion.x;
  40345. this.y = quaternion.y;
  40346. this.z = quaternion.z;
  40347. this.w = quaternion.w;
  40348. return this;
  40349. },
  40350. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  40351. var c1 = Math.cos(x / 2);
  40352. var c2 = Math.cos(y / 2);
  40353. var c3 = Math.cos(z / 2);
  40354. var s1 = Math.sin(x / 2);
  40355. var s2 = Math.sin(y / 2);
  40356. var s3 = Math.sin(z / 2);
  40357. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40358. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40359. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  40360. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  40361. return this;
  40362. },
  40363. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  40364. var c1 = Math.cos(x / 2);
  40365. var c2 = Math.cos(y / 2);
  40366. var c3 = Math.cos(z / 2);
  40367. var s1 = Math.sin(x / 2);
  40368. var s2 = Math.sin(y / 2);
  40369. var s3 = Math.sin(z / 2);
  40370. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40371. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40372. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  40373. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  40374. return this;
  40375. },
  40376. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  40377. var halfAngle = angle / 2,
  40378. s = Math.sin(halfAngle);
  40379. this.x = axis.x * s;
  40380. this.y = axis.y * s;
  40381. this.z = axis.z * s;
  40382. this.w = Math.cos(halfAngle);
  40383. return this;
  40384. },
  40385. multiply: function multiply(q) {
  40386. return this.multiplyQuaternions(this, q);
  40387. },
  40388. multiplyQuaternions: function multiplyQuaternions(a, b) {
  40389. var qax = a.x,
  40390. qay = a.y,
  40391. qaz = a.z,
  40392. qaw = a.w;
  40393. var qbx = b.x,
  40394. qby = b.y,
  40395. qbz = b.z,
  40396. qbw = b.w;
  40397. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  40398. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  40399. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  40400. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  40401. return this;
  40402. },
  40403. inverse: function inverse() {
  40404. this.x *= -1;
  40405. this.y *= -1;
  40406. this.z *= -1;
  40407. this.normalize();
  40408. return this;
  40409. },
  40410. normalize: function normalize() {
  40411. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  40412. if (l === 0) {
  40413. this.x = 0;
  40414. this.y = 0;
  40415. this.z = 0;
  40416. this.w = 1;
  40417. } else {
  40418. l = 1 / l;
  40419. this.x = this.x * l;
  40420. this.y = this.y * l;
  40421. this.z = this.z * l;
  40422. this.w = this.w * l;
  40423. }
  40424. return this;
  40425. },
  40426. slerp: function slerp(qb, t) {
  40427. if (t === 0) return this;
  40428. if (t === 1) return this.copy(qb);
  40429. var x = this.x,
  40430. y = this.y,
  40431. z = this.z,
  40432. w = this.w;
  40433. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  40434. if (cosHalfTheta < 0) {
  40435. this.w = -qb.w;
  40436. this.x = -qb.x;
  40437. this.y = -qb.y;
  40438. this.z = -qb.z;
  40439. cosHalfTheta = -cosHalfTheta;
  40440. } else {
  40441. this.copy(qb);
  40442. }
  40443. if (cosHalfTheta >= 1.0) {
  40444. this.w = w;
  40445. this.x = x;
  40446. this.y = y;
  40447. this.z = z;
  40448. return this;
  40449. }
  40450. var halfTheta = Math.acos(cosHalfTheta);
  40451. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  40452. if (Math.abs(sinHalfTheta) < 0.001) {
  40453. this.w = 0.5 * (w + this.w);
  40454. this.x = 0.5 * (x + this.x);
  40455. this.y = 0.5 * (y + this.y);
  40456. this.z = 0.5 * (z + this.z);
  40457. return this;
  40458. }
  40459. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  40460. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  40461. this.w = w * ratioA + this.w * ratioB;
  40462. this.x = x * ratioA + this.x * ratioB;
  40463. this.y = y * ratioA + this.y * ratioB;
  40464. this.z = z * ratioA + this.z * ratioB;
  40465. return this;
  40466. },
  40467. setFromUnitVectors: function () {
  40468. var v1, r;
  40469. var EPS = 0.000001;
  40470. return function (vFrom, vTo) {
  40471. if (v1 === undefined) v1 = new Vector3();
  40472. r = vFrom.dot(vTo) + 1;
  40473. if (r < EPS) {
  40474. r = 0;
  40475. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  40476. v1.set(-vFrom.y, vFrom.x, 0);
  40477. } else {
  40478. v1.set(0, -vFrom.z, vFrom.y);
  40479. }
  40480. } else {
  40481. v1.crossVectors(vFrom, vTo);
  40482. }
  40483. this.x = v1.x;
  40484. this.y = v1.y;
  40485. this.z = v1.z;
  40486. this.w = r;
  40487. this.normalize();
  40488. return this;
  40489. };
  40490. }()
  40491. };
  40492. function Device(params) {
  40493. this.width = params.width || getScreenWidth();
  40494. this.height = params.height || getScreenHeight();
  40495. this.widthMeters = params.widthMeters;
  40496. this.heightMeters = params.heightMeters;
  40497. this.bevelMeters = params.bevelMeters;
  40498. }
  40499. var DEFAULT_ANDROID = new Device({
  40500. widthMeters: 0.110,
  40501. heightMeters: 0.062,
  40502. bevelMeters: 0.004
  40503. });
  40504. var DEFAULT_IOS = new Device({
  40505. widthMeters: 0.1038,
  40506. heightMeters: 0.0584,
  40507. bevelMeters: 0.004
  40508. });
  40509. var Viewers = {
  40510. CardboardV1: new CardboardViewer({
  40511. id: 'CardboardV1',
  40512. label: 'Cardboard I/O 2014',
  40513. fov: 40,
  40514. interLensDistance: 0.060,
  40515. baselineLensDistance: 0.035,
  40516. screenLensDistance: 0.042,
  40517. distortionCoefficients: [0.441, 0.156],
  40518. 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]
  40519. }),
  40520. CardboardV2: new CardboardViewer({
  40521. id: 'CardboardV2',
  40522. label: 'Cardboard I/O 2015',
  40523. fov: 60,
  40524. interLensDistance: 0.064,
  40525. baselineLensDistance: 0.035,
  40526. screenLensDistance: 0.039,
  40527. distortionCoefficients: [0.34, 0.55],
  40528. 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]
  40529. })
  40530. };
  40531. function DeviceInfo(deviceParams, additionalViewers) {
  40532. this.viewer = Viewers.CardboardV2;
  40533. this.updateDeviceParams(deviceParams);
  40534. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  40535. for (var i = 0; i < additionalViewers.length; i++) {
  40536. var viewer = additionalViewers[i];
  40537. Viewers[viewer.id] = new CardboardViewer(viewer);
  40538. }
  40539. }
  40540. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  40541. this.device = this.determineDevice_(deviceParams) || this.device;
  40542. };
  40543. DeviceInfo.prototype.getDevice = function () {
  40544. return this.device;
  40545. };
  40546. DeviceInfo.prototype.setViewer = function (viewer) {
  40547. this.viewer = viewer;
  40548. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  40549. };
  40550. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  40551. if (!deviceParams) {
  40552. if (isIOS()) {
  40553. console.warn('Using fallback iOS device measurements.');
  40554. return DEFAULT_IOS;
  40555. } else {
  40556. console.warn('Using fallback Android device measurements.');
  40557. return DEFAULT_ANDROID;
  40558. }
  40559. }
  40560. var METERS_PER_INCH = 0.0254;
  40561. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  40562. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  40563. var width = getScreenWidth();
  40564. var height = getScreenHeight();
  40565. return new Device({
  40566. widthMeters: metersPerPixelX * width,
  40567. heightMeters: metersPerPixelY * height,
  40568. bevelMeters: deviceParams.bevelMm * 0.001
  40569. });
  40570. };
  40571. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  40572. var viewer = this.viewer;
  40573. var device = this.device;
  40574. var distortion = this.distortion;
  40575. var eyeToScreenDistance = viewer.screenLensDistance;
  40576. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  40577. var innerDist = viewer.interLensDistance / 2;
  40578. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  40579. var topDist = device.heightMeters - bottomDist;
  40580. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  40581. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  40582. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  40583. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  40584. return {
  40585. leftDegrees: Math.min(outerAngle, viewer.fov),
  40586. rightDegrees: Math.min(innerAngle, viewer.fov),
  40587. downDegrees: Math.min(bottomAngle, viewer.fov),
  40588. upDegrees: Math.min(topAngle, viewer.fov)
  40589. };
  40590. };
  40591. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  40592. var viewer = this.viewer;
  40593. var device = this.device;
  40594. var distortion = this.distortion;
  40595. var fovLeft = Math.tan(-degToRad * viewer.fov);
  40596. var fovTop = Math.tan(degToRad * viewer.fov);
  40597. var fovRight = Math.tan(degToRad * viewer.fov);
  40598. var fovBottom = Math.tan(-degToRad * viewer.fov);
  40599. var halfWidth = device.widthMeters / 4;
  40600. var halfHeight = device.heightMeters / 2;
  40601. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  40602. var centerX = viewer.interLensDistance / 2 - halfWidth;
  40603. var centerY = -verticalLensOffset;
  40604. var centerZ = viewer.screenLensDistance;
  40605. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  40606. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  40607. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  40608. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  40609. var result = new Float32Array(4);
  40610. result[0] = Math.max(fovLeft, screenLeft);
  40611. result[1] = Math.min(fovTop, screenTop);
  40612. result[2] = Math.min(fovRight, screenRight);
  40613. result[3] = Math.max(fovBottom, screenBottom);
  40614. return result;
  40615. };
  40616. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  40617. var viewer = this.viewer;
  40618. var device = this.device;
  40619. var distortion = this.distortion;
  40620. var result = new Float32Array(4);
  40621. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  40622. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  40623. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  40624. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  40625. var halfWidth = device.widthMeters / 4;
  40626. var halfHeight = device.heightMeters / 2;
  40627. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  40628. var centerX = viewer.interLensDistance / 2 - halfWidth;
  40629. var centerY = -verticalLensOffset;
  40630. var centerZ = viewer.screenLensDistance;
  40631. var screenLeft = (centerX - halfWidth) / centerZ;
  40632. var screenTop = (centerY + halfHeight) / centerZ;
  40633. var screenRight = (centerX + halfWidth) / centerZ;
  40634. var screenBottom = (centerY - halfHeight) / centerZ;
  40635. result[0] = Math.max(fovLeft, screenLeft);
  40636. result[1] = Math.min(fovTop, screenTop);
  40637. result[2] = Math.min(fovRight, screenRight);
  40638. result[3] = Math.max(fovBottom, screenBottom);
  40639. return result;
  40640. };
  40641. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  40642. var viewer = this.viewer;
  40643. var device = this.device;
  40644. var dist = viewer.screenLensDistance;
  40645. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  40646. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  40647. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  40648. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  40649. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  40650. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  40651. return {
  40652. x: left,
  40653. y: bottom,
  40654. width: right - left,
  40655. height: top - bottom
  40656. };
  40657. };
  40658. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  40659. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  40660. };
  40661. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  40662. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  40663. return {
  40664. leftDegrees: fov.rightDegrees,
  40665. rightDegrees: fov.leftDegrees,
  40666. upDegrees: fov.upDegrees,
  40667. downDegrees: fov.downDegrees
  40668. };
  40669. };
  40670. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  40671. var p = this.getUndistortedParams_();
  40672. return {
  40673. leftDegrees: radToDeg * Math.atan(p.outerDist),
  40674. rightDegrees: radToDeg * Math.atan(p.innerDist),
  40675. downDegrees: radToDeg * Math.atan(p.bottomDist),
  40676. upDegrees: radToDeg * Math.atan(p.topDist)
  40677. };
  40678. };
  40679. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  40680. var p = this.getUndistortedParams_();
  40681. var viewer = this.viewer;
  40682. var device = this.device;
  40683. var eyeToScreenDistance = viewer.screenLensDistance;
  40684. var screenWidth = device.widthMeters / eyeToScreenDistance;
  40685. var screenHeight = device.heightMeters / eyeToScreenDistance;
  40686. var xPxPerTanAngle = device.width / screenWidth;
  40687. var yPxPerTanAngle = device.height / screenHeight;
  40688. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  40689. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  40690. return {
  40691. x: x,
  40692. y: y,
  40693. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  40694. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  40695. };
  40696. };
  40697. DeviceInfo.prototype.getUndistortedParams_ = function () {
  40698. var viewer = this.viewer;
  40699. var device = this.device;
  40700. var distortion = this.distortion;
  40701. var eyeToScreenDistance = viewer.screenLensDistance;
  40702. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  40703. var screenWidth = device.widthMeters / eyeToScreenDistance;
  40704. var screenHeight = device.heightMeters / eyeToScreenDistance;
  40705. var eyePosX = screenWidth / 2 - halfLensDistance;
  40706. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  40707. var maxFov = viewer.fov;
  40708. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  40709. var outerDist = Math.min(eyePosX, viewerMax);
  40710. var innerDist = Math.min(halfLensDistance, viewerMax);
  40711. var bottomDist = Math.min(eyePosY, viewerMax);
  40712. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  40713. return {
  40714. outerDist: outerDist,
  40715. innerDist: innerDist,
  40716. topDist: topDist,
  40717. bottomDist: bottomDist,
  40718. eyePosX: eyePosX,
  40719. eyePosY: eyePosY
  40720. };
  40721. };
  40722. function CardboardViewer(params) {
  40723. this.id = params.id;
  40724. this.label = params.label;
  40725. this.fov = params.fov;
  40726. this.interLensDistance = params.interLensDistance;
  40727. this.baselineLensDistance = params.baselineLensDistance;
  40728. this.screenLensDistance = params.screenLensDistance;
  40729. this.distortionCoefficients = params.distortionCoefficients;
  40730. this.inverseCoefficients = params.inverseCoefficients;
  40731. }
  40732. DeviceInfo.Viewers = Viewers;
  40733. var format = 1;
  40734. var last_updated = "2018-12-10T17:01:42Z";
  40735. 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_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 E1005/*"},{"ua":"ONE E1005"}],"dpi":[442.4,441.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 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":"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":"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}];
  40736. var DPDB_CACHE = {
  40737. format: format,
  40738. last_updated: last_updated,
  40739. devices: devices
  40740. };
  40741. function Dpdb(url, onDeviceParamsUpdated) {
  40742. this.dpdb = DPDB_CACHE;
  40743. this.recalculateDeviceParams_();
  40744. if (url) {
  40745. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  40746. var xhr = new XMLHttpRequest();
  40747. var obj = this;
  40748. xhr.open('GET', url, true);
  40749. xhr.addEventListener('load', function () {
  40750. obj.loading = false;
  40751. if (xhr.status >= 200 && xhr.status <= 299) {
  40752. obj.dpdb = JSON.parse(xhr.response);
  40753. obj.recalculateDeviceParams_();
  40754. } else {
  40755. console.error('Error loading online DPDB!');
  40756. }
  40757. });
  40758. xhr.send();
  40759. }
  40760. }
  40761. Dpdb.prototype.getDeviceParams = function () {
  40762. return this.deviceParams;
  40763. };
  40764. Dpdb.prototype.recalculateDeviceParams_ = function () {
  40765. var newDeviceParams = this.calcDeviceParams_();
  40766. if (newDeviceParams) {
  40767. this.deviceParams = newDeviceParams;
  40768. if (this.onDeviceParamsUpdated) {
  40769. this.onDeviceParamsUpdated(this.deviceParams);
  40770. }
  40771. } else {
  40772. console.error('Failed to recalculate device parameters.');
  40773. }
  40774. };
  40775. Dpdb.prototype.calcDeviceParams_ = function () {
  40776. var db = this.dpdb;
  40777. if (!db) {
  40778. console.error('DPDB not available.');
  40779. return null;
  40780. }
  40781. if (db.format != 1) {
  40782. console.error('DPDB has unexpected format version.');
  40783. return null;
  40784. }
  40785. if (!db.devices || !db.devices.length) {
  40786. console.error('DPDB does not have a devices section.');
  40787. return null;
  40788. }
  40789. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  40790. var width = getScreenWidth();
  40791. var height = getScreenHeight();
  40792. if (!db.devices) {
  40793. console.error('DPDB has no devices section.');
  40794. return null;
  40795. }
  40796. for (var i = 0; i < db.devices.length; i++) {
  40797. var device = db.devices[i];
  40798. if (!device.rules) {
  40799. console.warn('Device[' + i + '] has no rules section.');
  40800. continue;
  40801. }
  40802. if (device.type != 'ios' && device.type != 'android') {
  40803. console.warn('Device[' + i + '] has invalid type.');
  40804. continue;
  40805. }
  40806. if (isIOS() != (device.type == 'ios')) continue;
  40807. var matched = false;
  40808. for (var j = 0; j < device.rules.length; j++) {
  40809. var rule = device.rules[j];
  40810. if (this.ruleMatches_(rule, userAgent, width, height)) {
  40811. matched = true;
  40812. break;
  40813. }
  40814. }
  40815. if (!matched) continue;
  40816. var xdpi = device.dpi[0] || device.dpi;
  40817. var ydpi = device.dpi[1] || device.dpi;
  40818. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  40819. }
  40820. console.warn('No DPDB device match.');
  40821. return null;
  40822. };
  40823. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  40824. if (!rule.ua && !rule.res) return false;
  40825. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  40826. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  40827. if (rule.res) {
  40828. if (!rule.res[0] || !rule.res[1]) return false;
  40829. var resX = rule.res[0];
  40830. var resY = rule.res[1];
  40831. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  40832. return false;
  40833. }
  40834. }
  40835. return true;
  40836. };
  40837. function DeviceParams(params) {
  40838. this.xdpi = params.xdpi;
  40839. this.ydpi = params.ydpi;
  40840. this.bevelMm = params.bevelMm;
  40841. }
  40842. function SensorSample(sample, timestampS) {
  40843. this.set(sample, timestampS);
  40844. }
  40845. SensorSample.prototype.set = function (sample, timestampS) {
  40846. this.sample = sample;
  40847. this.timestampS = timestampS;
  40848. };
  40849. SensorSample.prototype.copy = function (sensorSample) {
  40850. this.set(sensorSample.sample, sensorSample.timestampS);
  40851. };
  40852. function ComplementaryFilter(kFilter, isDebug) {
  40853. this.kFilter = kFilter;
  40854. this.isDebug = isDebug;
  40855. this.currentAccelMeasurement = new SensorSample();
  40856. this.currentGyroMeasurement = new SensorSample();
  40857. this.previousGyroMeasurement = new SensorSample();
  40858. if (isIOS()) {
  40859. this.filterQ = new Quaternion(-1, 0, 0, 1);
  40860. } else {
  40861. this.filterQ = new Quaternion(1, 0, 0, 1);
  40862. }
  40863. this.previousFilterQ = new Quaternion();
  40864. this.previousFilterQ.copy(this.filterQ);
  40865. this.accelQ = new Quaternion();
  40866. this.isOrientationInitialized = false;
  40867. this.estimatedGravity = new Vector3();
  40868. this.measuredGravity = new Vector3();
  40869. this.gyroIntegralQ = new Quaternion();
  40870. }
  40871. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  40872. this.currentAccelMeasurement.set(vector, timestampS);
  40873. };
  40874. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  40875. this.currentGyroMeasurement.set(vector, timestampS);
  40876. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  40877. if (isTimestampDeltaValid(deltaT)) {
  40878. this.run_();
  40879. }
  40880. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  40881. };
  40882. ComplementaryFilter.prototype.run_ = function () {
  40883. if (!this.isOrientationInitialized) {
  40884. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  40885. this.previousFilterQ.copy(this.accelQ);
  40886. this.isOrientationInitialized = true;
  40887. return;
  40888. }
  40889. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  40890. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  40891. this.gyroIntegralQ.multiply(gyroDeltaQ);
  40892. this.filterQ.copy(this.previousFilterQ);
  40893. this.filterQ.multiply(gyroDeltaQ);
  40894. var invFilterQ = new Quaternion();
  40895. invFilterQ.copy(this.filterQ);
  40896. invFilterQ.inverse();
  40897. this.estimatedGravity.set(0, 0, -1);
  40898. this.estimatedGravity.applyQuaternion(invFilterQ);
  40899. this.estimatedGravity.normalize();
  40900. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  40901. this.measuredGravity.normalize();
  40902. var deltaQ = new Quaternion();
  40903. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  40904. deltaQ.inverse();
  40905. if (this.isDebug) {
  40906. 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));
  40907. }
  40908. var targetQ = new Quaternion();
  40909. targetQ.copy(this.filterQ);
  40910. targetQ.multiply(deltaQ);
  40911. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  40912. this.previousFilterQ.copy(this.filterQ);
  40913. };
  40914. ComplementaryFilter.prototype.getOrientation = function () {
  40915. return this.filterQ;
  40916. };
  40917. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  40918. var normAccel = new Vector3();
  40919. normAccel.copy(accel);
  40920. normAccel.normalize();
  40921. var quat = new Quaternion();
  40922. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  40923. quat.inverse();
  40924. return quat;
  40925. };
  40926. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  40927. var quat = new Quaternion();
  40928. var axis = new Vector3();
  40929. axis.copy(gyro);
  40930. axis.normalize();
  40931. quat.setFromAxisAngle(axis, gyro.length() * dt);
  40932. return quat;
  40933. };
  40934. function PosePredictor(predictionTimeS, isDebug) {
  40935. this.predictionTimeS = predictionTimeS;
  40936. this.isDebug = isDebug;
  40937. this.previousQ = new Quaternion();
  40938. this.previousTimestampS = null;
  40939. this.deltaQ = new Quaternion();
  40940. this.outQ = new Quaternion();
  40941. }
  40942. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  40943. if (!this.previousTimestampS) {
  40944. this.previousQ.copy(currentQ);
  40945. this.previousTimestampS = timestampS;
  40946. return currentQ;
  40947. }
  40948. var axis = new Vector3();
  40949. axis.copy(gyro);
  40950. axis.normalize();
  40951. var angularSpeed = gyro.length();
  40952. if (angularSpeed < degToRad * 20) {
  40953. if (this.isDebug) {
  40954. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  40955. }
  40956. this.outQ.copy(currentQ);
  40957. this.previousQ.copy(currentQ);
  40958. return this.outQ;
  40959. }
  40960. var predictAngle = angularSpeed * this.predictionTimeS;
  40961. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  40962. this.outQ.copy(this.previousQ);
  40963. this.outQ.multiply(this.deltaQ);
  40964. this.previousQ.copy(currentQ);
  40965. this.previousTimestampS = timestampS;
  40966. return this.outQ;
  40967. };
  40968. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  40969. this.yawOnly = yawOnly;
  40970. this.accelerometer = new Vector3();
  40971. this.gyroscope = new Vector3();
  40972. this.filter = new ComplementaryFilter(kFilter, isDebug);
  40973. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  40974. this.isFirefoxAndroid = isFirefoxAndroid();
  40975. this.isIOS = isIOS();
  40976. var chromeVersion = getChromeVersion();
  40977. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  40978. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  40979. this.filterToWorldQ = new Quaternion();
  40980. if (isIOS()) {
  40981. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  40982. } else {
  40983. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  40984. }
  40985. this.inverseWorldToScreenQ = new Quaternion();
  40986. this.worldToScreenQ = new Quaternion();
  40987. this.originalPoseAdjustQ = new Quaternion();
  40988. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  40989. this.setScreenTransform_();
  40990. if (isLandscapeMode()) {
  40991. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  40992. }
  40993. this.resetQ = new Quaternion();
  40994. this.orientationOut_ = new Float32Array(4);
  40995. this.start();
  40996. }
  40997. FusionPoseSensor.prototype.getPosition = function () {
  40998. return null;
  40999. };
  41000. FusionPoseSensor.prototype.getOrientation = function () {
  41001. var orientation = void 0;
  41002. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  41003. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  41004. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  41005. var y = new Quaternion();
  41006. if (window.orientation === -90) {
  41007. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  41008. } else {
  41009. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  41010. }
  41011. return z.multiply(y);
  41012. }();
  41013. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  41014. var q = new Quaternion();
  41015. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  41016. return q;
  41017. }();
  41018. orientation = this._deviceOrientationQ;
  41019. var out = new Quaternion();
  41020. out.copy(orientation);
  41021. out.multiply(this.deviceOrientationFilterToWorldQ);
  41022. out.multiply(this.resetQ);
  41023. out.multiply(this.worldToScreenQ);
  41024. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  41025. if (this.yawOnly) {
  41026. out.x = 0;
  41027. out.z = 0;
  41028. out.normalize();
  41029. }
  41030. this.orientationOut_[0] = out.x;
  41031. this.orientationOut_[1] = out.y;
  41032. this.orientationOut_[2] = out.z;
  41033. this.orientationOut_[3] = out.w;
  41034. return this.orientationOut_;
  41035. } else {
  41036. var filterOrientation = this.filter.getOrientation();
  41037. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  41038. }
  41039. var out = new Quaternion();
  41040. out.copy(this.filterToWorldQ);
  41041. out.multiply(this.resetQ);
  41042. out.multiply(orientation);
  41043. out.multiply(this.worldToScreenQ);
  41044. if (this.yawOnly) {
  41045. out.x = 0;
  41046. out.z = 0;
  41047. out.normalize();
  41048. }
  41049. this.orientationOut_[0] = out.x;
  41050. this.orientationOut_[1] = out.y;
  41051. this.orientationOut_[2] = out.z;
  41052. this.orientationOut_[3] = out.w;
  41053. return this.orientationOut_;
  41054. };
  41055. FusionPoseSensor.prototype.resetPose = function () {
  41056. this.resetQ.copy(this.filter.getOrientation());
  41057. this.resetQ.x = 0;
  41058. this.resetQ.y = 0;
  41059. this.resetQ.z *= -1;
  41060. this.resetQ.normalize();
  41061. if (isLandscapeMode()) {
  41062. this.resetQ.multiply(this.inverseWorldToScreenQ);
  41063. }
  41064. this.resetQ.multiply(this.originalPoseAdjustQ);
  41065. };
  41066. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  41067. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  41068. var alpha = e.alpha,
  41069. beta = e.beta,
  41070. gamma = e.gamma;
  41071. alpha = (alpha || 0) * Math.PI / 180;
  41072. beta = (beta || 0) * Math.PI / 180;
  41073. gamma = (gamma || 0) * Math.PI / 180;
  41074. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  41075. };
  41076. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  41077. this.updateDeviceMotion_(deviceMotion);
  41078. };
  41079. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  41080. var accGravity = deviceMotion.accelerationIncludingGravity;
  41081. var rotRate = deviceMotion.rotationRate;
  41082. var timestampS = deviceMotion.timeStamp / 1000;
  41083. var deltaS = timestampS - this.previousTimestampS;
  41084. if (deltaS < 0) {
  41085. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  41086. this.previousTimestampS = timestampS;
  41087. return;
  41088. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  41089. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  41090. this.previousTimestampS = timestampS;
  41091. return;
  41092. }
  41093. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  41094. if (isR7()) {
  41095. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  41096. } else {
  41097. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  41098. }
  41099. if (!this.isDeviceMotionInRadians) {
  41100. this.gyroscope.multiplyScalar(Math.PI / 180);
  41101. }
  41102. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  41103. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  41104. this.previousTimestampS = timestampS;
  41105. };
  41106. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  41107. this.setScreenTransform_();
  41108. };
  41109. FusionPoseSensor.prototype.onMessage_ = function (event) {
  41110. var message = event.data;
  41111. if (!message || !message.type) {
  41112. return;
  41113. }
  41114. var type = message.type.toLowerCase();
  41115. if (type !== 'devicemotion') {
  41116. return;
  41117. }
  41118. this.updateDeviceMotion_(message.deviceMotionEvent);
  41119. };
  41120. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  41121. this.worldToScreenQ.set(0, 0, 0, 1);
  41122. switch (window.orientation) {
  41123. case 0:
  41124. break;
  41125. case 90:
  41126. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  41127. break;
  41128. case -90:
  41129. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  41130. break;
  41131. case 180:
  41132. break;
  41133. }
  41134. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  41135. this.inverseWorldToScreenQ.inverse();
  41136. };
  41137. FusionPoseSensor.prototype.start = function () {
  41138. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  41139. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  41140. this.onMessageCallback_ = this.onMessage_.bind(this);
  41141. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  41142. if (isIOS() && isInsideCrossOriginIFrame()) {
  41143. window.addEventListener('message', this.onMessageCallback_);
  41144. }
  41145. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  41146. if (this.isWithoutDeviceMotion) {
  41147. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  41148. } else {
  41149. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  41150. }
  41151. };
  41152. FusionPoseSensor.prototype.stop = function () {
  41153. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  41154. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  41155. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  41156. window.removeEventListener('message', this.onMessageCallback_);
  41157. };
  41158. var SENSOR_FREQUENCY = 60;
  41159. var X_AXIS = new Vector3(1, 0, 0);
  41160. var Z_AXIS = new Vector3(0, 0, 1);
  41161. var SENSOR_TO_VR = new Quaternion();
  41162. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  41163. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  41164. var PoseSensor = function () {
  41165. function PoseSensor(config) {
  41166. classCallCheck(this, PoseSensor);
  41167. this.config = config;
  41168. this.sensor = null;
  41169. this.fusionSensor = null;
  41170. this._out = new Float32Array(4);
  41171. this.api = null;
  41172. this.errors = [];
  41173. this._sensorQ = new Quaternion();
  41174. this._outQ = new Quaternion();
  41175. this._onSensorRead = this._onSensorRead.bind(this);
  41176. this._onSensorError = this._onSensorError.bind(this);
  41177. this.init();
  41178. }
  41179. createClass(PoseSensor, [{
  41180. key: 'init',
  41181. value: function init() {
  41182. var sensor = null;
  41183. try {
  41184. sensor = new RelativeOrientationSensor({
  41185. frequency: SENSOR_FREQUENCY,
  41186. referenceFrame: 'screen'
  41187. });
  41188. sensor.addEventListener('error', this._onSensorError);
  41189. } catch (error) {
  41190. this.errors.push(error);
  41191. if (error.name === 'SecurityError') {
  41192. console.error('Cannot construct sensors due to the Feature Policy');
  41193. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  41194. this.useDeviceMotion();
  41195. } else if (error.name === 'ReferenceError') {
  41196. this.useDeviceMotion();
  41197. } else {
  41198. console.error(error);
  41199. }
  41200. }
  41201. if (sensor) {
  41202. this.api = 'sensor';
  41203. this.sensor = sensor;
  41204. this.sensor.addEventListener('reading', this._onSensorRead);
  41205. this.sensor.start();
  41206. }
  41207. }
  41208. }, {
  41209. key: 'useDeviceMotion',
  41210. value: function useDeviceMotion() {
  41211. this.api = 'devicemotion';
  41212. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  41213. if (this.sensor) {
  41214. this.sensor.removeEventListener('reading', this._onSensorRead);
  41215. this.sensor.removeEventListener('error', this._onSensorError);
  41216. this.sensor = null;
  41217. }
  41218. }
  41219. }, {
  41220. key: 'getOrientation',
  41221. value: function getOrientation() {
  41222. if (this.fusionSensor) {
  41223. return this.fusionSensor.getOrientation();
  41224. }
  41225. if (!this.sensor || !this.sensor.quaternion) {
  41226. this._out[0] = this._out[1] = this._out[2] = 0;
  41227. this._out[3] = 1;
  41228. return this._out;
  41229. }
  41230. var q = this.sensor.quaternion;
  41231. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  41232. var out = this._outQ;
  41233. out.copy(SENSOR_TO_VR);
  41234. out.multiply(this._sensorQ);
  41235. if (this.config.YAW_ONLY) {
  41236. out.x = out.z = 0;
  41237. out.normalize();
  41238. }
  41239. this._out[0] = out.x;
  41240. this._out[1] = out.y;
  41241. this._out[2] = out.z;
  41242. this._out[3] = out.w;
  41243. return this._out;
  41244. }
  41245. }, {
  41246. key: '_onSensorError',
  41247. value: function _onSensorError(event) {
  41248. this.errors.push(event.error);
  41249. if (event.error.name === 'NotAllowedError') {
  41250. console.error('Permission to access sensor was denied');
  41251. } else if (event.error.name === 'NotReadableError') {
  41252. console.error('Sensor could not be read');
  41253. } else {
  41254. console.error(event.error);
  41255. }
  41256. this.useDeviceMotion();
  41257. }
  41258. }, {
  41259. key: '_onSensorRead',
  41260. value: function _onSensorRead() {}
  41261. }]);
  41262. return PoseSensor;
  41263. }();
  41264. 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>";
  41265. function RotateInstructions() {
  41266. this.loadIcon_();
  41267. var overlay = document.createElement('div');
  41268. var s = overlay.style;
  41269. s.position = 'fixed';
  41270. s.top = 0;
  41271. s.right = 0;
  41272. s.bottom = 0;
  41273. s.left = 0;
  41274. s.backgroundColor = 'gray';
  41275. s.fontFamily = 'sans-serif';
  41276. s.zIndex = 1000000;
  41277. var img = document.createElement('img');
  41278. img.src = this.icon;
  41279. var s = img.style;
  41280. s.marginLeft = '25%';
  41281. s.marginTop = '25%';
  41282. s.width = '50%';
  41283. overlay.appendChild(img);
  41284. var text = document.createElement('div');
  41285. var s = text.style;
  41286. s.textAlign = 'center';
  41287. s.fontSize = '16px';
  41288. s.lineHeight = '24px';
  41289. s.margin = '24px 25%';
  41290. s.width = '50%';
  41291. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  41292. overlay.appendChild(text);
  41293. var snackbar = document.createElement('div');
  41294. var s = snackbar.style;
  41295. s.backgroundColor = '#CFD8DC';
  41296. s.position = 'fixed';
  41297. s.bottom = 0;
  41298. s.width = '100%';
  41299. s.height = '48px';
  41300. s.padding = '14px 24px';
  41301. s.boxSizing = 'border-box';
  41302. s.color = '#656A6B';
  41303. overlay.appendChild(snackbar);
  41304. var snackbarText = document.createElement('div');
  41305. snackbarText.style.float = 'left';
  41306. snackbarText.innerHTML = 'No Cardboard viewer?';
  41307. var snackbarButton = document.createElement('a');
  41308. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  41309. snackbarButton.innerHTML = 'get one';
  41310. snackbarButton.target = '_blank';
  41311. var s = snackbarButton.style;
  41312. s.float = 'right';
  41313. s.fontWeight = 600;
  41314. s.textTransform = 'uppercase';
  41315. s.borderLeft = '1px solid gray';
  41316. s.paddingLeft = '24px';
  41317. s.textDecoration = 'none';
  41318. s.color = '#656A6B';
  41319. snackbar.appendChild(snackbarText);
  41320. snackbar.appendChild(snackbarButton);
  41321. this.overlay = overlay;
  41322. this.text = text;
  41323. this.hide();
  41324. }
  41325. RotateInstructions.prototype.show = function (parent) {
  41326. if (!parent && !this.overlay.parentElement) {
  41327. document.body.appendChild(this.overlay);
  41328. } else if (parent) {
  41329. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  41330. parent.appendChild(this.overlay);
  41331. }
  41332. this.overlay.style.display = 'block';
  41333. var img = this.overlay.querySelector('img');
  41334. var s = img.style;
  41335. if (isLandscapeMode()) {
  41336. s.width = '20%';
  41337. s.marginLeft = '40%';
  41338. s.marginTop = '3%';
  41339. } else {
  41340. s.width = '50%';
  41341. s.marginLeft = '25%';
  41342. s.marginTop = '25%';
  41343. }
  41344. };
  41345. RotateInstructions.prototype.hide = function () {
  41346. this.overlay.style.display = 'none';
  41347. };
  41348. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  41349. this.show(parent);
  41350. this.timer = setTimeout(this.hide.bind(this), ms);
  41351. };
  41352. RotateInstructions.prototype.disableShowTemporarily = function () {
  41353. clearTimeout(this.timer);
  41354. };
  41355. RotateInstructions.prototype.update = function () {
  41356. this.disableShowTemporarily();
  41357. if (!isLandscapeMode() && isMobile()) {
  41358. this.show();
  41359. } else {
  41360. this.hide();
  41361. }
  41362. };
  41363. RotateInstructions.prototype.loadIcon_ = function () {
  41364. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  41365. };
  41366. var DEFAULT_VIEWER = 'CardboardV1';
  41367. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  41368. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  41369. function ViewerSelector(defaultViewer) {
  41370. try {
  41371. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  41372. } catch (error) {
  41373. console.error('Failed to load viewer profile: %s', error);
  41374. }
  41375. if (!this.selectedKey) {
  41376. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  41377. }
  41378. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  41379. this.root = null;
  41380. this.onChangeCallbacks_ = [];
  41381. }
  41382. ViewerSelector.prototype.show = function (root) {
  41383. this.root = root;
  41384. root.appendChild(this.dialog);
  41385. var selected = this.dialog.querySelector('#' + this.selectedKey);
  41386. selected.checked = true;
  41387. this.dialog.style.display = 'block';
  41388. };
  41389. ViewerSelector.prototype.hide = function () {
  41390. if (this.root && this.root.contains(this.dialog)) {
  41391. this.root.removeChild(this.dialog);
  41392. }
  41393. this.dialog.style.display = 'none';
  41394. };
  41395. ViewerSelector.prototype.getCurrentViewer = function () {
  41396. return DeviceInfo.Viewers[this.selectedKey];
  41397. };
  41398. ViewerSelector.prototype.getSelectedKey_ = function () {
  41399. var input = this.dialog.querySelector('input[name=field]:checked');
  41400. if (input) {
  41401. return input.id;
  41402. }
  41403. return null;
  41404. };
  41405. ViewerSelector.prototype.onChange = function (cb) {
  41406. this.onChangeCallbacks_.push(cb);
  41407. };
  41408. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  41409. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  41410. this.onChangeCallbacks_[i](viewer);
  41411. }
  41412. };
  41413. ViewerSelector.prototype.onSave_ = function () {
  41414. this.selectedKey = this.getSelectedKey_();
  41415. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  41416. console.error('ViewerSelector.onSave_: this should never happen!');
  41417. return;
  41418. }
  41419. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  41420. try {
  41421. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  41422. } catch (error) {
  41423. console.error('Failed to save viewer profile: %s', error);
  41424. }
  41425. this.hide();
  41426. };
  41427. ViewerSelector.prototype.createDialog_ = function (options) {
  41428. var container = document.createElement('div');
  41429. container.classList.add(CLASS_NAME);
  41430. container.style.display = 'none';
  41431. var overlay = document.createElement('div');
  41432. var s = overlay.style;
  41433. s.position = 'fixed';
  41434. s.left = 0;
  41435. s.top = 0;
  41436. s.width = '100%';
  41437. s.height = '100%';
  41438. s.background = 'rgba(0, 0, 0, 0.3)';
  41439. overlay.addEventListener('click', this.hide.bind(this));
  41440. var width = 280;
  41441. var dialog = document.createElement('div');
  41442. var s = dialog.style;
  41443. s.boxSizing = 'border-box';
  41444. s.position = 'fixed';
  41445. s.top = '24px';
  41446. s.left = '50%';
  41447. s.marginLeft = -width / 2 + 'px';
  41448. s.width = width + 'px';
  41449. s.padding = '24px';
  41450. s.overflow = 'hidden';
  41451. s.background = '#fafafa';
  41452. s.fontFamily = "'Roboto', sans-serif";
  41453. s.boxShadow = '0px 5px 20px #666';
  41454. dialog.appendChild(this.createH1_('Select your viewer'));
  41455. for (var id in options) {
  41456. dialog.appendChild(this.createChoice_(id, options[id].label));
  41457. }
  41458. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  41459. container.appendChild(overlay);
  41460. container.appendChild(dialog);
  41461. return container;
  41462. };
  41463. ViewerSelector.prototype.createH1_ = function (name) {
  41464. var h1 = document.createElement('h1');
  41465. var s = h1.style;
  41466. s.color = 'black';
  41467. s.fontSize = '20px';
  41468. s.fontWeight = 'bold';
  41469. s.marginTop = 0;
  41470. s.marginBottom = '24px';
  41471. h1.innerHTML = name;
  41472. return h1;
  41473. };
  41474. ViewerSelector.prototype.createChoice_ = function (id, name) {
  41475. var div = document.createElement('div');
  41476. div.style.marginTop = '8px';
  41477. div.style.color = 'black';
  41478. var input = document.createElement('input');
  41479. input.style.fontSize = '30px';
  41480. input.setAttribute('id', id);
  41481. input.setAttribute('type', 'radio');
  41482. input.setAttribute('value', id);
  41483. input.setAttribute('name', 'field');
  41484. var label = document.createElement('label');
  41485. label.style.marginLeft = '4px';
  41486. label.setAttribute('for', id);
  41487. label.innerHTML = name;
  41488. div.appendChild(input);
  41489. div.appendChild(label);
  41490. return div;
  41491. };
  41492. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  41493. var button = document.createElement('button');
  41494. button.innerHTML = label;
  41495. var s = button.style;
  41496. s.float = 'right';
  41497. s.textTransform = 'uppercase';
  41498. s.color = '#1094f7';
  41499. s.fontSize = '14px';
  41500. s.letterSpacing = 0;
  41501. s.border = 0;
  41502. s.background = 'none';
  41503. s.marginTop = '16px';
  41504. button.addEventListener('click', onclick);
  41505. return button;
  41506. };
  41507. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  41508. function unwrapExports$$1 (x) {
  41509. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  41510. }
  41511. function createCommonjsModule$$1(fn, module) {
  41512. return module = { exports: {} }, fn(module, module.exports), module.exports;
  41513. }
  41514. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  41515. (function webpackUniversalModuleDefinition(root, factory) {
  41516. module.exports = factory();
  41517. })(commonjsGlobal$$1, function() {
  41518. return (function(modules) {
  41519. var installedModules = {};
  41520. function __webpack_require__(moduleId) {
  41521. if(installedModules[moduleId]) {
  41522. return installedModules[moduleId].exports;
  41523. }
  41524. var module = installedModules[moduleId] = {
  41525. i: moduleId,
  41526. l: false,
  41527. exports: {}
  41528. };
  41529. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  41530. module.l = true;
  41531. return module.exports;
  41532. }
  41533. __webpack_require__.m = modules;
  41534. __webpack_require__.c = installedModules;
  41535. __webpack_require__.d = function(exports, name, getter) {
  41536. if(!__webpack_require__.o(exports, name)) {
  41537. Object.defineProperty(exports, name, {
  41538. configurable: false,
  41539. enumerable: true,
  41540. get: getter
  41541. });
  41542. }
  41543. };
  41544. __webpack_require__.n = function(module) {
  41545. var getter = module && module.__esModule ?
  41546. function getDefault() { return module['default']; } :
  41547. function getModuleExports() { return module; };
  41548. __webpack_require__.d(getter, 'a', getter);
  41549. return getter;
  41550. };
  41551. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  41552. __webpack_require__.p = "";
  41553. return __webpack_require__(__webpack_require__.s = 0);
  41554. })
  41555. ([
  41556. (function(module, exports, __webpack_require__) {
  41557. 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; }; }();
  41558. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  41559. var mediaFile = __webpack_require__(1);
  41560. 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;
  41561. var NoSleep = function () {
  41562. function NoSleep() {
  41563. _classCallCheck(this, NoSleep);
  41564. if (oldIOS) {
  41565. this.noSleepTimer = null;
  41566. } else {
  41567. this.noSleepVideo = document.createElement('video');
  41568. this.noSleepVideo.setAttribute('playsinline', '');
  41569. this.noSleepVideo.setAttribute('src', mediaFile);
  41570. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  41571. if (this.noSleepVideo.currentTime > 0.5) {
  41572. this.noSleepVideo.currentTime = Math.random();
  41573. }
  41574. }.bind(this));
  41575. }
  41576. }
  41577. _createClass(NoSleep, [{
  41578. key: 'enable',
  41579. value: function enable() {
  41580. if (oldIOS) {
  41581. this.disable();
  41582. this.noSleepTimer = window.setInterval(function () {
  41583. window.location.href = '/';
  41584. window.setTimeout(window.stop, 0);
  41585. }, 15000);
  41586. } else {
  41587. this.noSleepVideo.play();
  41588. }
  41589. }
  41590. }, {
  41591. key: 'disable',
  41592. value: function disable() {
  41593. if (oldIOS) {
  41594. if (this.noSleepTimer) {
  41595. window.clearInterval(this.noSleepTimer);
  41596. this.noSleepTimer = null;
  41597. }
  41598. } else {
  41599. this.noSleepVideo.pause();
  41600. }
  41601. }
  41602. }]);
  41603. return NoSleep;
  41604. }();
  41605. module.exports = NoSleep;
  41606. }),
  41607. (function(module, exports, __webpack_require__) {
  41608. 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=';
  41609. })
  41610. ]);
  41611. });
  41612. });
  41613. var NoSleep$1 = unwrapExports$$1(NoSleep);
  41614. var nextDisplayId = 1000;
  41615. var defaultLeftBounds = [0, 0, 0.5, 1];
  41616. var defaultRightBounds = [0.5, 0, 0.5, 1];
  41617. var raf = window.requestAnimationFrame;
  41618. var caf = window.cancelAnimationFrame;
  41619. function VRFrameData() {
  41620. this.leftProjectionMatrix = new Float32Array(16);
  41621. this.leftViewMatrix = new Float32Array(16);
  41622. this.rightProjectionMatrix = new Float32Array(16);
  41623. this.rightViewMatrix = new Float32Array(16);
  41624. this.pose = null;
  41625. }
  41626. function VRDisplayCapabilities(config) {
  41627. Object.defineProperties(this, {
  41628. hasPosition: {
  41629. writable: false, enumerable: true, value: config.hasPosition
  41630. },
  41631. hasExternalDisplay: {
  41632. writable: false, enumerable: true, value: config.hasExternalDisplay
  41633. },
  41634. canPresent: {
  41635. writable: false, enumerable: true, value: config.canPresent
  41636. },
  41637. maxLayers: {
  41638. writable: false, enumerable: true, value: config.maxLayers
  41639. },
  41640. hasOrientation: {
  41641. enumerable: true, get: function get() {
  41642. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  41643. return config.hasOrientation;
  41644. }
  41645. }
  41646. });
  41647. }
  41648. function VRDisplay(config) {
  41649. config = config || {};
  41650. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  41651. this.isPolyfilled = true;
  41652. this.displayId = nextDisplayId++;
  41653. this.displayName = '';
  41654. this.depthNear = 0.01;
  41655. this.depthFar = 10000.0;
  41656. this.isPresenting = false;
  41657. Object.defineProperty(this, 'isConnected', {
  41658. get: function get() {
  41659. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  41660. return false;
  41661. }
  41662. });
  41663. this.capabilities = new VRDisplayCapabilities({
  41664. hasPosition: false,
  41665. hasOrientation: false,
  41666. hasExternalDisplay: false,
  41667. canPresent: false,
  41668. maxLayers: 1
  41669. });
  41670. this.stageParameters = null;
  41671. this.waitingForPresent_ = false;
  41672. this.layer_ = null;
  41673. this.originalParent_ = null;
  41674. this.fullscreenElement_ = null;
  41675. this.fullscreenWrapper_ = null;
  41676. this.fullscreenElementCachedStyle_ = null;
  41677. this.fullscreenEventTarget_ = null;
  41678. this.fullscreenChangeHandler_ = null;
  41679. this.fullscreenErrorHandler_ = null;
  41680. if (USE_WAKELOCK && isMobile()) {
  41681. this.wakelock_ = new NoSleep$1();
  41682. }
  41683. }
  41684. VRDisplay.prototype.getFrameData = function (frameData) {
  41685. return frameDataFromPose(frameData, this._getPose(), this);
  41686. };
  41687. VRDisplay.prototype.getPose = function () {
  41688. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  41689. return this._getPose();
  41690. };
  41691. VRDisplay.prototype.resetPose = function () {
  41692. deprecateWarning('VRDisplay.prototype.resetPose');
  41693. return this._resetPose();
  41694. };
  41695. VRDisplay.prototype.getImmediatePose = function () {
  41696. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  41697. return this._getPose();
  41698. };
  41699. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  41700. return raf(callback);
  41701. };
  41702. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  41703. return caf(id);
  41704. };
  41705. VRDisplay.prototype.wrapForFullscreen = function (element) {
  41706. if (isIOS()) {
  41707. return element;
  41708. }
  41709. if (!this.fullscreenWrapper_) {
  41710. this.fullscreenWrapper_ = document.createElement('div');
  41711. 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'];
  41712. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  41713. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  41714. }
  41715. if (this.fullscreenElement_ == element) {
  41716. return this.fullscreenWrapper_;
  41717. }
  41718. if (this.fullscreenElement_) {
  41719. if (this.originalParent_) {
  41720. this.originalParent_.appendChild(this.fullscreenElement_);
  41721. } else {
  41722. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  41723. }
  41724. }
  41725. this.fullscreenElement_ = element;
  41726. this.originalParent_ = element.parentElement;
  41727. if (!this.originalParent_) {
  41728. document.body.appendChild(element);
  41729. }
  41730. if (!this.fullscreenWrapper_.parentElement) {
  41731. var parent = this.fullscreenElement_.parentElement;
  41732. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  41733. parent.removeChild(this.fullscreenElement_);
  41734. }
  41735. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  41736. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  41737. var self = this;
  41738. function applyFullscreenElementStyle() {
  41739. if (!self.fullscreenElement_) {
  41740. return;
  41741. }
  41742. 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'];
  41743. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  41744. }
  41745. applyFullscreenElementStyle();
  41746. return this.fullscreenWrapper_;
  41747. };
  41748. VRDisplay.prototype.removeFullscreenWrapper = function () {
  41749. if (!this.fullscreenElement_) {
  41750. return;
  41751. }
  41752. var element = this.fullscreenElement_;
  41753. if (this.fullscreenElementCachedStyle_) {
  41754. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  41755. } else {
  41756. element.removeAttribute('style');
  41757. }
  41758. this.fullscreenElement_ = null;
  41759. this.fullscreenElementCachedStyle_ = null;
  41760. var parent = this.fullscreenWrapper_.parentElement;
  41761. this.fullscreenWrapper_.removeChild(element);
  41762. if (this.originalParent_ === parent) {
  41763. parent.insertBefore(element, this.fullscreenWrapper_);
  41764. }
  41765. else if (this.originalParent_) {
  41766. this.originalParent_.appendChild(element);
  41767. }
  41768. parent.removeChild(this.fullscreenWrapper_);
  41769. return element;
  41770. };
  41771. VRDisplay.prototype.requestPresent = function (layers) {
  41772. var wasPresenting = this.isPresenting;
  41773. var self = this;
  41774. if (!(layers instanceof Array)) {
  41775. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  41776. layers = [layers];
  41777. }
  41778. return new Promise(function (resolve, reject) {
  41779. if (!self.capabilities.canPresent) {
  41780. reject(new Error('VRDisplay is not capable of presenting.'));
  41781. return;
  41782. }
  41783. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  41784. reject(new Error('Invalid number of layers.'));
  41785. return;
  41786. }
  41787. var incomingLayer = layers[0];
  41788. if (!incomingLayer.source) {
  41789. resolve();
  41790. return;
  41791. }
  41792. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  41793. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  41794. if (wasPresenting) {
  41795. var layer = self.layer_;
  41796. if (layer.source !== incomingLayer.source) {
  41797. layer.source = incomingLayer.source;
  41798. }
  41799. for (var i = 0; i < 4; i++) {
  41800. layer.leftBounds[i] = leftBounds[i];
  41801. layer.rightBounds[i] = rightBounds[i];
  41802. }
  41803. self.wrapForFullscreen(self.layer_.source);
  41804. self.updatePresent_();
  41805. resolve();
  41806. return;
  41807. }
  41808. self.layer_ = {
  41809. predistorted: incomingLayer.predistorted,
  41810. source: incomingLayer.source,
  41811. leftBounds: leftBounds.slice(0),
  41812. rightBounds: rightBounds.slice(0)
  41813. };
  41814. self.waitingForPresent_ = false;
  41815. if (self.layer_ && self.layer_.source) {
  41816. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  41817. var onFullscreenChange = function onFullscreenChange() {
  41818. var actualFullscreenElement = getFullscreenElement();
  41819. self.isPresenting = fullscreenElement === actualFullscreenElement;
  41820. if (self.isPresenting) {
  41821. if (screen.orientation && screen.orientation.lock) {
  41822. screen.orientation.lock('landscape-primary').catch(function (error) {
  41823. console.error('screen.orientation.lock() failed due to', error.message);
  41824. });
  41825. }
  41826. self.waitingForPresent_ = false;
  41827. self.beginPresent_();
  41828. resolve();
  41829. } else {
  41830. if (screen.orientation && screen.orientation.unlock) {
  41831. screen.orientation.unlock();
  41832. }
  41833. self.removeFullscreenWrapper();
  41834. self.disableWakeLock();
  41835. self.endPresent_();
  41836. self.removeFullscreenListeners_();
  41837. }
  41838. self.fireVRDisplayPresentChange_();
  41839. };
  41840. var onFullscreenError = function onFullscreenError() {
  41841. if (!self.waitingForPresent_) {
  41842. return;
  41843. }
  41844. self.removeFullscreenWrapper();
  41845. self.removeFullscreenListeners_();
  41846. self.disableWakeLock();
  41847. self.waitingForPresent_ = false;
  41848. self.isPresenting = false;
  41849. reject(new Error('Unable to present.'));
  41850. };
  41851. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  41852. if (requestFullscreen(fullscreenElement)) {
  41853. self.enableWakeLock();
  41854. self.waitingForPresent_ = true;
  41855. } else if (isIOS() || isWebViewAndroid()) {
  41856. self.enableWakeLock();
  41857. self.isPresenting = true;
  41858. self.beginPresent_();
  41859. self.fireVRDisplayPresentChange_();
  41860. resolve();
  41861. }
  41862. }
  41863. if (!self.waitingForPresent_ && !isIOS()) {
  41864. exitFullscreen();
  41865. reject(new Error('Unable to present.'));
  41866. }
  41867. });
  41868. };
  41869. VRDisplay.prototype.exitPresent = function () {
  41870. var wasPresenting = this.isPresenting;
  41871. var self = this;
  41872. this.isPresenting = false;
  41873. this.layer_ = null;
  41874. this.disableWakeLock();
  41875. return new Promise(function (resolve, reject) {
  41876. if (wasPresenting) {
  41877. if (!exitFullscreen() && isIOS()) {
  41878. self.endPresent_();
  41879. self.fireVRDisplayPresentChange_();
  41880. }
  41881. if (isWebViewAndroid()) {
  41882. self.removeFullscreenWrapper();
  41883. self.removeFullscreenListeners_();
  41884. self.endPresent_();
  41885. self.fireVRDisplayPresentChange_();
  41886. }
  41887. resolve();
  41888. } else {
  41889. reject(new Error('Was not presenting to VRDisplay.'));
  41890. }
  41891. });
  41892. };
  41893. VRDisplay.prototype.getLayers = function () {
  41894. if (this.layer_) {
  41895. return [this.layer_];
  41896. }
  41897. return [];
  41898. };
  41899. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  41900. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  41901. window.dispatchEvent(event);
  41902. };
  41903. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  41904. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  41905. window.dispatchEvent(event);
  41906. };
  41907. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  41908. this.removeFullscreenListeners_();
  41909. this.fullscreenEventTarget_ = element;
  41910. this.fullscreenChangeHandler_ = changeHandler;
  41911. this.fullscreenErrorHandler_ = errorHandler;
  41912. if (changeHandler) {
  41913. if (document.fullscreenEnabled) {
  41914. element.addEventListener('fullscreenchange', changeHandler, false);
  41915. } else if (document.webkitFullscreenEnabled) {
  41916. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  41917. } else if (document.mozFullScreenEnabled) {
  41918. document.addEventListener('mozfullscreenchange', changeHandler, false);
  41919. } else if (document.msFullscreenEnabled) {
  41920. element.addEventListener('msfullscreenchange', changeHandler, false);
  41921. }
  41922. }
  41923. if (errorHandler) {
  41924. if (document.fullscreenEnabled) {
  41925. element.addEventListener('fullscreenerror', errorHandler, false);
  41926. } else if (document.webkitFullscreenEnabled) {
  41927. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  41928. } else if (document.mozFullScreenEnabled) {
  41929. document.addEventListener('mozfullscreenerror', errorHandler, false);
  41930. } else if (document.msFullscreenEnabled) {
  41931. element.addEventListener('msfullscreenerror', errorHandler, false);
  41932. }
  41933. }
  41934. };
  41935. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  41936. if (!this.fullscreenEventTarget_) return;
  41937. var element = this.fullscreenEventTarget_;
  41938. if (this.fullscreenChangeHandler_) {
  41939. var changeHandler = this.fullscreenChangeHandler_;
  41940. element.removeEventListener('fullscreenchange', changeHandler, false);
  41941. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  41942. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  41943. element.removeEventListener('msfullscreenchange', changeHandler, false);
  41944. }
  41945. if (this.fullscreenErrorHandler_) {
  41946. var errorHandler = this.fullscreenErrorHandler_;
  41947. element.removeEventListener('fullscreenerror', errorHandler, false);
  41948. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  41949. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  41950. element.removeEventListener('msfullscreenerror', errorHandler, false);
  41951. }
  41952. this.fullscreenEventTarget_ = null;
  41953. this.fullscreenChangeHandler_ = null;
  41954. this.fullscreenErrorHandler_ = null;
  41955. };
  41956. VRDisplay.prototype.enableWakeLock = function () {
  41957. if (this.wakelock_) {
  41958. this.wakelock_.enable();
  41959. }
  41960. };
  41961. VRDisplay.prototype.disableWakeLock = function () {
  41962. if (this.wakelock_) {
  41963. this.wakelock_.disable();
  41964. }
  41965. };
  41966. VRDisplay.prototype.beginPresent_ = function () {
  41967. };
  41968. VRDisplay.prototype.endPresent_ = function () {
  41969. };
  41970. VRDisplay.prototype.submitFrame = function (pose) {
  41971. };
  41972. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  41973. return null;
  41974. };
  41975. var config = {
  41976. ADDITIONAL_VIEWERS: [],
  41977. DEFAULT_VIEWER: '',
  41978. MOBILE_WAKE_LOCK: true,
  41979. DEBUG: false,
  41980. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  41981. K_FILTER: 0.98,
  41982. PREDICTION_TIME_S: 0.040,
  41983. CARDBOARD_UI_DISABLED: false,
  41984. ROTATE_INSTRUCTIONS_DISABLED: false,
  41985. YAW_ONLY: false,
  41986. BUFFER_SCALE: 0.5,
  41987. DIRTY_SUBMIT_FRAME_BINDINGS: false
  41988. };
  41989. var Eye = {
  41990. LEFT: 'left',
  41991. RIGHT: 'right'
  41992. };
  41993. function CardboardVRDisplay(config$$1) {
  41994. var defaults = extend({}, config);
  41995. config$$1 = extend(defaults, config$$1 || {});
  41996. VRDisplay.call(this, {
  41997. wakelock: config$$1.MOBILE_WAKE_LOCK
  41998. });
  41999. this.config = config$$1;
  42000. this.displayName = 'Cardboard VRDisplay';
  42001. this.capabilities = new VRDisplayCapabilities({
  42002. hasPosition: false,
  42003. hasOrientation: true,
  42004. hasExternalDisplay: false,
  42005. canPresent: true,
  42006. maxLayers: 1
  42007. });
  42008. this.stageParameters = null;
  42009. this.bufferScale_ = this.config.BUFFER_SCALE;
  42010. this.poseSensor_ = new PoseSensor(this.config);
  42011. this.distorter_ = null;
  42012. this.cardboardUI_ = null;
  42013. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  42014. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  42015. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  42016. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  42017. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  42018. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  42019. this.rotateInstructions_ = new RotateInstructions();
  42020. }
  42021. if (isIOS()) {
  42022. window.addEventListener('resize', this.onResize_.bind(this));
  42023. }
  42024. }
  42025. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  42026. CardboardVRDisplay.prototype._getPose = function () {
  42027. return {
  42028. position: null,
  42029. orientation: this.poseSensor_.getOrientation(),
  42030. linearVelocity: null,
  42031. linearAcceleration: null,
  42032. angularVelocity: null,
  42033. angularAcceleration: null
  42034. };
  42035. };
  42036. CardboardVRDisplay.prototype._resetPose = function () {
  42037. if (this.poseSensor_.resetPose) {
  42038. this.poseSensor_.resetPose();
  42039. }
  42040. };
  42041. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  42042. var fieldOfView;
  42043. if (whichEye == Eye.LEFT) {
  42044. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  42045. } else if (whichEye == Eye.RIGHT) {
  42046. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  42047. } else {
  42048. console.error('Invalid eye provided: %s', whichEye);
  42049. return null;
  42050. }
  42051. return fieldOfView;
  42052. };
  42053. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  42054. var offset;
  42055. if (whichEye == Eye.LEFT) {
  42056. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  42057. } else if (whichEye == Eye.RIGHT) {
  42058. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  42059. } else {
  42060. console.error('Invalid eye provided: %s', whichEye);
  42061. return null;
  42062. }
  42063. return offset;
  42064. };
  42065. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  42066. var offset = this._getEyeOffset(whichEye);
  42067. var fieldOfView = this._getFieldOfView(whichEye);
  42068. var eyeParams = {
  42069. offset: offset,
  42070. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  42071. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  42072. };
  42073. Object.defineProperty(eyeParams, 'fieldOfView', {
  42074. enumerable: true,
  42075. get: function get() {
  42076. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  42077. return fieldOfView;
  42078. }
  42079. });
  42080. return eyeParams;
  42081. };
  42082. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  42083. if (this.config.DEBUG) {
  42084. console.log('DPDB reported that device params were updated.');
  42085. }
  42086. this.deviceInfo_.updateDeviceParams(newParams);
  42087. if (this.distorter_) {
  42088. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  42089. }
  42090. };
  42091. CardboardVRDisplay.prototype.updateBounds_ = function () {
  42092. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  42093. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  42094. }
  42095. };
  42096. CardboardVRDisplay.prototype.beginPresent_ = function () {
  42097. var gl = this.layer_.source.getContext('webgl');
  42098. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  42099. if (!gl) gl = this.layer_.source.getContext('webgl2');
  42100. if (!gl) return;
  42101. if (this.layer_.predistorted) {
  42102. if (!this.config.CARDBOARD_UI_DISABLED) {
  42103. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  42104. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  42105. this.cardboardUI_ = new CardboardUI(gl);
  42106. }
  42107. } else {
  42108. if (!this.config.CARDBOARD_UI_DISABLED) {
  42109. this.cardboardUI_ = new CardboardUI(gl);
  42110. }
  42111. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  42112. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  42113. }
  42114. if (this.cardboardUI_) {
  42115. this.cardboardUI_.listen(function (e) {
  42116. this.viewerSelector_.show(this.layer_.source.parentElement);
  42117. e.stopPropagation();
  42118. e.preventDefault();
  42119. }.bind(this), function (e) {
  42120. this.exitPresent();
  42121. e.stopPropagation();
  42122. e.preventDefault();
  42123. }.bind(this));
  42124. }
  42125. if (this.rotateInstructions_) {
  42126. if (isLandscapeMode() && isMobile()) {
  42127. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  42128. } else {
  42129. this.rotateInstructions_.update();
  42130. }
  42131. }
  42132. this.orientationHandler = this.onOrientationChange_.bind(this);
  42133. window.addEventListener('orientationchange', this.orientationHandler);
  42134. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  42135. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  42136. this.fireVRDisplayDeviceParamsChange_();
  42137. };
  42138. CardboardVRDisplay.prototype.endPresent_ = function () {
  42139. if (this.distorter_) {
  42140. this.distorter_.destroy();
  42141. this.distorter_ = null;
  42142. }
  42143. if (this.cardboardUI_) {
  42144. this.cardboardUI_.destroy();
  42145. this.cardboardUI_ = null;
  42146. }
  42147. if (this.rotateInstructions_) {
  42148. this.rotateInstructions_.hide();
  42149. }
  42150. this.viewerSelector_.hide();
  42151. window.removeEventListener('orientationchange', this.orientationHandler);
  42152. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  42153. };
  42154. CardboardVRDisplay.prototype.updatePresent_ = function () {
  42155. this.endPresent_();
  42156. this.beginPresent_();
  42157. };
  42158. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  42159. if (this.distorter_) {
  42160. this.updateBounds_();
  42161. this.distorter_.submitFrame();
  42162. } else if (this.cardboardUI_ && this.layer_) {
  42163. var canvas = this.layer_.source.getContext('webgl').canvas;
  42164. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  42165. this.cardboardUI_.onResize();
  42166. }
  42167. this.lastWidth = canvas.width;
  42168. this.lastHeight = canvas.height;
  42169. this.cardboardUI_.render();
  42170. }
  42171. };
  42172. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  42173. this.viewerSelector_.hide();
  42174. if (this.rotateInstructions_) {
  42175. this.rotateInstructions_.update();
  42176. }
  42177. this.onResize_();
  42178. };
  42179. CardboardVRDisplay.prototype.onResize_ = function (e) {
  42180. if (this.layer_) {
  42181. var gl = this.layer_.source.getContext('webgl');
  42182. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  42183. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  42184. 'padding: 0px', 'box-sizing: content-box'];
  42185. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  42186. safariCssSizeWorkaround(gl.canvas);
  42187. }
  42188. };
  42189. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  42190. this.deviceInfo_.setViewer(viewer);
  42191. if (this.distorter_) {
  42192. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  42193. }
  42194. this.fireVRDisplayDeviceParamsChange_();
  42195. };
  42196. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  42197. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  42198. detail: {
  42199. vrdisplay: this,
  42200. deviceInfo: this.deviceInfo_
  42201. }
  42202. });
  42203. window.dispatchEvent(event);
  42204. };
  42205. CardboardVRDisplay.VRFrameData = VRFrameData;
  42206. CardboardVRDisplay.VRDisplay = VRDisplay;
  42207. return CardboardVRDisplay;
  42208. })));
  42209. });
  42210. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  42211. var version = "0.10.10";
  42212. var DefaultConfig = {
  42213. ADDITIONAL_VIEWERS: [],
  42214. DEFAULT_VIEWER: '',
  42215. PROVIDE_MOBILE_VRDISPLAY: true,
  42216. MOBILE_WAKE_LOCK: true,
  42217. DEBUG: false,
  42218. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  42219. K_FILTER: 0.98,
  42220. PREDICTION_TIME_S: 0.040,
  42221. CARDBOARD_UI_DISABLED: false,
  42222. ROTATE_INSTRUCTIONS_DISABLED: false,
  42223. YAW_ONLY: false,
  42224. BUFFER_SCALE: 0.5,
  42225. DIRTY_SUBMIT_FRAME_BINDINGS: false
  42226. };
  42227. function WebVRPolyfill(config) {
  42228. this.config = extend(extend({}, DefaultConfig), config);
  42229. this.polyfillDisplays = [];
  42230. this.enabled = false;
  42231. this.hasNative = 'getVRDisplays' in navigator;
  42232. this.native = {};
  42233. this.native.getVRDisplays = navigator.getVRDisplays;
  42234. this.native.VRFrameData = window.VRFrameData;
  42235. this.native.VRDisplay = window.VRDisplay;
  42236. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  42237. this.enable();
  42238. this.getVRDisplays().then(function (displays) {
  42239. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  42240. displays[0].fireVRDisplayConnect_();
  42241. }
  42242. });
  42243. }
  42244. }
  42245. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  42246. if (this._polyfillDisplaysPopulated) {
  42247. return this.polyfillDisplays;
  42248. }
  42249. if (isMobile()) {
  42250. var vrDisplay = new CardboardVRDisplay({
  42251. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  42252. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  42253. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  42254. DEBUG: this.config.DEBUG,
  42255. DPDB_URL: this.config.DPDB_URL,
  42256. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  42257. K_FILTER: this.config.K_FILTER,
  42258. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  42259. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  42260. YAW_ONLY: this.config.YAW_ONLY,
  42261. BUFFER_SCALE: this.config.BUFFER_SCALE,
  42262. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  42263. });
  42264. this.polyfillDisplays.push(vrDisplay);
  42265. }
  42266. this._polyfillDisplaysPopulated = true;
  42267. return this.polyfillDisplays;
  42268. };
  42269. WebVRPolyfill.prototype.enable = function () {
  42270. this.enabled = true;
  42271. if (this.hasNative && this.native.VRFrameData) {
  42272. var NativeVRFrameData = this.native.VRFrameData;
  42273. var nativeFrameData = new this.native.VRFrameData();
  42274. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  42275. window.VRDisplay.prototype.getFrameData = function (frameData) {
  42276. if (frameData instanceof NativeVRFrameData) {
  42277. nativeGetFrameData.call(this, frameData);
  42278. return;
  42279. }
  42280. nativeGetFrameData.call(this, nativeFrameData);
  42281. frameData.pose = nativeFrameData.pose;
  42282. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  42283. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  42284. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  42285. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  42286. };
  42287. }
  42288. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  42289. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  42290. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  42291. };
  42292. WebVRPolyfill.prototype.getVRDisplays = function () {
  42293. var _this = this;
  42294. var config = this.config;
  42295. if (!this.hasNative) {
  42296. return Promise.resolve(this.getPolyfillDisplays());
  42297. }
  42298. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  42299. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  42300. });
  42301. };
  42302. WebVRPolyfill.version = version;
  42303. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  42304. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  42305. var webvrPolyfill = Object.freeze({
  42306. default: WebVRPolyfill
  42307. });
  42308. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  42309. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  42310. if (!commonjsGlobal.document) {
  42311. commonjsGlobal.document = commonjsGlobal.window.document;
  42312. }
  42313. if (!commonjsGlobal.navigator) {
  42314. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  42315. }
  42316. }
  42317. var src = require$$0;
  42318. return src;
  42319. })));
  42320. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42321. },{}],68:[function(_dereq_,module,exports){
  42322. var newline = /\n/
  42323. var newlineChar = '\n'
  42324. var whitespace = /\s/
  42325. module.exports = function(text, opt) {
  42326. var lines = module.exports.lines(text, opt)
  42327. return lines.map(function(line) {
  42328. return text.substring(line.start, line.end)
  42329. }).join('\n')
  42330. }
  42331. module.exports.lines = function wordwrap(text, opt) {
  42332. opt = opt||{}
  42333. //zero width results in nothing visible
  42334. if (opt.width === 0 && opt.mode !== 'nowrap')
  42335. return []
  42336. text = text||''
  42337. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  42338. var start = Math.max(0, opt.start||0)
  42339. var end = typeof opt.end === 'number' ? opt.end : text.length
  42340. var mode = opt.mode
  42341. var measure = opt.measure || monospace
  42342. if (mode === 'pre')
  42343. return pre(measure, text, start, end, width)
  42344. else
  42345. return greedy(measure, text, start, end, width, mode)
  42346. }
  42347. function idxOf(text, chr, start, end) {
  42348. var idx = text.indexOf(chr, start)
  42349. if (idx === -1 || idx > end)
  42350. return end
  42351. return idx
  42352. }
  42353. function isWhitespace(chr) {
  42354. return whitespace.test(chr)
  42355. }
  42356. function pre(measure, text, start, end, width) {
  42357. var lines = []
  42358. var lineStart = start
  42359. for (var i=start; i<end && i<text.length; i++) {
  42360. var chr = text.charAt(i)
  42361. var isNewline = newline.test(chr)
  42362. //If we've reached a newline, then step down a line
  42363. //Or if we've reached the EOF
  42364. if (isNewline || i===end-1) {
  42365. var lineEnd = isNewline ? i : i+1
  42366. var measured = measure(text, lineStart, lineEnd, width)
  42367. lines.push(measured)
  42368. lineStart = i+1
  42369. }
  42370. }
  42371. return lines
  42372. }
  42373. function greedy(measure, text, start, end, width, mode) {
  42374. //A greedy word wrapper based on LibGDX algorithm
  42375. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  42376. var lines = []
  42377. var testWidth = width
  42378. //if 'nowrap' is specified, we only wrap on newline chars
  42379. if (mode === 'nowrap')
  42380. testWidth = Number.MAX_VALUE
  42381. while (start < end && start < text.length) {
  42382. //get next newline position
  42383. var newLine = idxOf(text, newlineChar, start, end)
  42384. //eat whitespace at start of line
  42385. while (start < newLine) {
  42386. if (!isWhitespace( text.charAt(start) ))
  42387. break
  42388. start++
  42389. }
  42390. //determine visible # of glyphs for the available width
  42391. var measured = measure(text, start, newLine, testWidth)
  42392. var lineEnd = start + (measured.end-measured.start)
  42393. var nextStart = lineEnd + newlineChar.length
  42394. //if we had to cut the line before the next newline...
  42395. if (lineEnd < newLine) {
  42396. //find char to break on
  42397. while (lineEnd > start) {
  42398. if (isWhitespace(text.charAt(lineEnd)))
  42399. break
  42400. lineEnd--
  42401. }
  42402. if (lineEnd === start) {
  42403. if (nextStart > start + newlineChar.length) nextStart--
  42404. lineEnd = nextStart // If no characters to break, show all.
  42405. } else {
  42406. nextStart = lineEnd
  42407. //eat whitespace at end of line
  42408. while (lineEnd > start) {
  42409. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  42410. break
  42411. lineEnd--
  42412. }
  42413. }
  42414. }
  42415. if (lineEnd >= start) {
  42416. var result = measure(text, start, lineEnd, testWidth)
  42417. lines.push(result)
  42418. }
  42419. start = nextStart
  42420. }
  42421. return lines
  42422. }
  42423. //determines the visible number of glyphs within a given width
  42424. function monospace(text, start, end, width) {
  42425. var glyphs = Math.min(width, end-start)
  42426. return {
  42427. start: start,
  42428. end: start+glyphs
  42429. }
  42430. }
  42431. },{}],69:[function(_dereq_,module,exports){
  42432. "use strict";
  42433. var window = _dereq_("global/window")
  42434. var isFunction = _dereq_("is-function")
  42435. var parseHeaders = _dereq_("parse-headers")
  42436. var xtend = _dereq_("xtend")
  42437. module.exports = createXHR
  42438. // Allow use of default import syntax in TypeScript
  42439. module.exports.default = createXHR;
  42440. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  42441. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  42442. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  42443. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  42444. options = initParams(uri, options, callback)
  42445. options.method = method.toUpperCase()
  42446. return _createXHR(options)
  42447. }
  42448. })
  42449. function forEachArray(array, iterator) {
  42450. for (var i = 0; i < array.length; i++) {
  42451. iterator(array[i])
  42452. }
  42453. }
  42454. function isEmpty(obj){
  42455. for(var i in obj){
  42456. if(obj.hasOwnProperty(i)) return false
  42457. }
  42458. return true
  42459. }
  42460. function initParams(uri, options, callback) {
  42461. var params = uri
  42462. if (isFunction(options)) {
  42463. callback = options
  42464. if (typeof uri === "string") {
  42465. params = {uri:uri}
  42466. }
  42467. } else {
  42468. params = xtend(options, {uri: uri})
  42469. }
  42470. params.callback = callback
  42471. return params
  42472. }
  42473. function createXHR(uri, options, callback) {
  42474. options = initParams(uri, options, callback)
  42475. return _createXHR(options)
  42476. }
  42477. function _createXHR(options) {
  42478. if(typeof options.callback === "undefined"){
  42479. throw new Error("callback argument missing")
  42480. }
  42481. var called = false
  42482. var callback = function cbOnce(err, response, body){
  42483. if(!called){
  42484. called = true
  42485. options.callback(err, response, body)
  42486. }
  42487. }
  42488. function readystatechange() {
  42489. if (xhr.readyState === 4) {
  42490. setTimeout(loadFunc, 0)
  42491. }
  42492. }
  42493. function getBody() {
  42494. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  42495. var body = undefined
  42496. if (xhr.response) {
  42497. body = xhr.response
  42498. } else {
  42499. body = xhr.responseText || getXml(xhr)
  42500. }
  42501. if (isJson) {
  42502. try {
  42503. body = JSON.parse(body)
  42504. } catch (e) {}
  42505. }
  42506. return body
  42507. }
  42508. function errorFunc(evt) {
  42509. clearTimeout(timeoutTimer)
  42510. if(!(evt instanceof Error)){
  42511. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  42512. }
  42513. evt.statusCode = 0
  42514. return callback(evt, failureResponse)
  42515. }
  42516. // will load the data & process the response in a special response object
  42517. function loadFunc() {
  42518. if (aborted) return
  42519. var status
  42520. clearTimeout(timeoutTimer)
  42521. if(options.useXDR && xhr.status===undefined) {
  42522. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  42523. status = 200
  42524. } else {
  42525. status = (xhr.status === 1223 ? 204 : xhr.status)
  42526. }
  42527. var response = failureResponse
  42528. var err = null
  42529. if (status !== 0){
  42530. response = {
  42531. body: getBody(),
  42532. statusCode: status,
  42533. method: method,
  42534. headers: {},
  42535. url: uri,
  42536. rawRequest: xhr
  42537. }
  42538. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  42539. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  42540. }
  42541. } else {
  42542. err = new Error("Internal XMLHttpRequest Error")
  42543. }
  42544. return callback(err, response, response.body)
  42545. }
  42546. var xhr = options.xhr || null
  42547. if (!xhr) {
  42548. if (options.cors || options.useXDR) {
  42549. xhr = new createXHR.XDomainRequest()
  42550. }else{
  42551. xhr = new createXHR.XMLHttpRequest()
  42552. }
  42553. }
  42554. var key
  42555. var aborted
  42556. var uri = xhr.url = options.uri || options.url
  42557. var method = xhr.method = options.method || "GET"
  42558. var body = options.body || options.data
  42559. var headers = xhr.headers = options.headers || {}
  42560. var sync = !!options.sync
  42561. var isJson = false
  42562. var timeoutTimer
  42563. var failureResponse = {
  42564. body: undefined,
  42565. headers: {},
  42566. statusCode: 0,
  42567. method: method,
  42568. url: uri,
  42569. rawRequest: xhr
  42570. }
  42571. if ("json" in options && options.json !== false) {
  42572. isJson = true
  42573. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  42574. if (method !== "GET" && method !== "HEAD") {
  42575. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  42576. body = JSON.stringify(options.json === true ? body : options.json)
  42577. }
  42578. }
  42579. xhr.onreadystatechange = readystatechange
  42580. xhr.onload = loadFunc
  42581. xhr.onerror = errorFunc
  42582. // IE9 must have onprogress be set to a unique function.
  42583. xhr.onprogress = function () {
  42584. // IE must die
  42585. }
  42586. xhr.onabort = function(){
  42587. aborted = true;
  42588. }
  42589. xhr.ontimeout = errorFunc
  42590. xhr.open(method, uri, !sync, options.username, options.password)
  42591. //has to be after open
  42592. if(!sync) {
  42593. xhr.withCredentials = !!options.withCredentials
  42594. }
  42595. // Cannot set timeout with sync request
  42596. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  42597. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  42598. if (!sync && options.timeout > 0 ) {
  42599. timeoutTimer = setTimeout(function(){
  42600. if (aborted) return
  42601. aborted = true//IE9 may still call readystatechange
  42602. xhr.abort("timeout")
  42603. var e = new Error("XMLHttpRequest timeout")
  42604. e.code = "ETIMEDOUT"
  42605. errorFunc(e)
  42606. }, options.timeout )
  42607. }
  42608. if (xhr.setRequestHeader) {
  42609. for(key in headers){
  42610. if(headers.hasOwnProperty(key)){
  42611. xhr.setRequestHeader(key, headers[key])
  42612. }
  42613. }
  42614. } else if (options.headers && !isEmpty(options.headers)) {
  42615. throw new Error("Headers cannot be set on an XDomainRequest object")
  42616. }
  42617. if ("responseType" in options) {
  42618. xhr.responseType = options.responseType
  42619. }
  42620. if ("beforeSend" in options &&
  42621. typeof options.beforeSend === "function"
  42622. ) {
  42623. options.beforeSend(xhr)
  42624. }
  42625. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  42626. // XMLHttpRequest spec says to pass null as body to indicate no body
  42627. // See https://github.com/naugtur/xhr/issues/100.
  42628. xhr.send(body || null)
  42629. return xhr
  42630. }
  42631. function getXml(xhr) {
  42632. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  42633. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  42634. try {
  42635. if (xhr.responseType === "document") {
  42636. return xhr.responseXML
  42637. }
  42638. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  42639. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  42640. return xhr.responseXML
  42641. }
  42642. } catch (e) {}
  42643. return null
  42644. }
  42645. function noop() {}
  42646. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":71}],70:[function(_dereq_,module,exports){
  42647. module.exports = (function xmlparser() {
  42648. //common browsers
  42649. if (typeof self.DOMParser !== 'undefined') {
  42650. return function(str) {
  42651. var parser = new self.DOMParser()
  42652. return parser.parseFromString(str, 'application/xml')
  42653. }
  42654. }
  42655. //IE8 fallback
  42656. if (typeof self.ActiveXObject !== 'undefined'
  42657. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  42658. return function(str) {
  42659. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  42660. xmlDoc.async = "false"
  42661. xmlDoc.loadXML(str)
  42662. return xmlDoc
  42663. }
  42664. }
  42665. //last resort fallback
  42666. return function(str) {
  42667. var div = document.createElement('div')
  42668. div.innerHTML = str
  42669. return div
  42670. }
  42671. })()
  42672. },{}],71:[function(_dereq_,module,exports){
  42673. module.exports = extend
  42674. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42675. function extend() {
  42676. var target = {}
  42677. for (var i = 0; i < arguments.length; i++) {
  42678. var source = arguments[i]
  42679. for (var key in source) {
  42680. if (hasOwnProperty.call(source, key)) {
  42681. target[key] = source[key]
  42682. }
  42683. }
  42684. }
  42685. return target
  42686. }
  42687. },{}],72:[function(_dereq_,module,exports){
  42688. module.exports={
  42689. "name": "aframe",
  42690. "version": "0.9.2",
  42691. "description": "A web framework for building virtual reality experiences.",
  42692. "homepage": "https://aframe.io/",
  42693. "main": "dist/aframe-master.js",
  42694. "scripts": {
  42695. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  42696. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  42697. "codecov": "codecov",
  42698. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  42699. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  42700. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  42701. "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",
  42702. "docs": "markserv --dir docs --port 9001",
  42703. "preghpages": "node ./scripts/preghpages.js",
  42704. "ghpages": "ghpages -p gh-pages/",
  42705. "lint": "semistandard -v | snazzy",
  42706. "lint:fix": "semistandard --fix",
  42707. "precommit": "npm run lint",
  42708. "prepush": "node scripts/testOnlyCheck.js",
  42709. "prerelease": "node scripts/release.js 0.9.1 0.9.2",
  42710. "start": "npm run dev",
  42711. "start:https": "cross-env SSL=true npm run dev",
  42712. "test": "karma start ./tests/karma.conf.js",
  42713. "test:docs": "node scripts/docsLint.js",
  42714. "test:firefox": "npm test -- --browsers Firefox",
  42715. "test:chrome": "npm test -- --browsers Chrome",
  42716. "test:nobrowser": "NO_BROWSER=true npm test",
  42717. "test:node": "mocha --ui tdd tests/node"
  42718. },
  42719. "repository": "aframevr/aframe",
  42720. "license": "MIT",
  42721. "files": [
  42722. "dist/*",
  42723. "docs/**/*",
  42724. "src/**/*",
  42725. "vendor/**/*"
  42726. ],
  42727. "dependencies": {
  42728. "custom-event-polyfill": "^1.0.6",
  42729. "debug": "ngokevin/debug#noTimestamp",
  42730. "deep-assign": "^2.0.0",
  42731. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  42732. "load-bmfont": "^1.2.3",
  42733. "object-assign": "^4.0.1",
  42734. "present": "0.0.6",
  42735. "promise-polyfill": "^3.1.0",
  42736. "super-animejs": "^3.1.0",
  42737. "super-three": "^0.108.0",
  42738. "three-bmfont-text": "^2.1.0",
  42739. "webvr-polyfill": "^0.10.10"
  42740. },
  42741. "devDependencies": {
  42742. "browserify": "^13.1.0",
  42743. "browserify-css": "^0.8.4",
  42744. "browserify-derequire": "^0.9.4",
  42745. "browserify-istanbul": "^2.0.0",
  42746. "budo": "^9.2.0",
  42747. "chai": "^3.5.0",
  42748. "chai-shallow-deep-equal": "^1.4.0",
  42749. "chalk": "^1.1.3",
  42750. "codecov": "^1.0.1",
  42751. "cross-env": "^5.0.1",
  42752. "envify": "^3.4.1",
  42753. "exorcist": "^0.4.0",
  42754. "ghpages": "0.0.8",
  42755. "git-rev": "^0.2.1",
  42756. "glob": "^7.1.1",
  42757. "husky": "^0.11.7",
  42758. "istanbul": "^0.4.5",
  42759. "jsdom": "^9.11.0",
  42760. "karma": "1.4.1",
  42761. "karma-browserify": "^5.1.0",
  42762. "karma-chai-shallow-deep-equal": "0.0.4",
  42763. "karma-chrome-launcher": "^2.0.0",
  42764. "karma-coverage": "^1.1.1",
  42765. "karma-env-preprocessor": "^0.1.1",
  42766. "karma-firefox-launcher": "^1.0.0",
  42767. "karma-mocha": "^1.1.1",
  42768. "karma-mocha-reporter": "^2.1.0",
  42769. "karma-sinon-chai": "1.2.4",
  42770. "lolex": "^1.5.1",
  42771. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  42772. "minifyify": "^7.3.3",
  42773. "mocha": "^3.0.2",
  42774. "mozilla-download": "^1.1.1",
  42775. "replace-in-file": "^2.5.3",
  42776. "semistandard": "^9.0.0",
  42777. "shelljs": "^0.7.7",
  42778. "shx": "^0.2.2",
  42779. "sinon": "^1.17.5",
  42780. "sinon-chai": "2.8.0",
  42781. "snazzy": "^5.0.0",
  42782. "too-wordy": "ngokevin/too-wordy",
  42783. "uglifyjs": "^2.4.10",
  42784. "write-good": "^0.9.1"
  42785. },
  42786. "link": true,
  42787. "browserify": {
  42788. "transform": [
  42789. "browserify-css",
  42790. "envify"
  42791. ]
  42792. },
  42793. "semistandard": {
  42794. "ignore": [
  42795. "build/**",
  42796. "dist/**",
  42797. "examples/**/shaders/*.js",
  42798. "**/vendor/**"
  42799. ]
  42800. },
  42801. "keywords": [
  42802. "3d",
  42803. "aframe",
  42804. "cardboard",
  42805. "components",
  42806. "oculus",
  42807. "three",
  42808. "three.js",
  42809. "rift",
  42810. "vive",
  42811. "vr",
  42812. "web-components",
  42813. "webvr"
  42814. ],
  42815. "browserify-css": {
  42816. "minify": true
  42817. },
  42818. "engines": {
  42819. "node": ">= 4.6.0",
  42820. "npm": "^2.15.9"
  42821. }
  42822. }
  42823. },{}],73:[function(_dereq_,module,exports){
  42824. var anime = _dereq_('super-animejs');
  42825. var components = _dereq_('../core/component').components;
  42826. var registerComponent = _dereq_('../core/component').registerComponent;
  42827. var THREE = _dereq_('../lib/three');
  42828. var utils = _dereq_('../utils');
  42829. var colorHelperFrom = new THREE.Color();
  42830. var colorHelperTo = new THREE.Color();
  42831. var getComponentProperty = utils.entity.getComponentProperty;
  42832. var setComponentProperty = utils.entity.setComponentProperty;
  42833. var splitCache = {};
  42834. var TYPE_COLOR = 'color';
  42835. var PROP_POSITION = 'position';
  42836. var PROP_ROTATION = 'rotation';
  42837. var PROP_SCALE = 'scale';
  42838. var STRING_COMPONENTS = 'components';
  42839. var STRING_OBJECT3D = 'object3D';
  42840. /**
  42841. * Animation component for A-Frame using anime.js.
  42842. *
  42843. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  42844. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  42845. * boolean * flag * `isAnimationPlaying`.
  42846. *
  42847. * anime.js animation config for tweenining Javascript objects and values works as:
  42848. *
  42849. * config = {
  42850. * targets: {foo: 0.0, bar: '#000'},
  42851. * foo: 1.0,
  42852. * bar: '#FFF'
  42853. * }
  42854. *
  42855. * The above will tween each property in `targets`. The `to` values are set in the root of
  42856. * the config.
  42857. *
  42858. * @member {object} animation - anime.js instance.
  42859. * @member {boolean} animationIsPlaying - Control if animation is playing.
  42860. */
  42861. module.exports.Component = registerComponent('animation', {
  42862. schema: {
  42863. autoplay: {default: true},
  42864. delay: {default: 0},
  42865. dir: {default: ''},
  42866. dur: {default: 1000},
  42867. easing: {default: 'easeInQuad'},
  42868. elasticity: {default: 400},
  42869. enabled: {default: true},
  42870. from: {default: ''},
  42871. loop: {
  42872. default: 0,
  42873. parse: function (value) {
  42874. // Boolean or integer.
  42875. if (value === true || value === 'true') { return true; }
  42876. if (value === false || value === 'false') { return false; }
  42877. return parseInt(value, 10);
  42878. }
  42879. },
  42880. property: {default: ''},
  42881. startEvents: {type: 'array'},
  42882. pauseEvents: {type: 'array'},
  42883. resumeEvents: {type: 'array'},
  42884. round: {default: false},
  42885. to: {default: ''},
  42886. type: {default: ''},
  42887. isRawProperty: {default: false}
  42888. },
  42889. multiple: true,
  42890. init: function () {
  42891. var self = this;
  42892. this.eventDetail = {name: this.attrName};
  42893. this.time = 0;
  42894. this.animation = null;
  42895. this.animationIsPlaying = false;
  42896. this.onStartEvent = this.onStartEvent.bind(this);
  42897. this.beginAnimation = this.beginAnimation.bind(this);
  42898. this.pauseAnimation = this.pauseAnimation.bind(this);
  42899. this.resumeAnimation = this.resumeAnimation.bind(this);
  42900. this.fromColor = {};
  42901. this.toColor = {};
  42902. this.targets = {};
  42903. this.targetsArray = [];
  42904. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  42905. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  42906. this.config = {
  42907. complete: function () {
  42908. self.animationIsPlaying = false;
  42909. self.el.emit('animationcomplete', self.eventDetail, false);
  42910. if (self.id) {
  42911. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  42912. }
  42913. }
  42914. };
  42915. },
  42916. update: function (oldData) {
  42917. var config = this.config;
  42918. var data = this.data;
  42919. this.animationIsPlaying = false;
  42920. if (!this.data.enabled) { return; }
  42921. if (!data.property) { return; }
  42922. // Base config.
  42923. config.autoplay = false;
  42924. config.direction = data.dir;
  42925. config.duration = data.dur;
  42926. config.easing = data.easing;
  42927. config.elasticity = data.elasticity;
  42928. config.loop = data.loop;
  42929. config.round = data.round;
  42930. // Start new animation.
  42931. this.createAndStartAnimation();
  42932. },
  42933. tick: function (t, dt) {
  42934. if (!this.animationIsPlaying) { return; }
  42935. this.time += dt;
  42936. this.animation.tick(this.time);
  42937. },
  42938. remove: function () {
  42939. this.pauseAnimation();
  42940. this.removeEventListeners();
  42941. },
  42942. pause: function () {
  42943. this.paused = true;
  42944. this.pausedWasPlaying = this.animationIsPlaying;
  42945. this.pauseAnimation();
  42946. this.removeEventListeners();
  42947. },
  42948. /**
  42949. * `play` handler only for resuming scene.
  42950. */
  42951. play: function () {
  42952. if (!this.paused) { return; }
  42953. this.paused = false;
  42954. this.addEventListeners();
  42955. if (this.pausedWasPlaying) {
  42956. this.resumeAnimation();
  42957. this.pausedWasPlaying = false;
  42958. }
  42959. },
  42960. /**
  42961. * Start animation from scratch.
  42962. */
  42963. createAndStartAnimation: function () {
  42964. var data = this.data;
  42965. this.updateConfig();
  42966. this.animationIsPlaying = false;
  42967. this.animation = anime(this.config);
  42968. this.animation.began = true;
  42969. this.removeEventListeners();
  42970. this.addEventListeners();
  42971. // Wait for start events for animation.
  42972. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  42973. // Delay animation.
  42974. if (data.delay) {
  42975. setTimeout(this.beginAnimation, data.delay);
  42976. return;
  42977. }
  42978. // Play animation.
  42979. this.beginAnimation();
  42980. },
  42981. /**
  42982. * This is before animation start (including from startEvents).
  42983. * Set to initial state (config.from, time = 0, seekTime = 0).
  42984. */
  42985. beginAnimation: function () {
  42986. this.updateConfig();
  42987. this.animation.began = true;
  42988. this.time = 0;
  42989. this.animationIsPlaying = true;
  42990. this.stopRelatedAnimations();
  42991. this.el.emit('animationbegin', this.eventDetail, false);
  42992. },
  42993. pauseAnimation: function () {
  42994. this.animationIsPlaying = false;
  42995. },
  42996. resumeAnimation: function () {
  42997. this.animationIsPlaying = true;
  42998. },
  42999. /**
  43000. * startEvents callback.
  43001. */
  43002. onStartEvent: function () {
  43003. if (!this.data.enabled) { return; }
  43004. this.updateConfig();
  43005. if (this.animation) {
  43006. this.animation.pause();
  43007. }
  43008. this.animation = anime(this.config);
  43009. // Include the delay before each start event.
  43010. if (this.data.delay) {
  43011. setTimeout(this.beginAnimation, this.data.delay);
  43012. return;
  43013. }
  43014. this.beginAnimation();
  43015. },
  43016. /**
  43017. * rawProperty: true and type: color;
  43018. */
  43019. updateConfigForRawColor: function () {
  43020. var config = this.config;
  43021. var data = this.data;
  43022. var el = this.el;
  43023. var from;
  43024. var key;
  43025. var to;
  43026. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  43027. return;
  43028. }
  43029. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  43030. to = data.to;
  43031. // Use r/g/b vector for color type.
  43032. this.setColorConfig(from, to);
  43033. from = this.fromColor;
  43034. to = this.toColor;
  43035. this.targetsArray.length = 0;
  43036. this.targetsArray.push(from);
  43037. config.targets = this.targetsArray;
  43038. for (key in to) { config[key] = to[key]; }
  43039. config.update = (function () {
  43040. var lastValue = {};
  43041. return function (anim) {
  43042. var value;
  43043. value = anim.animatables[0].target;
  43044. // For animation timeline.
  43045. if (value.r === lastValue.r &&
  43046. value.g === lastValue.g &&
  43047. value.b === lastValue.b) { return; }
  43048. setRawProperty(el, data.property, value, data.type);
  43049. };
  43050. })();
  43051. },
  43052. /**
  43053. * Stuff property into generic `property` key.
  43054. */
  43055. updateConfigForDefault: function () {
  43056. var config = this.config;
  43057. var data = this.data;
  43058. var el = this.el;
  43059. var from;
  43060. var isBoolean;
  43061. var isNumber;
  43062. var to;
  43063. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  43064. return;
  43065. }
  43066. if (data.from === '') {
  43067. // Infer from.
  43068. from = isRawProperty(data)
  43069. ? getRawProperty(el, data.property)
  43070. : getComponentProperty(el, data.property);
  43071. } else {
  43072. // Explicit from.
  43073. from = data.from;
  43074. }
  43075. to = data.to;
  43076. isNumber = !isNaN(from || to);
  43077. if (isNumber) {
  43078. from = parseFloat(from);
  43079. to = parseFloat(to);
  43080. } else {
  43081. from = from ? from.toString() : from;
  43082. to = to ? to.toString() : to;
  43083. }
  43084. // Convert booleans to integer to allow boolean flipping.
  43085. isBoolean = data.to === 'true' || data.to === 'false' ||
  43086. data.to === true || data.to === false;
  43087. if (isBoolean) {
  43088. from = data.from === 'true' || data.from === true ? 1 : 0;
  43089. to = data.to === 'true' || data.to === true ? 1 : 0;
  43090. }
  43091. this.targets.aframeProperty = from;
  43092. config.targets = this.targets;
  43093. config.aframeProperty = to;
  43094. config.update = (function () {
  43095. var lastValue;
  43096. return function (anim) {
  43097. var value;
  43098. value = anim.animatables[0].target.aframeProperty;
  43099. // Need to do a last value check for animation timeline since all the tweening
  43100. // begins simultaenously even if the value has not changed. Also better for perf
  43101. // anyways.
  43102. if (value === lastValue) { return; }
  43103. lastValue = value;
  43104. if (isBoolean) { value = value >= 1; }
  43105. if (isRawProperty(data)) {
  43106. setRawProperty(el, data.property, value, data.type);
  43107. } else {
  43108. setComponentProperty(el, data.property, value);
  43109. }
  43110. };
  43111. })();
  43112. },
  43113. /**
  43114. * Extend x/y/z/w onto the config.
  43115. * Update vector by modifying object3D.
  43116. */
  43117. updateConfigForVector: function () {
  43118. var config = this.config;
  43119. var data = this.data;
  43120. var el = this.el;
  43121. var key;
  43122. var from;
  43123. var to;
  43124. // Parse coordinates.
  43125. from = data.from !== ''
  43126. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  43127. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  43128. to = utils.coordinates.parse(data.to);
  43129. if (data.property === PROP_ROTATION) {
  43130. toRadians(from);
  43131. toRadians(to);
  43132. }
  43133. // Set to and from.
  43134. this.targetsArray.length = 0;
  43135. this.targetsArray.push(from);
  43136. config.targets = this.targetsArray;
  43137. for (key in to) { config[key] = to[key]; }
  43138. // If animating object3D transformation, run more optimized updater.
  43139. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  43140. data.property === PROP_SCALE) {
  43141. config.update = (function () {
  43142. var lastValue = {};
  43143. return function (anim) {
  43144. var value = anim.animatables[0].target;
  43145. if (data.property === PROP_SCALE) {
  43146. value.x = Math.max(0.0001, value.x);
  43147. value.y = Math.max(0.0001, value.y);
  43148. value.z = Math.max(0.0001, value.z);
  43149. }
  43150. // For animation timeline.
  43151. if (value.x === lastValue.x &&
  43152. value.y === lastValue.y &&
  43153. value.z === lastValue.z) { return; }
  43154. lastValue.x = value.x;
  43155. lastValue.y = value.y;
  43156. lastValue.z = value.z;
  43157. el.object3D[data.property].set(value.x, value.y, value.z);
  43158. };
  43159. })();
  43160. return;
  43161. }
  43162. // Animating some vector.
  43163. config.update = (function () {
  43164. var lastValue = {};
  43165. return function (anim) {
  43166. var value = anim.animatables[0].target;
  43167. // Animate rotation through radians.
  43168. // For animation timeline.
  43169. if (value.x === lastValue.x &&
  43170. value.y === lastValue.y &&
  43171. value.z === lastValue.z) { return; }
  43172. lastValue.x = value.x;
  43173. lastValue.y = value.y;
  43174. lastValue.z = value.z;
  43175. setComponentProperty(el, data.property, value);
  43176. };
  43177. })();
  43178. },
  43179. /**
  43180. * Update the config before each run.
  43181. */
  43182. updateConfig: function () {
  43183. var propType;
  43184. // Route config type.
  43185. propType = getPropertyType(this.el, this.data.property);
  43186. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  43187. this.updateConfigForRawColor();
  43188. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  43189. this.updateConfigForVector();
  43190. } else {
  43191. this.updateConfigForDefault();
  43192. }
  43193. },
  43194. /**
  43195. * Wait for component to initialize.
  43196. */
  43197. waitComponentInitRawProperty: function (cb) {
  43198. var componentName;
  43199. var data = this.data;
  43200. var el = this.el;
  43201. var self = this;
  43202. if (data.from !== '') { return false; }
  43203. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  43204. componentName = splitDot(data.property)[1];
  43205. if (el.components[componentName]) { return false; }
  43206. el.addEventListener('componentinitialized', function wait (evt) {
  43207. if (evt.detail.name !== componentName) { return; }
  43208. cb();
  43209. // Since the config was created async, create the animation now since we missed it
  43210. // earlier.
  43211. self.animation = anime(self.config);
  43212. el.removeEventListener('componentinitialized', wait);
  43213. });
  43214. return true;
  43215. },
  43216. /**
  43217. * Make sure two animations on the same property don't fight each other.
  43218. * e.g., animation__mouseenter="property: material.opacity"
  43219. * animation__mouseleave="property: material.opacity"
  43220. */
  43221. stopRelatedAnimations: function () {
  43222. var component;
  43223. var componentName;
  43224. for (componentName in this.el.components) {
  43225. component = this.el.components[componentName];
  43226. if (componentName === this.attrName) { continue; }
  43227. if (component.name !== 'animation') { continue; }
  43228. if (!component.animationIsPlaying) { continue; }
  43229. if (component.data.property !== this.data.property) { continue; }
  43230. component.animationIsPlaying = false;
  43231. }
  43232. },
  43233. addEventListeners: function () {
  43234. var data = this.data;
  43235. var el = this.el;
  43236. addEventListeners(el, data.startEvents, this.onStartEvent);
  43237. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  43238. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  43239. },
  43240. removeEventListeners: function () {
  43241. var data = this.data;
  43242. var el = this.el;
  43243. removeEventListeners(el, data.startEvents, this.onStartEvent);
  43244. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  43245. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  43246. },
  43247. setColorConfig: function (from, to) {
  43248. colorHelperFrom.set(from);
  43249. colorHelperTo.set(to);
  43250. from = this.fromColor;
  43251. to = this.toColor;
  43252. from.r = colorHelperFrom.r;
  43253. from.g = colorHelperFrom.g;
  43254. from.b = colorHelperFrom.b;
  43255. to.r = colorHelperTo.r;
  43256. to.g = colorHelperTo.g;
  43257. to.b = colorHelperTo.b;
  43258. }
  43259. });
  43260. /**
  43261. * Given property name, check schema to see what type we are animating.
  43262. * We just care whether the property is a vector.
  43263. */
  43264. function getPropertyType (el, property) {
  43265. var component;
  43266. var componentName;
  43267. var split;
  43268. var propertyName;
  43269. split = property.split('.');
  43270. componentName = split[0];
  43271. propertyName = split[1];
  43272. component = el.components[componentName] || components[componentName];
  43273. // Primitives.
  43274. if (!component) { return null; }
  43275. // Dynamic schema. We only care about vectors anyways.
  43276. if (propertyName && !component.schema[propertyName]) { return null; }
  43277. // Multi-prop.
  43278. if (propertyName) { return component.schema[propertyName].type; }
  43279. // Single-prop.
  43280. return component.schema.type;
  43281. }
  43282. /**
  43283. * Convert object to radians.
  43284. */
  43285. function toRadians (obj) {
  43286. obj.x = THREE.Math.degToRad(obj.x);
  43287. obj.y = THREE.Math.degToRad(obj.y);
  43288. obj.z = THREE.Math.degToRad(obj.z);
  43289. }
  43290. function addEventListeners (el, eventNames, handler) {
  43291. var i;
  43292. for (i = 0; i < eventNames.length; i++) {
  43293. el.addEventListener(eventNames[i], handler);
  43294. }
  43295. }
  43296. function removeEventListeners (el, eventNames, handler) {
  43297. var i;
  43298. for (i = 0; i < eventNames.length; i++) {
  43299. el.removeEventListener(eventNames[i], handler);
  43300. }
  43301. }
  43302. function getRawProperty (el, path) {
  43303. var i;
  43304. var split;
  43305. var value;
  43306. split = splitDot(path);
  43307. value = el;
  43308. for (i = 0; i < split.length; i++) {
  43309. value = value[split[i]];
  43310. }
  43311. if (value === undefined) {
  43312. console.log(el);
  43313. throw new Error('[animation] property (' + path + ') could not be found');
  43314. }
  43315. return value;
  43316. }
  43317. function setRawProperty (el, path, value, type) {
  43318. var i;
  43319. var split;
  43320. var propertyName;
  43321. var targetValue;
  43322. if (path.startsWith('object3D.rotation')) {
  43323. value = THREE.Math.degToRad(value);
  43324. }
  43325. // Walk.
  43326. split = splitDot(path);
  43327. targetValue = el;
  43328. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  43329. propertyName = split[split.length - 1];
  43330. // Raw color.
  43331. if (type === TYPE_COLOR) {
  43332. if ('r' in targetValue[propertyName]) {
  43333. targetValue[propertyName].r = value.r;
  43334. targetValue[propertyName].g = value.g;
  43335. targetValue[propertyName].b = value.b;
  43336. } else {
  43337. targetValue[propertyName].x = value.r;
  43338. targetValue[propertyName].y = value.g;
  43339. targetValue[propertyName].z = value.b;
  43340. }
  43341. return;
  43342. }
  43343. targetValue[propertyName] = value;
  43344. }
  43345. function splitDot (path) {
  43346. if (path in splitCache) { return splitCache[path]; }
  43347. splitCache[path] = path.split('.');
  43348. return splitCache[path];
  43349. }
  43350. function isRawProperty (data) {
  43351. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  43352. data.property.startsWith(STRING_OBJECT3D);
  43353. }
  43354. },{"../core/component":124,"../lib/three":172,"../utils":197,"super-animejs":56}],74:[function(_dereq_,module,exports){
  43355. var registerComponent = _dereq_('../core/component').registerComponent;
  43356. var THREE = _dereq_('../lib/three');
  43357. /**
  43358. * Camera component.
  43359. * Pairs along with camera system to handle tracking the active camera.
  43360. */
  43361. module.exports.Component = registerComponent('camera', {
  43362. schema: {
  43363. active: {default: true},
  43364. far: {default: 10000},
  43365. fov: {default: 80, min: 0},
  43366. near: {default: 0.005, min: 0},
  43367. spectator: {default: false},
  43368. zoom: {default: 1, min: 0}
  43369. },
  43370. /**
  43371. * Initialize three.js camera and add it to the entity.
  43372. * Add reference from scene to this entity as the camera.
  43373. */
  43374. init: function () {
  43375. var camera;
  43376. var el = this.el;
  43377. // Create camera.
  43378. camera = this.camera = new THREE.PerspectiveCamera();
  43379. el.setObject3D('camera', camera);
  43380. },
  43381. /**
  43382. * Update three.js camera.
  43383. */
  43384. update: function (oldData) {
  43385. var data = this.data;
  43386. var camera = this.camera;
  43387. // Update properties.
  43388. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  43389. camera.far = data.far;
  43390. camera.fov = data.fov;
  43391. camera.near = data.near;
  43392. camera.zoom = data.zoom;
  43393. camera.updateProjectionMatrix();
  43394. this.updateActiveCamera(oldData);
  43395. this.updateSpectatorCamera(oldData);
  43396. },
  43397. updateActiveCamera: function (oldData) {
  43398. var data = this.data;
  43399. var el = this.el;
  43400. var system = this.system;
  43401. // Active property did not change.
  43402. if (oldData && oldData.active === data.active || data.spectator) { return; }
  43403. // If `active` property changes, or first update, handle active camera with system.
  43404. if (data.active && system.activeCameraEl !== el) {
  43405. // Camera enabled. Set camera to this camera.
  43406. system.setActiveCamera(el);
  43407. } else if (!data.active && system.activeCameraEl === el) {
  43408. // Camera disabled. Set camera to another camera.
  43409. system.disableActiveCamera();
  43410. }
  43411. },
  43412. updateSpectatorCamera: function (oldData) {
  43413. var data = this.data;
  43414. var el = this.el;
  43415. var system = this.system;
  43416. // spectator property did not change.
  43417. if (oldData && oldData.spectator === data.spectator) { return; }
  43418. // If `spectator` property changes, or first update, handle spectator camera with system.
  43419. if (data.spectator && system.spectatorCameraEl !== el) {
  43420. // Camera enabled. Set camera to this camera.
  43421. system.setSpectatorCamera(el);
  43422. } else if (!data.spectator && system.spectatorCameraEl === el) {
  43423. // Camera disabled. Set camera to another camera.
  43424. system.disableSpectatorCamera();
  43425. }
  43426. },
  43427. /**
  43428. * Remove camera on remove (callback).
  43429. */
  43430. remove: function () {
  43431. this.el.removeObject3D('camera');
  43432. }
  43433. });
  43434. },{"../core/component":124,"../lib/three":172}],75:[function(_dereq_,module,exports){
  43435. /* global THREE */
  43436. var registerComponent = _dereq_('../core/component').registerComponent;
  43437. var utils = _dereq_('../utils/');
  43438. var bind = utils.bind;
  43439. var EVENTS = {
  43440. CLICK: 'click',
  43441. FUSING: 'fusing',
  43442. MOUSEENTER: 'mouseenter',
  43443. MOUSEDOWN: 'mousedown',
  43444. MOUSELEAVE: 'mouseleave',
  43445. MOUSEUP: 'mouseup'
  43446. };
  43447. var STATES = {
  43448. FUSING: 'cursor-fusing',
  43449. HOVERING: 'cursor-hovering',
  43450. HOVERED: 'cursor-hovered'
  43451. };
  43452. var CANVAS_EVENTS = {
  43453. DOWN: ['mousedown', 'touchstart'],
  43454. UP: ['mouseup', 'touchend']
  43455. };
  43456. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  43457. /**
  43458. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  43459. * from the camera and pointing from camera's facing direction, and then only returning the
  43460. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  43461. *
  43462. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  43463. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  43464. * @member {object} intersection - Attributes of the current intersection event, including
  43465. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  43466. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  43467. * emit events when unintersecting.
  43468. */
  43469. module.exports.Component = registerComponent('cursor', {
  43470. dependencies: ['raycaster'],
  43471. schema: {
  43472. downEvents: {default: []},
  43473. fuse: {default: utils.device.isMobile()},
  43474. fuseTimeout: {default: 1500, min: 0},
  43475. mouseCursorStylesEnabled: {default: true},
  43476. upEvents: {default: []},
  43477. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  43478. },
  43479. init: function () {
  43480. var self = this;
  43481. this.fuseTimeout = undefined;
  43482. this.cursorDownEl = null;
  43483. this.intersectedEl = null;
  43484. this.canvasBounds = document.body.getBoundingClientRect();
  43485. this.isCursorDown = false;
  43486. // Debounce.
  43487. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  43488. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  43489. }, 500);
  43490. this.eventDetail = {};
  43491. this.intersectedEventDetail = {cursorEl: this.el};
  43492. // Bind methods.
  43493. this.onCursorDown = bind(this.onCursorDown, this);
  43494. this.onCursorUp = bind(this.onCursorUp, this);
  43495. this.onIntersection = bind(this.onIntersection, this);
  43496. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  43497. this.onMouseMove = bind(this.onMouseMove, this);
  43498. },
  43499. update: function (oldData) {
  43500. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  43501. this.updateMouseEventListeners();
  43502. },
  43503. play: function () {
  43504. this.addEventListeners();
  43505. },
  43506. pause: function () {
  43507. this.removeEventListeners();
  43508. },
  43509. remove: function () {
  43510. var el = this.el;
  43511. el.removeState(STATES.HOVERING);
  43512. el.removeState(STATES.FUSING);
  43513. clearTimeout(this.fuseTimeout);
  43514. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  43515. this.removeEventListeners();
  43516. },
  43517. addEventListeners: function () {
  43518. var canvas;
  43519. var data = this.data;
  43520. var el = this.el;
  43521. var self = this;
  43522. function addCanvasListeners () {
  43523. canvas = el.sceneEl.canvas;
  43524. if (data.downEvents.length || data.upEvents.length) { return; }
  43525. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43526. canvas.addEventListener(downEvent, self.onCursorDown);
  43527. });
  43528. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43529. canvas.addEventListener(upEvent, self.onCursorUp);
  43530. });
  43531. }
  43532. canvas = el.sceneEl.canvas;
  43533. if (canvas) {
  43534. addCanvasListeners();
  43535. } else {
  43536. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  43537. }
  43538. data.downEvents.forEach(function (downEvent) {
  43539. el.addEventListener(downEvent, self.onCursorDown);
  43540. });
  43541. data.upEvents.forEach(function (upEvent) {
  43542. el.addEventListener(upEvent, self.onCursorUp);
  43543. });
  43544. el.addEventListener('raycaster-intersection', this.onIntersection);
  43545. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43546. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  43547. window.addEventListener('resize', this.updateCanvasBounds);
  43548. window.addEventListener('scroll', this.updateCanvasBounds);
  43549. this.updateMouseEventListeners();
  43550. },
  43551. removeEventListeners: function () {
  43552. var canvas;
  43553. var data = this.data;
  43554. var el = this.el;
  43555. var self = this;
  43556. canvas = el.sceneEl.canvas;
  43557. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  43558. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43559. canvas.removeEventListener(downEvent, self.onCursorDown);
  43560. });
  43561. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43562. canvas.removeEventListener(upEvent, self.onCursorUp);
  43563. });
  43564. }
  43565. data.downEvents.forEach(function (downEvent) {
  43566. el.removeEventListener(downEvent, self.onCursorDown);
  43567. });
  43568. data.upEvents.forEach(function (upEvent) {
  43569. el.removeEventListener(upEvent, self.onCursorUp);
  43570. });
  43571. el.removeEventListener('raycaster-intersection', this.onIntersection);
  43572. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43573. canvas.removeEventListener('mousemove', this.onMouseMove);
  43574. canvas.removeEventListener('touchstart', this.onMouseMove);
  43575. canvas.removeEventListener('touchmove', this.onMouseMove);
  43576. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  43577. window.removeEventListener('resize', this.updateCanvasBounds);
  43578. window.removeEventListener('scroll', this.updateCanvasBounds);
  43579. },
  43580. updateMouseEventListeners: function () {
  43581. var canvas;
  43582. var el = this.el;
  43583. canvas = el.sceneEl.canvas;
  43584. canvas.removeEventListener('mousemove', this.onMouseMove);
  43585. canvas.removeEventListener('touchmove', this.onMouseMove);
  43586. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  43587. if (this.data.rayOrigin !== 'mouse') { return; }
  43588. canvas.addEventListener('mousemove', this.onMouseMove, false);
  43589. canvas.addEventListener('touchmove', this.onMouseMove, false);
  43590. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  43591. this.updateCanvasBounds();
  43592. },
  43593. onMouseMove: (function () {
  43594. var direction = new THREE.Vector3();
  43595. var mouse = new THREE.Vector2();
  43596. var origin = new THREE.Vector3();
  43597. var rayCasterConfig = {origin: origin, direction: direction};
  43598. return function (evt) {
  43599. var bounds = this.canvasBounds;
  43600. var camera = this.el.sceneEl.camera;
  43601. var left;
  43602. var point;
  43603. var top;
  43604. camera.parent.updateMatrixWorld();
  43605. // Calculate mouse position based on the canvas element
  43606. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  43607. // Track the first touch for simplicity.
  43608. point = evt.touches.item(0);
  43609. } else {
  43610. point = evt;
  43611. }
  43612. left = point.clientX - bounds.left;
  43613. top = point.clientY - bounds.top;
  43614. mouse.x = (left / bounds.width) * 2 - 1;
  43615. mouse.y = -(top / bounds.height) * 2 + 1;
  43616. origin.setFromMatrixPosition(camera.matrixWorld);
  43617. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  43618. this.el.setAttribute('raycaster', rayCasterConfig);
  43619. if (evt.type === 'touchmove') { evt.preventDefault(); }
  43620. };
  43621. })(),
  43622. /**
  43623. * Trigger mousedown and keep track of the mousedowned entity.
  43624. */
  43625. onCursorDown: function (evt) {
  43626. this.isCursorDown = true;
  43627. // Raycast again for touch.
  43628. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  43629. this.onMouseMove(evt);
  43630. this.el.components.raycaster.checkIntersections();
  43631. evt.preventDefault();
  43632. }
  43633. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43634. this.cursorDownEl = this.intersectedEl;
  43635. },
  43636. /**
  43637. * Trigger mouseup if:
  43638. * - Not fusing (mobile has no mouse).
  43639. * - Currently intersecting an entity.
  43640. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43641. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43642. */
  43643. onCursorUp: function (evt) {
  43644. if (!this.isCursorDown) { return; }
  43645. this.isCursorDown = false;
  43646. var data = this.data;
  43647. this.twoWayEmit(EVENTS.MOUSEUP);
  43648. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  43649. // previously cursorUp entity.
  43650. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  43651. this.intersectedEventDetail.intersection = null;
  43652. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  43653. }
  43654. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  43655. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  43656. this.twoWayEmit(EVENTS.CLICK);
  43657. }
  43658. this.cursorDownEl = null;
  43659. if (evt.type === 'touchend') { evt.preventDefault(); }
  43660. },
  43661. /**
  43662. * Handle intersection.
  43663. */
  43664. onIntersection: function (evt) {
  43665. var currentIntersection;
  43666. var cursorEl = this.el;
  43667. var index;
  43668. var intersectedEl;
  43669. var intersection;
  43670. // Select closest object, excluding the cursor.
  43671. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43672. intersection = evt.detail.intersections[index];
  43673. intersectedEl = evt.detail.els[index];
  43674. // If cursor is the only intersected object, ignore the event.
  43675. if (!intersectedEl) { return; }
  43676. // Already intersecting this entity.
  43677. if (this.intersectedEl === intersectedEl) { return; }
  43678. // Ignore events further away than active intersection.
  43679. if (this.intersectedEl) {
  43680. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  43681. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  43682. }
  43683. // Unset current intersection.
  43684. this.clearCurrentIntersection(true);
  43685. this.setIntersection(intersectedEl, intersection);
  43686. },
  43687. /**
  43688. * Handle intersection cleared.
  43689. */
  43690. onIntersectionCleared: function (evt) {
  43691. var clearedEls = evt.detail.clearedEls;
  43692. // Check if the current intersection has ended
  43693. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  43694. this.clearCurrentIntersection();
  43695. },
  43696. setIntersection: function (intersectedEl, intersection) {
  43697. var cursorEl = this.el;
  43698. var data = this.data;
  43699. var self = this;
  43700. // Already intersecting.
  43701. if (this.intersectedEl === intersectedEl) { return; }
  43702. // Set new intersection.
  43703. this.intersectedEl = intersectedEl;
  43704. // Hovering.
  43705. cursorEl.addState(STATES.HOVERING);
  43706. intersectedEl.addState(STATES.HOVERED);
  43707. this.twoWayEmit(EVENTS.MOUSEENTER);
  43708. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  43709. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  43710. }
  43711. // Begin fuse if necessary.
  43712. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43713. cursorEl.addState(STATES.FUSING);
  43714. this.twoWayEmit(EVENTS.FUSING);
  43715. this.fuseTimeout = setTimeout(function fuse () {
  43716. cursorEl.removeState(STATES.FUSING);
  43717. self.twoWayEmit(EVENTS.CLICK);
  43718. }, data.fuseTimeout);
  43719. },
  43720. clearCurrentIntersection: function (ignoreRemaining) {
  43721. var index;
  43722. var intersection;
  43723. var intersections;
  43724. var cursorEl = this.el;
  43725. // Nothing to be cleared.
  43726. if (!this.intersectedEl) { return; }
  43727. // No longer hovering (or fusing).
  43728. this.intersectedEl.removeState(STATES.HOVERED);
  43729. cursorEl.removeState(STATES.HOVERING);
  43730. cursorEl.removeState(STATES.FUSING);
  43731. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43732. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  43733. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  43734. }
  43735. // Unset intersected entity (after emitting the event).
  43736. this.intersectedEl = null;
  43737. // Clear fuseTimeout.
  43738. clearTimeout(this.fuseTimeout);
  43739. // Set intersection to another raycasted element if any.
  43740. if (ignoreRemaining === true) { return; }
  43741. intersections = this.el.components.raycaster.intersections;
  43742. if (intersections.length === 0) { return; }
  43743. // Exclude the cursor.
  43744. index = intersections[0].object.el === cursorEl ? 1 : 0;
  43745. intersection = intersections[index];
  43746. if (!intersection) { return; }
  43747. this.setIntersection(intersection.object.el, intersection);
  43748. },
  43749. /**
  43750. * Helper to emit on both the cursor and the intersected entity (if exists).
  43751. */
  43752. twoWayEmit: function (evtName) {
  43753. var el = this.el;
  43754. var intersectedEl = this.intersectedEl;
  43755. var intersection;
  43756. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  43757. this.eventDetail.intersectedEl = intersectedEl;
  43758. this.eventDetail.intersection = intersection;
  43759. el.emit(evtName, this.eventDetail);
  43760. if (!intersectedEl) { return; }
  43761. this.intersectedEventDetail.intersection = intersection;
  43762. intersectedEl.emit(evtName, this.intersectedEventDetail);
  43763. }
  43764. });
  43765. },{"../core/component":124,"../utils/":197}],76:[function(_dereq_,module,exports){
  43766. var registerComponent = _dereq_('../core/component').registerComponent;
  43767. var bind = _dereq_('../utils/bind');
  43768. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43769. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43770. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43771. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43772. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  43773. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  43774. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  43775. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  43776. /**
  43777. * Daydream controls.
  43778. * Interface with Daydream controller and map Gamepad events to
  43779. * controller buttons: trackpad, menu, system
  43780. * Load a controller model and highlight the pressed buttons.
  43781. */
  43782. module.exports.Component = registerComponent('daydream-controls', {
  43783. schema: {
  43784. hand: {default: ''}, // This informs the degenerate arm model.
  43785. buttonColor: {type: 'color', default: '#000000'},
  43786. buttonTouchedColor: {type: 'color', default: '#777777'},
  43787. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43788. model: {default: true},
  43789. orientationOffset: {type: 'vec3'},
  43790. armModel: {default: true}
  43791. },
  43792. /**
  43793. * Button IDs:
  43794. * 0 - trackpad
  43795. * 1 - menu (never dispatched on this layer)
  43796. * 2 - system (never dispatched on this layer)
  43797. */
  43798. mapping: {
  43799. axes: {trackpad: [0, 1]},
  43800. buttons: ['trackpad', 'menu', 'system']
  43801. },
  43802. bindMethods: function () {
  43803. this.onModelLoaded = bind(this.onModelLoaded, this);
  43804. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43805. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43806. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43807. this.onAxisMoved = bind(this.onAxisMoved, this);
  43808. },
  43809. init: function () {
  43810. var self = this;
  43811. this.onButtonChanged = bind(this.onButtonChanged, this);
  43812. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43813. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43814. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43815. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43816. this.controllerPresent = false;
  43817. this.lastControllerCheck = 0;
  43818. this.bindMethods();
  43819. },
  43820. addEventListeners: function () {
  43821. var el = this.el;
  43822. el.addEventListener('buttonchanged', this.onButtonChanged);
  43823. el.addEventListener('buttondown', this.onButtonDown);
  43824. el.addEventListener('buttonup', this.onButtonUp);
  43825. el.addEventListener('touchstart', this.onButtonTouchStart);
  43826. el.addEventListener('touchend', this.onButtonTouchEnd);
  43827. el.addEventListener('model-loaded', this.onModelLoaded);
  43828. el.addEventListener('axismove', this.onAxisMoved);
  43829. this.controllerEventsActive = true;
  43830. },
  43831. removeEventListeners: function () {
  43832. var el = this.el;
  43833. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43834. el.removeEventListener('buttondown', this.onButtonDown);
  43835. el.removeEventListener('buttonup', this.onButtonUp);
  43836. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43837. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43838. el.removeEventListener('model-loaded', this.onModelLoaded);
  43839. el.removeEventListener('axismove', this.onAxisMoved);
  43840. this.controllerEventsActive = false;
  43841. },
  43842. checkIfControllerPresent: function () {
  43843. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  43844. },
  43845. play: function () {
  43846. this.checkIfControllerPresent();
  43847. this.addControllersUpdateListener();
  43848. },
  43849. pause: function () {
  43850. this.removeEventListeners();
  43851. this.removeControllersUpdateListener();
  43852. },
  43853. injectTrackedControls: function () {
  43854. var el = this.el;
  43855. var data = this.data;
  43856. el.setAttribute('tracked-controls', {
  43857. armModel: data.armModel,
  43858. hand: data.hand,
  43859. idPrefix: GAMEPAD_ID_PREFIX,
  43860. orientationOffset: data.orientationOffset
  43861. });
  43862. if (!this.data.model) { return; }
  43863. this.el.setAttribute('obj-model', {
  43864. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  43865. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  43866. });
  43867. },
  43868. addControllersUpdateListener: function () {
  43869. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43870. },
  43871. removeControllersUpdateListener: function () {
  43872. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43873. },
  43874. onControllersUpdate: function () {
  43875. this.checkIfControllerPresent();
  43876. },
  43877. onModelLoaded: function (evt) {
  43878. var controllerObject3D = evt.detail.model;
  43879. var buttonMeshes;
  43880. if (!this.data.model) { return; }
  43881. buttonMeshes = this.buttonMeshes = {};
  43882. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  43883. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  43884. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  43885. // Offset pivot point.
  43886. controllerObject3D.position.set(0, 0, -0.04);
  43887. },
  43888. onAxisMoved: function (evt) {
  43889. emitIfAxesChanged(this, this.mapping.axes, evt);
  43890. },
  43891. onButtonChanged: function (evt) {
  43892. var button = this.mapping.buttons[evt.detail.id];
  43893. if (!button) return;
  43894. // Pass along changed event with button state, using button mapping for convenience.
  43895. this.el.emit(button + 'changed', evt.detail.state);
  43896. },
  43897. updateModel: function (buttonName, evtName) {
  43898. if (!this.data.model) { return; }
  43899. this.updateButtonModel(buttonName, evtName);
  43900. },
  43901. updateButtonModel: function (buttonName, state) {
  43902. var buttonMeshes = this.buttonMeshes;
  43903. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43904. var color;
  43905. switch (state) {
  43906. case 'down':
  43907. color = this.data.buttonHighlightColor;
  43908. break;
  43909. case 'touchstart':
  43910. color = this.data.buttonTouchedColor;
  43911. break;
  43912. default:
  43913. color = this.data.buttonColor;
  43914. }
  43915. buttonMeshes[buttonName].material.color.set(color);
  43916. }
  43917. });
  43918. },{"../core/component":124,"../utils/bind":191,"../utils/tracked-controls":205}],77:[function(_dereq_,module,exports){
  43919. var registerComponent = _dereq_('../core/component').registerComponent;
  43920. var bind = _dereq_('../utils/bind');
  43921. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43922. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43923. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43924. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43925. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  43926. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  43927. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  43928. var GAMEPAD_ID_PREFIX = 'Gear VR';
  43929. /**
  43930. * Gear VR controls.
  43931. * Interface with Gear VR controller and map Gamepad events to
  43932. * controller buttons: trackpad, trigger
  43933. * Load a controller model and highlight the pressed buttons.
  43934. */
  43935. module.exports.Component = registerComponent('gearvr-controls', {
  43936. schema: {
  43937. hand: {default: ''}, // This informs the degenerate arm model.
  43938. buttonColor: {type: 'color', default: '#000000'},
  43939. buttonTouchedColor: {type: 'color', default: '#777777'},
  43940. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43941. model: {default: true},
  43942. orientationOffset: {type: 'vec3'},
  43943. armModel: {default: true}
  43944. },
  43945. /**
  43946. * Button IDs:
  43947. * 0 - trackpad
  43948. * 1 - trigger
  43949. */
  43950. mapping: {
  43951. axes: {trackpad: [0, 1]},
  43952. buttons: ['trackpad', 'trigger']
  43953. },
  43954. bindMethods: function () {
  43955. this.onModelLoaded = bind(this.onModelLoaded, this);
  43956. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43957. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43958. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43959. this.onAxisMoved = bind(this.onAxisMoved, this);
  43960. },
  43961. init: function () {
  43962. var self = this;
  43963. this.onButtonChanged = bind(this.onButtonChanged, this);
  43964. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43965. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43966. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43967. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43968. this.controllerPresent = false;
  43969. this.lastControllerCheck = 0;
  43970. this.bindMethods();
  43971. },
  43972. addEventListeners: function () {
  43973. var el = this.el;
  43974. el.addEventListener('buttonchanged', this.onButtonChanged);
  43975. el.addEventListener('buttondown', this.onButtonDown);
  43976. el.addEventListener('buttonup', this.onButtonUp);
  43977. el.addEventListener('touchstart', this.onButtonTouchStart);
  43978. el.addEventListener('touchend', this.onButtonTouchEnd);
  43979. el.addEventListener('model-loaded', this.onModelLoaded);
  43980. el.addEventListener('axismove', this.onAxisMoved);
  43981. this.controllerEventsActive = true;
  43982. },
  43983. removeEventListeners: function () {
  43984. var el = this.el;
  43985. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43986. el.removeEventListener('buttondown', this.onButtonDown);
  43987. el.removeEventListener('buttonup', this.onButtonUp);
  43988. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43989. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43990. el.removeEventListener('model-loaded', this.onModelLoaded);
  43991. el.removeEventListener('axismove', this.onAxisMoved);
  43992. this.controllerEventsActive = false;
  43993. },
  43994. checkIfControllerPresent: function () {
  43995. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  43996. this.data.hand ? {hand: this.data.hand} : {});
  43997. },
  43998. play: function () {
  43999. this.checkIfControllerPresent();
  44000. this.addControllersUpdateListener();
  44001. },
  44002. pause: function () {
  44003. this.removeEventListeners();
  44004. this.removeControllersUpdateListener();
  44005. },
  44006. injectTrackedControls: function () {
  44007. var el = this.el;
  44008. var data = this.data;
  44009. el.setAttribute('tracked-controls', {
  44010. armModel: data.armModel,
  44011. idPrefix: GAMEPAD_ID_PREFIX,
  44012. orientationOffset: data.orientationOffset
  44013. });
  44014. if (!this.data.model) { return; }
  44015. this.el.setAttribute('obj-model', {
  44016. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  44017. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  44018. });
  44019. },
  44020. addControllersUpdateListener: function () {
  44021. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44022. },
  44023. removeControllersUpdateListener: function () {
  44024. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44025. },
  44026. onControllersUpdate: function () {
  44027. this.checkIfControllerPresent();
  44028. },
  44029. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  44030. onModelLoaded: function (evt) {
  44031. var controllerObject3D = evt.detail.model;
  44032. var buttonMeshes;
  44033. if (!this.data.model) { return; }
  44034. buttonMeshes = this.buttonMeshes = {};
  44035. buttonMeshes.trigger = controllerObject3D.children[2];
  44036. buttonMeshes.trackpad = controllerObject3D.children[1];
  44037. },
  44038. onButtonChanged: function (evt) {
  44039. var button = this.mapping.buttons[evt.detail.id];
  44040. if (!button) return;
  44041. // Pass along changed event with button state, using button mapping for convenience.
  44042. this.el.emit(button + 'changed', evt.detail.state);
  44043. },
  44044. onAxisMoved: function (evt) {
  44045. emitIfAxesChanged(this, this.mapping.axes, evt);
  44046. },
  44047. updateModel: function (buttonName, evtName) {
  44048. if (!this.data.model) { return; }
  44049. this.updateButtonModel(buttonName, evtName);
  44050. },
  44051. updateButtonModel: function (buttonName, state) {
  44052. var buttonMeshes = this.buttonMeshes;
  44053. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44054. var color;
  44055. switch (state) {
  44056. case 'down':
  44057. color = this.data.buttonHighlightColor;
  44058. break;
  44059. case 'touchstart':
  44060. color = this.data.buttonTouchedColor;
  44061. break;
  44062. default:
  44063. color = this.data.buttonColor;
  44064. }
  44065. buttonMeshes[buttonName].material.color.set(color);
  44066. }
  44067. });
  44068. },{"../core/component":124,"../utils/bind":191,"../utils/tracked-controls":205}],78:[function(_dereq_,module,exports){
  44069. var geometries = _dereq_('../core/geometry').geometries;
  44070. var geometryNames = _dereq_('../core/geometry').geometryNames;
  44071. var registerComponent = _dereq_('../core/component').registerComponent;
  44072. var THREE = _dereq_('../lib/three');
  44073. var dummyGeometry = new THREE.Geometry();
  44074. /**
  44075. * Geometry component. Combined with material component to make a mesh in 3D object.
  44076. * Extended with registered geometries.
  44077. */
  44078. module.exports.Component = registerComponent('geometry', {
  44079. schema: {
  44080. buffer: {default: true},
  44081. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  44082. skipCache: {default: false}
  44083. },
  44084. init: function () {
  44085. this.geometry = null;
  44086. },
  44087. /**
  44088. * Talk to geometry system to get or create geometry.
  44089. */
  44090. update: function (previousData) {
  44091. var data = this.data;
  44092. var el = this.el;
  44093. var mesh;
  44094. var system = this.system;
  44095. // Dispose old geometry if we created one.
  44096. if (this.geometry) {
  44097. system.unuseGeometry(previousData);
  44098. this.geometry = null;
  44099. }
  44100. // Create new geometry.
  44101. this.geometry = system.getOrCreateGeometry(data);
  44102. // Set on mesh. If mesh does not exist, create it.
  44103. mesh = el.getObject3D('mesh');
  44104. if (mesh) {
  44105. mesh.geometry = this.geometry;
  44106. } else {
  44107. mesh = new THREE.Mesh();
  44108. mesh.geometry = this.geometry;
  44109. el.setObject3D('mesh', mesh);
  44110. }
  44111. },
  44112. /**
  44113. * Tell geometry system that entity is no longer using the geometry.
  44114. * Unset the geometry on the mesh
  44115. */
  44116. remove: function () {
  44117. this.system.unuseGeometry(this.data);
  44118. this.el.getObject3D('mesh').geometry = dummyGeometry;
  44119. this.geometry = null;
  44120. },
  44121. /**
  44122. * Update geometry component schema based on geometry type.
  44123. */
  44124. updateSchema: function (data) {
  44125. var currentGeometryType = this.oldData && this.oldData.primitive;
  44126. var newGeometryType = data.primitive;
  44127. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  44128. // Geometry has no schema.
  44129. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  44130. // Nothing has changed.
  44131. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  44132. this.extendSchema(schema);
  44133. }
  44134. });
  44135. },{"../core/component":124,"../core/geometry":125,"../lib/three":172}],79:[function(_dereq_,module,exports){
  44136. var registerComponent = _dereq_('../core/component').registerComponent;
  44137. var THREE = _dereq_('../lib/three');
  44138. var utils = _dereq_('../utils/');
  44139. var warn = utils.debug('components:gltf-model:warn');
  44140. /**
  44141. * glTF model loader.
  44142. */
  44143. module.exports.Component = registerComponent('gltf-model', {
  44144. schema: {type: 'model'},
  44145. init: function () {
  44146. var dracoLoader = this.system.getDRACOLoader();
  44147. this.model = null;
  44148. this.loader = new THREE.GLTFLoader();
  44149. if (dracoLoader) {
  44150. this.loader.setDRACOLoader(dracoLoader);
  44151. }
  44152. },
  44153. update: function () {
  44154. var self = this;
  44155. var el = this.el;
  44156. var src = this.data;
  44157. if (!src) { return; }
  44158. this.remove();
  44159. this.loader.load(src, function gltfLoaded (gltfModel) {
  44160. self.model = gltfModel.scene || gltfModel.scenes[0];
  44161. self.model.animations = gltfModel.animations;
  44162. el.setObject3D('mesh', self.model);
  44163. el.emit('model-loaded', {format: 'gltf', model: self.model});
  44164. }, undefined /* onProgress */, function gltfFailed (error) {
  44165. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  44166. warn(message);
  44167. el.emit('model-error', {format: 'gltf', src: src});
  44168. });
  44169. },
  44170. remove: function () {
  44171. if (!this.model) { return; }
  44172. this.el.removeObject3D('mesh');
  44173. }
  44174. });
  44175. },{"../core/component":124,"../lib/three":172,"../utils/":197}],80:[function(_dereq_,module,exports){
  44176. /* global THREE */
  44177. var registerComponent = _dereq_('../core/component').registerComponent;
  44178. // Found at https://github.com/aframevr/assets.
  44179. var MODEL_URLS = {
  44180. left: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  44181. right: 'https://cdn.aframe.io/controllers/hands/rightHand.glb'
  44182. };
  44183. // Poses.
  44184. var ANIMATIONS = {
  44185. open: 'Open',
  44186. // point: grip active, trackpad surface active, trigger inactive.
  44187. point: 'Point',
  44188. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  44189. pointThumb: 'Point + Thumb',
  44190. // fist: grip active, trigger active, trackpad surface active.
  44191. fist: 'Fist',
  44192. // hold: trigger active, grip inactive.
  44193. hold: 'Hold',
  44194. // thumbUp: grip active, trigger active, trackpad surface inactive.
  44195. thumbUp: 'Thumb Up'
  44196. };
  44197. // Map animation to public events for the API.
  44198. var EVENTS = {};
  44199. EVENTS[ANIMATIONS.fist] = 'grip';
  44200. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  44201. EVENTS[ANIMATIONS.point] = 'pointing';
  44202. /**
  44203. * Hand controls component that abstracts 6DoF controls:
  44204. * oculus-touch-controls, vive-controls, windows-motion-controls.
  44205. *
  44206. * Originally meant to be a sample implementation of applications-specific controls that
  44207. * abstracts multiple types of controllers.
  44208. *
  44209. * Auto-detect appropriate controller.
  44210. * Handle common events coming from the detected vendor-specific controls.
  44211. * Translate button events to semantic hand-related event names:
  44212. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  44213. * Load hand model with gestures that are applied based on the button pressed.
  44214. *
  44215. * @property {string} Hand mapping (`left`, `right`).
  44216. */
  44217. module.exports.Component = registerComponent('hand-controls', {
  44218. schema: {default: 'left'},
  44219. init: function () {
  44220. var self = this;
  44221. var el = this.el;
  44222. // Current pose.
  44223. this.gesture = ANIMATIONS.open;
  44224. // Active buttons populated by events provided by the attached controls.
  44225. this.pressedButtons = {};
  44226. this.touchedButtons = {};
  44227. this.loader = new THREE.GLTFLoader();
  44228. this.loader.setCrossOrigin('anonymous');
  44229. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  44230. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  44231. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  44232. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  44233. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  44234. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  44235. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  44236. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  44237. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  44238. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  44239. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  44240. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  44241. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  44242. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  44243. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  44244. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  44245. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  44246. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  44247. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  44248. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  44249. el.addEventListener('controllerconnected', this.onControllerConnected);
  44250. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  44251. // Hidden by default.
  44252. el.object3D.visible = false;
  44253. },
  44254. play: function () {
  44255. this.addEventListeners();
  44256. },
  44257. pause: function () {
  44258. this.removeEventListeners();
  44259. },
  44260. tick: function (time, delta) {
  44261. var mesh = this.el.getObject3D('mesh');
  44262. if (!mesh || !mesh.mixer) { return; }
  44263. mesh.mixer.update(delta / 1000);
  44264. },
  44265. addEventListeners: function () {
  44266. var el = this.el;
  44267. el.addEventListener('gripdown', this.onGripDown);
  44268. el.addEventListener('gripup', this.onGripUp);
  44269. el.addEventListener('trackpaddown', this.onTrackpadDown);
  44270. el.addEventListener('trackpadup', this.onTrackpadUp);
  44271. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44272. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44273. el.addEventListener('triggerdown', this.onTriggerDown);
  44274. el.addEventListener('triggerup', this.onTriggerUp);
  44275. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  44276. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  44277. el.addEventListener('griptouchstart', this.onGripTouchStart);
  44278. el.addEventListener('griptouchend', this.onGripTouchEnd);
  44279. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  44280. el.addEventListener('thumbstickup', this.onThumbstickUp);
  44281. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  44282. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  44283. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44284. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44285. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44286. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44287. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44288. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44289. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44290. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44291. },
  44292. removeEventListeners: function () {
  44293. var el = this.el;
  44294. el.removeEventListener('gripdown', this.onGripDown);
  44295. el.removeEventListener('gripup', this.onGripUp);
  44296. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  44297. el.removeEventListener('trackpadup', this.onTrackpadUp);
  44298. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44299. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44300. el.removeEventListener('triggerdown', this.onTriggerDown);
  44301. el.removeEventListener('triggerup', this.onTriggerUp);
  44302. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  44303. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  44304. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  44305. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  44306. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  44307. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  44308. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  44309. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  44310. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44311. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44312. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44313. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44314. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44315. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44316. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44317. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44318. },
  44319. /**
  44320. * Update handler. More like the `init` handler since the only property is the hand, and
  44321. * that won't be changing much.
  44322. */
  44323. update: function (previousHand) {
  44324. var controlConfiguration;
  44325. var el = this.el;
  44326. var hand = this.data;
  44327. var self = this;
  44328. // Get common configuration to abstract different vendor controls.
  44329. controlConfiguration = {
  44330. hand: hand,
  44331. model: false,
  44332. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  44333. };
  44334. // Set model.
  44335. if (hand !== previousHand) {
  44336. this.loader.load(MODEL_URLS[hand], function (gltf) {
  44337. var mesh = gltf.scene.children[0];
  44338. mesh.mixer = new THREE.AnimationMixer(mesh);
  44339. self.clips = gltf.animations;
  44340. el.setObject3D('mesh', mesh);
  44341. mesh.position.set(0, 0, 0);
  44342. mesh.rotation.set(0, 0, 0);
  44343. el.setAttribute('vive-controls', controlConfiguration);
  44344. el.setAttribute('oculus-touch-controls', controlConfiguration);
  44345. el.setAttribute('windows-motion-controls', controlConfiguration);
  44346. });
  44347. }
  44348. },
  44349. remove: function () {
  44350. this.el.removeObject3D('mesh');
  44351. },
  44352. /**
  44353. * Play model animation, based on which button was pressed and which kind of event.
  44354. *
  44355. * 1. Process buttons.
  44356. * 2. Determine gesture (this.determineGesture()).
  44357. * 3. Animation gesture (this.animationGesture()).
  44358. * 4. Emit gesture events (this.emitGestureEvents()).
  44359. *
  44360. * @param {string} button - Name of the button.
  44361. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  44362. */
  44363. handleButton: function (button, evt) {
  44364. var lastGesture;
  44365. var isPressed = evt === 'down';
  44366. var isTouched = evt === 'touchstart';
  44367. // Update objects.
  44368. if (evt.indexOf('touch') === 0) {
  44369. // Update touch object.
  44370. if (isTouched === this.touchedButtons[button]) { return; }
  44371. this.touchedButtons[button] = isTouched;
  44372. } else {
  44373. // Update button object.
  44374. if (isPressed === this.pressedButtons[button]) { return; }
  44375. this.pressedButtons[button] = isPressed;
  44376. }
  44377. // Determine the gesture.
  44378. lastGesture = this.gesture;
  44379. this.gesture = this.determineGesture();
  44380. // Same gesture.
  44381. if (this.gesture === lastGesture) { return; }
  44382. // Animate gesture.
  44383. this.animateGesture(this.gesture, lastGesture);
  44384. // Emit events.
  44385. this.emitGestureEvents(this.gesture, lastGesture);
  44386. },
  44387. /**
  44388. * Determine which pose hand should be in considering active and touched buttons.
  44389. */
  44390. determineGesture: function () {
  44391. var gesture;
  44392. var isGripActive = this.pressedButtons['grip'];
  44393. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  44394. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  44395. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  44396. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  44397. var isVive = isViveController(this.el.components['tracked-controls']);
  44398. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  44399. if (isVive) {
  44400. if (isGripActive || isTriggerActive) {
  44401. gesture = ANIMATIONS.fist;
  44402. } else if (isTrackpadActive) {
  44403. gesture = ANIMATIONS.point;
  44404. }
  44405. } else {
  44406. if (isGripActive) {
  44407. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  44408. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  44409. } else {
  44410. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  44411. }
  44412. } else if (isTriggerActive) {
  44413. gesture = ANIMATIONS.hold;
  44414. }
  44415. }
  44416. return gesture;
  44417. },
  44418. /**
  44419. * Play corresponding clip to a gesture
  44420. */
  44421. getClip: function (gesture) {
  44422. var clip;
  44423. var i;
  44424. for (i = 0; i < this.clips.length; i++) {
  44425. clip = this.clips[i];
  44426. if (clip.name !== gesture) { continue; }
  44427. return clip;
  44428. }
  44429. },
  44430. /**
  44431. * Play gesture animation.
  44432. *
  44433. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  44434. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  44435. */
  44436. animateGesture: function (gesture, lastGesture) {
  44437. if (gesture) {
  44438. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  44439. return;
  44440. }
  44441. // If no gesture, then reverse the current gesture back to open pose.
  44442. this.playAnimation(lastGesture, lastGesture, true);
  44443. },
  44444. /**
  44445. * Emit `hand-controls`-specific events.
  44446. */
  44447. emitGestureEvents: function (gesture, lastGesture) {
  44448. var el = this.el;
  44449. var eventName;
  44450. if (lastGesture === gesture) { return; }
  44451. // Emit event for lastGesture not inactive.
  44452. eventName = getGestureEventName(lastGesture, false);
  44453. if (eventName) { el.emit(eventName); }
  44454. // Emit event for current gesture now active.
  44455. eventName = getGestureEventName(gesture, true);
  44456. if (eventName) { el.emit(eventName); }
  44457. },
  44458. /**
  44459. * Play hand animation based on button state.
  44460. *
  44461. * @param {string} gesture - Name of the animation as specified by the model.
  44462. * @param {string} lastGesture - Previous pose.
  44463. * @param {boolean} reverse - Whether animation should play in reverse.
  44464. */
  44465. playAnimation: function (gesture, lastGesture, reverse) {
  44466. var clip;
  44467. var fromAction;
  44468. var mesh = this.el.getObject3D('mesh');
  44469. var toAction;
  44470. if (!mesh) { return; }
  44471. // Stop all current animations.
  44472. mesh.mixer.stopAllAction();
  44473. // Grab clip action.
  44474. clip = this.getClip(gesture);
  44475. toAction = mesh.mixer.clipAction(clip);
  44476. toAction.clampWhenFinished = true;
  44477. toAction.loop = THREE.LoopRepeat;
  44478. toAction.repetitions = 0;
  44479. toAction.timeScale = reverse ? -1 : 1;
  44480. toAction.time = reverse ? clip.duration : 0;
  44481. toAction.weight = 1;
  44482. // No gesture to gesture or gesture to no gesture.
  44483. if (!lastGesture || gesture === lastGesture) {
  44484. // Stop all current animations.
  44485. mesh.mixer.stopAllAction();
  44486. // Play animation.
  44487. toAction.play();
  44488. return;
  44489. }
  44490. // Animate or crossfade from gesture to gesture.
  44491. clip = this.getClip(lastGesture);
  44492. fromAction = mesh.mixer.clipAction(clip);
  44493. fromAction.weight = 0.15;
  44494. fromAction.play();
  44495. toAction.play();
  44496. fromAction.crossFadeTo(toAction, 0.15, true);
  44497. }
  44498. });
  44499. /**
  44500. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  44501. *
  44502. * @param {string} gesture
  44503. * @param {boolean} active
  44504. */
  44505. function getGestureEventName (gesture, active) {
  44506. var eventName;
  44507. if (!gesture) { return; }
  44508. eventName = EVENTS[gesture];
  44509. if (eventName === 'grip') {
  44510. return eventName + (active ? 'close' : 'open');
  44511. }
  44512. if (eventName === 'point') {
  44513. return eventName + (active ? 'up' : 'down');
  44514. }
  44515. if (eventName === 'pointing' || eventName === 'pistol') {
  44516. return eventName + (active ? 'start' : 'end');
  44517. }
  44518. return;
  44519. }
  44520. function isViveController (trackedControls) {
  44521. var controllerId = trackedControls && trackedControls.controller &&
  44522. trackedControls.controller.id;
  44523. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  44524. }
  44525. },{"../core/component":124}],81:[function(_dereq_,module,exports){
  44526. _dereq_('./animation');
  44527. _dereq_('./camera');
  44528. _dereq_('./cursor');
  44529. _dereq_('./daydream-controls');
  44530. _dereq_('./gearvr-controls');
  44531. _dereq_('./geometry');
  44532. _dereq_('./gltf-model');
  44533. _dereq_('./hand-controls');
  44534. _dereq_('./laser-controls');
  44535. _dereq_('./light');
  44536. _dereq_('./line');
  44537. _dereq_('./link');
  44538. _dereq_('./look-controls');
  44539. _dereq_('./material');
  44540. _dereq_('./obj-model');
  44541. _dereq_('./oculus-go-controls');
  44542. _dereq_('./oculus-touch-controls');
  44543. _dereq_('./position');
  44544. _dereq_('./raycaster');
  44545. _dereq_('./rotation');
  44546. _dereq_('./scale');
  44547. _dereq_('./shadow');
  44548. _dereq_('./sound');
  44549. _dereq_('./text');
  44550. _dereq_('./tracked-controls');
  44551. _dereq_('./tracked-controls-webvr');
  44552. _dereq_('./tracked-controls-webxr');
  44553. _dereq_('./visible');
  44554. _dereq_('./vive-controls');
  44555. _dereq_('./vive-focus-controls');
  44556. _dereq_('./wasd-controls');
  44557. _dereq_('./windows-motion-controls');
  44558. _dereq_('./scene/background');
  44559. _dereq_('./scene/debug');
  44560. _dereq_('./scene/embedded');
  44561. _dereq_('./scene/inspector');
  44562. _dereq_('./scene/fog');
  44563. _dereq_('./scene/keyboard-shortcuts');
  44564. _dereq_('./scene/pool');
  44565. _dereq_('./scene/screenshot');
  44566. _dereq_('./scene/stats');
  44567. _dereq_('./scene/vr-mode-ui');
  44568. },{"./animation":73,"./camera":74,"./cursor":75,"./daydream-controls":76,"./gearvr-controls":77,"./geometry":78,"./gltf-model":79,"./hand-controls":80,"./laser-controls":82,"./light":83,"./line":84,"./link":85,"./look-controls":86,"./material":87,"./obj-model":88,"./oculus-go-controls":89,"./oculus-touch-controls":90,"./position":91,"./raycaster":92,"./rotation":93,"./scale":94,"./scene/background":95,"./scene/debug":96,"./scene/embedded":97,"./scene/fog":98,"./scene/inspector":99,"./scene/keyboard-shortcuts":100,"./scene/pool":101,"./scene/screenshot":102,"./scene/stats":103,"./scene/vr-mode-ui":104,"./shadow":105,"./sound":106,"./text":107,"./tracked-controls":110,"./tracked-controls-webvr":108,"./tracked-controls-webxr":109,"./visible":111,"./vive-controls":112,"./vive-focus-controls":113,"./wasd-controls":114,"./windows-motion-controls":115}],82:[function(_dereq_,module,exports){
  44569. var registerComponent = _dereq_('../core/component').registerComponent;
  44570. var utils = _dereq_('../utils/');
  44571. registerComponent('laser-controls', {
  44572. schema: {
  44573. hand: {default: 'right'},
  44574. model: {default: true},
  44575. defaultModelColor: {type: 'color', default: 'grey'}
  44576. },
  44577. init: function () {
  44578. var config = this.config;
  44579. var data = this.data;
  44580. var el = this.el;
  44581. var self = this;
  44582. var modelEnabled = this.data.model && !this.el.sceneEl.hasWebXR;
  44583. var controlsConfiguration = {hand: data.hand, model: modelEnabled};
  44584. // Set all controller models.
  44585. el.setAttribute('daydream-controls', controlsConfiguration);
  44586. el.setAttribute('gearvr-controls', controlsConfiguration);
  44587. el.setAttribute('oculus-go-controls', controlsConfiguration);
  44588. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  44589. el.setAttribute('vive-controls', controlsConfiguration);
  44590. el.setAttribute('vive-focus-controls', controlsConfiguration);
  44591. el.setAttribute('windows-motion-controls', controlsConfiguration);
  44592. // WebXR doesn't allow to discriminate between controllers, a default model is used.
  44593. if (this.data.model && this.el.sceneEl.hasWebXR) { this.initDefaultModel(); }
  44594. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  44595. el.addEventListener('controllerconnected', createRay);
  44596. el.addEventListener('controllerdisconnected', hideRay);
  44597. el.addEventListener('controllermodelready', function (evt) {
  44598. createRay(evt);
  44599. self.modelReady = true;
  44600. });
  44601. function createRay (evt) {
  44602. var controllerConfig = config[evt.detail.name];
  44603. if (!controllerConfig) { return; }
  44604. // Show the line unless a particular config opts to hide it, until a controllermodelready
  44605. // event comes through.
  44606. var raycasterConfig = utils.extend({
  44607. showLine: true
  44608. }, controllerConfig.raycaster || {});
  44609. // The controllermodelready event contains a rayOrigin that takes into account
  44610. // offsets specific to the loaded model.
  44611. if (evt.detail.rayOrigin) {
  44612. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  44613. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  44614. raycasterConfig.showLine = true;
  44615. }
  44616. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  44617. // config applied from a controllermodelready event.
  44618. if (evt.detail.rayOrigin || !self.modelReady) {
  44619. el.setAttribute('raycaster', raycasterConfig);
  44620. } else {
  44621. el.setAttribute('raycaster', 'showLine', true);
  44622. }
  44623. el.setAttribute('cursor', utils.extend({
  44624. fuse: false
  44625. }, controllerConfig.cursor));
  44626. }
  44627. function hideRay () {
  44628. el.setAttribute('raycaster', 'showLine', false);
  44629. }
  44630. },
  44631. config: {
  44632. 'daydream-controls': {
  44633. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  44634. },
  44635. 'gearvr-controls': {
  44636. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44637. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44638. },
  44639. 'oculus-go-controls': {
  44640. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44641. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44642. },
  44643. 'oculus-touch-controls': {
  44644. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44645. raycaster: {origin: {x: 0, y: 0, z: 0}}
  44646. },
  44647. 'vive-controls': {
  44648. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  44649. },
  44650. 'vive-focus-controls': {
  44651. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  44652. },
  44653. 'windows-motion-controls': {
  44654. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44655. raycaster: {showLine: false}
  44656. }
  44657. },
  44658. initDefaultModel: function () {
  44659. var modelEl = this.modelEl = document.createElement('a-entity');
  44660. modelEl.setAttribute('geometry', {
  44661. primitive: 'sphere',
  44662. radius: 0.03
  44663. });
  44664. modelEl.setAttribute('material', {color: this.data.color});
  44665. this.el.appendChild(modelEl);
  44666. }
  44667. });
  44668. },{"../core/component":124,"../utils/":197}],83:[function(_dereq_,module,exports){
  44669. var bind = _dereq_('../utils/bind');
  44670. var diff = _dereq_('../utils').diff;
  44671. var debug = _dereq_('../utils/debug');
  44672. var registerComponent = _dereq_('../core/component').registerComponent;
  44673. var THREE = _dereq_('../lib/three');
  44674. var degToRad = THREE.Math.degToRad;
  44675. var warn = debug('components:light:warn');
  44676. /**
  44677. * Light component.
  44678. */
  44679. module.exports.Component = registerComponent('light', {
  44680. schema: {
  44681. angle: {default: 60, if: {type: ['spot']}},
  44682. color: {type: 'color'},
  44683. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44684. decay: {default: 1, if: {type: ['point', 'spot']}},
  44685. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44686. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44687. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44688. type: {
  44689. default: 'directional',
  44690. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  44691. schemaChange: true
  44692. },
  44693. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  44694. // Shadows.
  44695. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  44696. shadowBias: {default: 0, if: {castShadow: true}},
  44697. shadowCameraFar: {default: 500, if: {castShadow: true}},
  44698. shadowCameraFov: {default: 90, if: {castShadow: true}},
  44699. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  44700. shadowCameraTop: {default: 5, if: {castShadow: true}},
  44701. shadowCameraRight: {default: 5, if: {castShadow: true}},
  44702. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  44703. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  44704. shadowCameraVisible: {default: false, if: {castShadow: true}},
  44705. shadowMapHeight: {default: 512, if: {castShadow: true}},
  44706. shadowMapWidth: {default: 512, if: {castShadow: true}},
  44707. shadowRadius: {default: 1, if: {castShadow: true}}
  44708. },
  44709. /**
  44710. * Notifies scene a light has been added to remove default lighting.
  44711. */
  44712. init: function () {
  44713. var el = this.el;
  44714. this.light = null;
  44715. this.defaultTarget = null;
  44716. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44717. this.system.registerLight(el);
  44718. },
  44719. /**
  44720. * (Re)create or update light.
  44721. */
  44722. update: function (oldData) {
  44723. var data = this.data;
  44724. var diffData = diff(data, oldData);
  44725. var light = this.light;
  44726. var rendererSystem = this.rendererSystem;
  44727. var self = this;
  44728. // Existing light.
  44729. if (light && !('type' in diffData)) {
  44730. var shadowsLoaded = false;
  44731. // Light type has not changed. Update light.
  44732. Object.keys(diffData).forEach(function (key) {
  44733. var value = data[key];
  44734. switch (key) {
  44735. case 'color': {
  44736. light.color.set(value);
  44737. rendererSystem.applyColorCorrection(light.color);
  44738. break;
  44739. }
  44740. case 'groundColor': {
  44741. light.groundColor.set(value);
  44742. rendererSystem.applyColorCorrection(light.groundColor);
  44743. break;
  44744. }
  44745. case 'angle': {
  44746. light.angle = degToRad(value);
  44747. break;
  44748. }
  44749. case 'target': {
  44750. // Reset target if selector is null.
  44751. if (value === null) {
  44752. if (data.type === 'spot' || data.type === 'directional') {
  44753. light.target = self.defaultTarget;
  44754. }
  44755. } else {
  44756. // Target specified, set target to entity's `object3D` when it is loaded.
  44757. if (value.hasLoaded) {
  44758. self.onSetTarget(value, light);
  44759. } else {
  44760. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  44761. }
  44762. }
  44763. break;
  44764. }
  44765. case 'castShadow':
  44766. case 'shadowBias':
  44767. case 'shadowCameraFar':
  44768. case 'shadowCameraFov':
  44769. case 'shadowCameraNear':
  44770. case 'shadowCameraTop':
  44771. case 'shadowCameraRight':
  44772. case 'shadowCameraBottom':
  44773. case 'shadowCameraLeft':
  44774. case 'shadowCameraVisible':
  44775. case 'shadowMapHeight':
  44776. case 'shadowMapWidth':
  44777. case 'shadowRadius':
  44778. if (!shadowsLoaded) {
  44779. self.updateShadow();
  44780. shadowsLoaded = true;
  44781. }
  44782. break;
  44783. default: {
  44784. light[key] = value;
  44785. }
  44786. }
  44787. });
  44788. return;
  44789. }
  44790. // No light yet or light type has changed. Create and add light.
  44791. this.setLight(this.data);
  44792. this.updateShadow();
  44793. },
  44794. setLight: function (data) {
  44795. var el = this.el;
  44796. var newLight = this.getLight(data);
  44797. if (newLight) {
  44798. if (this.light) {
  44799. el.removeObject3D('light');
  44800. }
  44801. this.light = newLight;
  44802. this.light.el = el;
  44803. el.setObject3D('light', this.light);
  44804. // HACK solution for issue #1624
  44805. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44806. el.getObject3D('light').translateY(-1);
  44807. }
  44808. // set and position default lighttarget as a child to enable spotlight orientation
  44809. if (data.type === 'spot') {
  44810. el.setObject3D('light-target', this.defaultTarget);
  44811. el.getObject3D('light-target').position.set(0, 0, -1);
  44812. }
  44813. }
  44814. },
  44815. /**
  44816. * Updates shadow-related properties on the current light.
  44817. */
  44818. updateShadow: function () {
  44819. var el = this.el;
  44820. var data = this.data;
  44821. var light = this.light;
  44822. light.castShadow = data.castShadow;
  44823. // Shadow camera helper.
  44824. var cameraHelper = el.getObject3D('cameraHelper');
  44825. if (data.shadowCameraVisible && !cameraHelper) {
  44826. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  44827. } else if (!data.shadowCameraVisible && cameraHelper) {
  44828. el.removeObject3D('cameraHelper');
  44829. }
  44830. if (!data.castShadow) { return light; }
  44831. // Shadow appearance.
  44832. light.shadow.bias = data.shadowBias;
  44833. light.shadow.radius = data.shadowRadius;
  44834. light.shadow.mapSize.height = data.shadowMapHeight;
  44835. light.shadow.mapSize.width = data.shadowMapWidth;
  44836. // Shadow camera.
  44837. light.shadow.camera.near = data.shadowCameraNear;
  44838. light.shadow.camera.far = data.shadowCameraFar;
  44839. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  44840. light.shadow.camera.top = data.shadowCameraTop;
  44841. light.shadow.camera.right = data.shadowCameraRight;
  44842. light.shadow.camera.bottom = data.shadowCameraBottom;
  44843. light.shadow.camera.left = data.shadowCameraLeft;
  44844. } else {
  44845. light.shadow.camera.fov = data.shadowCameraFov;
  44846. }
  44847. light.shadow.camera.updateProjectionMatrix();
  44848. if (cameraHelper) { cameraHelper.update(); }
  44849. },
  44850. /**
  44851. * Creates a new three.js light object given data object defining the light.
  44852. *
  44853. * @param {object} data
  44854. */
  44855. getLight: function (data) {
  44856. var angle = data.angle;
  44857. var color = new THREE.Color(data.color);
  44858. this.rendererSystem.applyColorCorrection(color);
  44859. color = color.getHex();
  44860. var decay = data.decay;
  44861. var distance = data.distance;
  44862. var groundColor = new THREE.Color(data.groundColor);
  44863. this.rendererSystem.applyColorCorrection(groundColor);
  44864. groundColor = groundColor.getHex();
  44865. var intensity = data.intensity;
  44866. var type = data.type;
  44867. var target = data.target;
  44868. var light = null;
  44869. switch (type.toLowerCase()) {
  44870. case 'ambient': {
  44871. return new THREE.AmbientLight(color, intensity);
  44872. }
  44873. case 'directional': {
  44874. light = new THREE.DirectionalLight(color, intensity);
  44875. this.defaultTarget = light.target;
  44876. if (target) {
  44877. if (target.hasLoaded) {
  44878. this.onSetTarget(target, light);
  44879. } else {
  44880. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44881. }
  44882. }
  44883. return light;
  44884. }
  44885. case 'hemisphere': {
  44886. return new THREE.HemisphereLight(color, groundColor, intensity);
  44887. }
  44888. case 'point': {
  44889. return new THREE.PointLight(color, intensity, distance, decay);
  44890. }
  44891. case 'spot': {
  44892. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44893. this.defaultTarget = light.target;
  44894. if (target) {
  44895. if (target.hasLoaded) {
  44896. this.onSetTarget(target, light);
  44897. } else {
  44898. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44899. }
  44900. }
  44901. return light;
  44902. }
  44903. default: {
  44904. warn('%s is not a valid light type. ' +
  44905. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44906. }
  44907. }
  44908. },
  44909. onSetTarget: function (targetEl, light) {
  44910. light.target = targetEl.object3D;
  44911. },
  44912. /**
  44913. * Remove light on remove (callback).
  44914. */
  44915. remove: function () {
  44916. var el = this.el;
  44917. el.removeObject3D('light');
  44918. if (el.getObject3D('cameraHelper')) {
  44919. el.removeObject3D('cameraHelper');
  44920. }
  44921. }
  44922. });
  44923. },{"../core/component":124,"../lib/three":172,"../utils":197,"../utils/bind":191,"../utils/debug":193}],84:[function(_dereq_,module,exports){
  44924. /* global THREE */
  44925. var registerComponent = _dereq_('../core/component').registerComponent;
  44926. module.exports.Component = registerComponent('line', {
  44927. schema: {
  44928. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44929. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44930. color: {type: 'color', default: '#74BEC1'},
  44931. opacity: {type: 'number', default: 1},
  44932. visible: {default: true}
  44933. },
  44934. multiple: true,
  44935. init: function () {
  44936. var data = this.data;
  44937. var geometry;
  44938. var material;
  44939. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44940. material = this.material = new THREE.LineBasicMaterial({
  44941. color: data.color,
  44942. opacity: data.opacity,
  44943. transparent: data.opacity < 1,
  44944. visible: data.visible
  44945. });
  44946. geometry = this.geometry = new THREE.BufferGeometry();
  44947. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  44948. this.rendererSystem.applyColorCorrection(material.color);
  44949. this.line = new THREE.Line(geometry, material);
  44950. this.el.setObject3D(this.attrName, this.line);
  44951. },
  44952. update: function (oldData) {
  44953. var data = this.data;
  44954. var geometry = this.geometry;
  44955. var geoNeedsUpdate = false;
  44956. var material = this.material;
  44957. var positionArray = geometry.attributes.position.array;
  44958. // Update geometry.
  44959. if (!isEqualVec3(data.start, oldData.start)) {
  44960. positionArray[0] = data.start.x;
  44961. positionArray[1] = data.start.y;
  44962. positionArray[2] = data.start.z;
  44963. geoNeedsUpdate = true;
  44964. }
  44965. if (!isEqualVec3(data.end, oldData.end)) {
  44966. positionArray[3] = data.end.x;
  44967. positionArray[4] = data.end.y;
  44968. positionArray[5] = data.end.z;
  44969. geoNeedsUpdate = true;
  44970. }
  44971. if (geoNeedsUpdate) {
  44972. geometry.attributes.position.needsUpdate = true;
  44973. geometry.computeBoundingSphere();
  44974. }
  44975. material.color.setStyle(data.color);
  44976. this.rendererSystem.applyColorCorrection(material.color);
  44977. material.opacity = data.opacity;
  44978. material.transparent = data.opacity < 1;
  44979. material.visible = data.visible;
  44980. },
  44981. remove: function () {
  44982. this.el.removeObject3D('line', this.line);
  44983. }
  44984. });
  44985. function isEqualVec3 (a, b) {
  44986. if (!a || !b) { return false; }
  44987. return (a.x === b.x && a.y === b.y && a.z === b.z);
  44988. }
  44989. },{"../core/component":124}],85:[function(_dereq_,module,exports){
  44990. var registerComponent = _dereq_('../core/component').registerComponent;
  44991. var registerShader = _dereq_('../core/shader').registerShader;
  44992. var THREE = _dereq_('../lib/three');
  44993. /**
  44994. * Link component. Connect experiences and traverse between them in VR
  44995. *
  44996. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  44997. */
  44998. module.exports.Component = registerComponent('link', {
  44999. schema: {
  45000. backgroundColor: {default: 'red', type: 'color'},
  45001. borderColor: {default: 'white', type: 'color'},
  45002. highlighted: {default: false},
  45003. highlightedColor: {default: '#24CAFF', type: 'color'},
  45004. href: {default: ''},
  45005. image: {type: 'asset'},
  45006. on: {default: 'click'},
  45007. peekMode: {default: false},
  45008. title: {default: ''},
  45009. titleColor: {default: 'white', type: 'color'},
  45010. visualAspectEnabled: {default: false}
  45011. },
  45012. init: function () {
  45013. this.navigate = this.navigate.bind(this);
  45014. this.previousQuaternion = undefined;
  45015. this.quaternionClone = new THREE.Quaternion();
  45016. // Store hidden elements during peek mode so we can show them again later.
  45017. this.hiddenEls = [];
  45018. },
  45019. update: function (oldData) {
  45020. var data = this.data;
  45021. var el = this.el;
  45022. var backgroundColor;
  45023. var strokeColor;
  45024. if (!data.visualAspectEnabled) { return; }
  45025. this.initVisualAspect();
  45026. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  45027. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  45028. el.setAttribute('material', 'backgroundColor', backgroundColor);
  45029. el.setAttribute('material', 'strokeColor', strokeColor);
  45030. if (data.on !== oldData.on) { this.updateEventListener(); }
  45031. if (oldData.peekMode !== undefined &&
  45032. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  45033. if (!data.image || oldData.image === data.image) { return; }
  45034. el.setAttribute('material', 'pano',
  45035. typeof data.image === 'string' ? data.image : data.image.src);
  45036. },
  45037. /*
  45038. * Toggle all elements and full 360 preview of the linked page.
  45039. */
  45040. updatePeekMode: function () {
  45041. var el = this.el;
  45042. var sphereEl = this.sphereEl;
  45043. if (this.data.peekMode) {
  45044. this.hideAll();
  45045. el.getObject3D('mesh').visible = false;
  45046. sphereEl.setAttribute('visible', true);
  45047. } else {
  45048. this.showAll();
  45049. el.getObject3D('mesh').visible = true;
  45050. sphereEl.setAttribute('visible', false);
  45051. }
  45052. },
  45053. play: function () {
  45054. this.updateEventListener();
  45055. },
  45056. pause: function () {
  45057. this.removeEventListener();
  45058. },
  45059. updateEventListener: function () {
  45060. var el = this.el;
  45061. if (!el.isPlaying) { return; }
  45062. this.removeEventListener();
  45063. el.addEventListener(this.data.on, this.navigate);
  45064. },
  45065. removeEventListener: function () {
  45066. var on = this.data.on;
  45067. if (!on) { return; }
  45068. this.el.removeEventListener(on, this.navigate);
  45069. },
  45070. initVisualAspect: function () {
  45071. var el = this.el;
  45072. var semiSphereEl;
  45073. var sphereEl;
  45074. var textEl;
  45075. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  45076. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  45077. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  45078. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  45079. // Set portal.
  45080. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  45081. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  45082. // Set text that displays the link title and URL.
  45083. textEl.setAttribute('text', {
  45084. color: this.data.titleColor,
  45085. align: 'center',
  45086. font: 'kelsonsans',
  45087. value: this.data.title || this.data.href,
  45088. width: 4
  45089. });
  45090. textEl.setAttribute('position', '0 1.5 0');
  45091. el.appendChild(textEl);
  45092. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  45093. semiSphereEl.setAttribute('geometry', {
  45094. primitive: 'sphere',
  45095. radius: 1.0,
  45096. phiStart: 0,
  45097. segmentsWidth: 64,
  45098. segmentsHeight: 64,
  45099. phiLength: 180,
  45100. thetaStart: 0,
  45101. thetaLength: 360
  45102. });
  45103. semiSphereEl.setAttribute('material', {
  45104. shader: 'portal',
  45105. borderEnabled: 0.0,
  45106. pano: this.data.image,
  45107. side: 'back'
  45108. });
  45109. semiSphereEl.setAttribute('rotation', '0 180 0');
  45110. semiSphereEl.setAttribute('position', '0 0 0');
  45111. semiSphereEl.setAttribute('visible', false);
  45112. el.appendChild(semiSphereEl);
  45113. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  45114. sphereEl.setAttribute('geometry', {
  45115. primitive: 'sphere',
  45116. radius: 10,
  45117. segmentsWidth: 64,
  45118. segmentsHeight: 64
  45119. });
  45120. sphereEl.setAttribute('material', {
  45121. shader: 'portal',
  45122. borderEnabled: 0.0,
  45123. pano: this.data.image,
  45124. side: 'back'
  45125. });
  45126. sphereEl.setAttribute('visible', false);
  45127. el.appendChild(sphereEl);
  45128. this.visualAspectInitialized = true;
  45129. },
  45130. navigate: function () {
  45131. window.location = this.data.href;
  45132. },
  45133. /**
  45134. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  45135. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  45136. * from where user enters.
  45137. * 2. Place the url/title above or inside portal depending on distance to camera.
  45138. * 3. Face portal to camera when far away from user.
  45139. */
  45140. tick: (function () {
  45141. var cameraWorldPosition = new THREE.Vector3();
  45142. var elWorldPosition = new THREE.Vector3();
  45143. var quaternion = new THREE.Quaternion();
  45144. var scale = new THREE.Vector3();
  45145. return function () {
  45146. var el = this.el;
  45147. var object3D = el.object3D;
  45148. var camera = el.sceneEl.camera;
  45149. var cameraPortalOrientation;
  45150. var distance;
  45151. var textEl = this.textEl;
  45152. if (!this.data.visualAspectEnabled) { return; }
  45153. // Update matrices
  45154. object3D.updateMatrixWorld();
  45155. camera.parent.updateMatrixWorld();
  45156. camera.updateMatrixWorld();
  45157. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  45158. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  45159. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  45160. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  45161. if (distance > 20) {
  45162. // Store original orientation to be restored when the portal stops facing the camera.
  45163. if (!this.previousQuaternion) {
  45164. this.quaternionClone.copy(quaternion);
  45165. this.previousQuaternion = this.quaternionClone;
  45166. }
  45167. // If the portal is far away from the user, face portal to camera.
  45168. object3D.lookAt(cameraWorldPosition);
  45169. } else {
  45170. // When portal is close to the user/camera.
  45171. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  45172. // If user gets very close to portal, replace with holed sphere they can peek in.
  45173. if (distance < 0.5) {
  45174. // Configure text size and sphere orientation depending side user approaches portal.
  45175. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  45176. textEl.setAttribute('text', 'width', 1.5);
  45177. if (cameraPortalOrientation <= 0.0) {
  45178. textEl.setAttribute('position', '0 0 0.75');
  45179. textEl.setAttribute('rotation', '0 180 0');
  45180. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  45181. } else {
  45182. textEl.setAttribute('position', '0 0 -0.75');
  45183. textEl.setAttribute('rotation', '0 0 0');
  45184. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  45185. }
  45186. el.getObject3D('mesh').visible = false;
  45187. this.semiSphereEl.setAttribute('visible', true);
  45188. this.peekCameraPortalOrientation = cameraPortalOrientation;
  45189. } else {
  45190. // Calculate wich side the camera is approaching the camera (back / front).
  45191. // Adjust text orientation based on camera position.
  45192. if (cameraPortalOrientation <= 0.0) {
  45193. textEl.setAttribute('rotation', '0 180 0');
  45194. } else {
  45195. textEl.setAttribute('rotation', '0 0 0');
  45196. }
  45197. textEl.setAttribute('text', 'width', 5);
  45198. textEl.setAttribute('position', '0 1.5 0');
  45199. el.getObject3D('mesh').visible = true;
  45200. this.semiSphereEl.setAttribute('visible', false);
  45201. this.peekCameraPortalOrientation = undefined;
  45202. }
  45203. if (this.previousQuaternion) {
  45204. object3D.quaternion.copy(this.previousQuaternion);
  45205. this.previousQuaternion = undefined;
  45206. }
  45207. }
  45208. };
  45209. })(),
  45210. hideAll: function () {
  45211. var el = this.el;
  45212. var hiddenEls = this.hiddenEls;
  45213. var self = this;
  45214. if (hiddenEls.length > 0) { return; }
  45215. el.sceneEl.object3D.traverse(function (object) {
  45216. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  45217. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  45218. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  45219. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  45220. object.el === self.semiSphereEl) {
  45221. return;
  45222. }
  45223. object.el.setAttribute('visible', false);
  45224. hiddenEls.push(object.el);
  45225. });
  45226. },
  45227. showAll: function () {
  45228. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  45229. this.hiddenEls = [];
  45230. },
  45231. /**
  45232. * Calculate whether the camera faces the front or back face of the portal.
  45233. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  45234. */
  45235. calculateCameraPortalOrientation: (function () {
  45236. var mat4 = new THREE.Matrix4();
  45237. var cameraPosition = new THREE.Vector3();
  45238. var portalNormal = new THREE.Vector3(0, 0, 1);
  45239. var portalPosition = new THREE.Vector3(0, 0, 0);
  45240. return function () {
  45241. var el = this.el;
  45242. var camera = el.sceneEl.camera;
  45243. // Reset tmp variables.
  45244. cameraPosition.set(0, 0, 0);
  45245. portalNormal.set(0, 0, 1);
  45246. portalPosition.set(0, 0, 0);
  45247. // Apply portal orientation to the normal.
  45248. el.object3D.matrixWorld.extractRotation(mat4);
  45249. portalNormal.applyMatrix4(mat4);
  45250. // Calculate portal world position.
  45251. el.object3D.updateMatrixWorld();
  45252. el.object3D.localToWorld(portalPosition);
  45253. // Calculate camera world position.
  45254. camera.parent.parent.updateMatrixWorld();
  45255. camera.parent.updateMatrixWorld();
  45256. camera.updateMatrixWorld();
  45257. camera.localToWorld(cameraPosition);
  45258. // Calculate vector from portal to camera.
  45259. // (portal) -------> (camera)
  45260. cameraPosition.sub(portalPosition).normalize();
  45261. portalNormal.normalize();
  45262. // Side where camera approaches portal is given by sign of dot product of portal normal
  45263. // and portal to camera vectors.
  45264. return Math.sign(portalNormal.dot(cameraPosition));
  45265. };
  45266. })(),
  45267. remove: function () {
  45268. this.removeEventListener();
  45269. }
  45270. });
  45271. /* eslint-disable */
  45272. registerShader('portal', {
  45273. schema: {
  45274. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  45275. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  45276. pano: {type: 'map', is: 'uniform'},
  45277. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  45278. },
  45279. vertexShader: [
  45280. 'vec3 portalPosition;',
  45281. 'varying vec3 vWorldPosition;',
  45282. 'varying float vDistanceToCenter;',
  45283. 'varying float vDistance;',
  45284. 'void main() {',
  45285. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  45286. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  45287. 'vDistance = length(portalPosition - cameraPosition);',
  45288. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  45289. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  45290. '}'
  45291. ].join('\n'),
  45292. fragmentShader: [
  45293. '#define RECIPROCAL_PI2 0.15915494',
  45294. 'uniform sampler2D pano;',
  45295. 'uniform vec3 strokeColor;',
  45296. 'uniform vec3 backgroundColor;',
  45297. 'uniform float borderEnabled;',
  45298. 'varying float vDistanceToCenter;',
  45299. 'varying float vDistance;',
  45300. 'varying vec3 vWorldPosition;',
  45301. 'void main() {',
  45302. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  45303. 'vec2 sampleUV;',
  45304. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  45305. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  45306. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  45307. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  45308. 'gl_FragColor = vec4(strokeColor, 1.0);',
  45309. '} else {',
  45310. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  45311. '}',
  45312. '}'
  45313. ].join('\n')
  45314. });
  45315. /* eslint-enable */
  45316. },{"../core/component":124,"../core/shader":134,"../lib/three":172}],86:[function(_dereq_,module,exports){
  45317. var registerComponent = _dereq_('../core/component').registerComponent;
  45318. var THREE = _dereq_('../lib/three');
  45319. var utils = _dereq_('../utils/');
  45320. var bind = utils.bind;
  45321. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  45322. // To avoid recalculation at every mouse movement tick
  45323. var PI_2 = Math.PI / 2;
  45324. /**
  45325. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  45326. */
  45327. module.exports.Component = registerComponent('look-controls', {
  45328. dependencies: ['position', 'rotation'],
  45329. schema: {
  45330. enabled: {default: true},
  45331. hmdEnabled: {default: true},
  45332. pointerLockEnabled: {default: false},
  45333. reverseMouseDrag: {default: false},
  45334. reverseTouchDrag: {default: false},
  45335. touchEnabled: {default: true}
  45336. },
  45337. init: function () {
  45338. this.previousHMDPosition = new THREE.Vector3();
  45339. this.hmdQuaternion = new THREE.Quaternion();
  45340. this.hmdEuler = new THREE.Euler();
  45341. this.position = new THREE.Vector3();
  45342. // To save / restore camera pose
  45343. this.savedRotation = new THREE.Vector3();
  45344. this.savedPosition = new THREE.Vector3();
  45345. this.polyfillObject = new THREE.Object3D();
  45346. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  45347. this.rotation = {};
  45348. this.deltaRotation = {};
  45349. this.savedPose = null;
  45350. this.pointerLocked = false;
  45351. this.setupMouseControls();
  45352. this.bindMethods();
  45353. this.el.object3D.matrixAutoUpdate = false;
  45354. this.el.object3D.updateMatrix();
  45355. this.savedPose = {
  45356. position: new THREE.Vector3(),
  45357. rotation: new THREE.Euler()
  45358. };
  45359. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  45360. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  45361. },
  45362. update: function (oldData) {
  45363. var data = this.data;
  45364. // Disable grab cursor classes if no longer enabled.
  45365. if (data.enabled !== oldData.enabled) {
  45366. this.updateGrabCursor(data.enabled);
  45367. }
  45368. // Reset pitch and yaw if disabling HMD.
  45369. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  45370. this.pitchObject.rotation.set(0, 0, 0);
  45371. this.yawObject.rotation.set(0, 0, 0);
  45372. }
  45373. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  45374. this.removeEventListeners();
  45375. this.addEventListeners();
  45376. if (this.pointerLocked) { this.exitPointerLock(); }
  45377. }
  45378. },
  45379. tick: function (t) {
  45380. var data = this.data;
  45381. if (!data.enabled) { return; }
  45382. this.updateOrientation();
  45383. },
  45384. play: function () {
  45385. this.addEventListeners();
  45386. },
  45387. pause: function () {
  45388. this.removeEventListeners();
  45389. if (this.pointerLocked) { this.exitPointerLock(); }
  45390. },
  45391. remove: function () {
  45392. this.removeEventListeners();
  45393. if (this.pointerLocked) { this.exitPointerLock(); }
  45394. },
  45395. bindMethods: function () {
  45396. this.onMouseDown = bind(this.onMouseDown, this);
  45397. this.onMouseMove = bind(this.onMouseMove, this);
  45398. this.onMouseUp = bind(this.onMouseUp, this);
  45399. this.onTouchStart = bind(this.onTouchStart, this);
  45400. this.onTouchMove = bind(this.onTouchMove, this);
  45401. this.onTouchEnd = bind(this.onTouchEnd, this);
  45402. this.onEnterVR = bind(this.onEnterVR, this);
  45403. this.onExitVR = bind(this.onExitVR, this);
  45404. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  45405. this.onPointerLockError = bind(this.onPointerLockError, this);
  45406. },
  45407. /**
  45408. * Set up states and Object3Ds needed to store rotation data.
  45409. */
  45410. setupMouseControls: function () {
  45411. this.mouseDown = false;
  45412. this.pitchObject = new THREE.Object3D();
  45413. this.yawObject = new THREE.Object3D();
  45414. this.yawObject.position.y = 10;
  45415. this.yawObject.add(this.pitchObject);
  45416. },
  45417. /**
  45418. * Add mouse and touch event listeners to canvas.
  45419. */
  45420. addEventListeners: function () {
  45421. var sceneEl = this.el.sceneEl;
  45422. var canvasEl = sceneEl.canvas;
  45423. // Wait for canvas to load.
  45424. if (!canvasEl) {
  45425. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  45426. return;
  45427. }
  45428. // Mouse events.
  45429. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  45430. window.addEventListener('mousemove', this.onMouseMove, false);
  45431. window.addEventListener('mouseup', this.onMouseUp, false);
  45432. // Touch events.
  45433. canvasEl.addEventListener('touchstart', this.onTouchStart);
  45434. window.addEventListener('touchmove', this.onTouchMove);
  45435. window.addEventListener('touchend', this.onTouchEnd);
  45436. // sceneEl events.
  45437. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  45438. sceneEl.addEventListener('exit-vr', this.onExitVR);
  45439. // Pointer Lock events.
  45440. if (this.data.pointerLockEnabled) {
  45441. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  45442. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  45443. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  45444. }
  45445. },
  45446. /**
  45447. * Remove mouse and touch event listeners from canvas.
  45448. */
  45449. removeEventListeners: function () {
  45450. var sceneEl = this.el.sceneEl;
  45451. var canvasEl = sceneEl && sceneEl.canvas;
  45452. if (!canvasEl) { return; }
  45453. // Mouse events.
  45454. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  45455. window.removeEventListener('mousemove', this.onMouseMove);
  45456. window.removeEventListener('mouseup', this.onMouseUp);
  45457. // Touch events.
  45458. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  45459. window.removeEventListener('touchmove', this.onTouchMove);
  45460. window.removeEventListener('touchend', this.onTouchEnd);
  45461. // sceneEl events.
  45462. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  45463. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  45464. // Pointer Lock events.
  45465. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  45466. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  45467. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  45468. },
  45469. /**
  45470. * Update orientation for mobile, mouse drag, and headset.
  45471. * Mouse-drag only enabled if HMD is not active.
  45472. */
  45473. updateOrientation: (function () {
  45474. var poseMatrix = new THREE.Matrix4();
  45475. return function () {
  45476. var hmdEuler = this.hmdEuler;
  45477. var object3D = this.el.object3D;
  45478. var pitchObject = this.pitchObject;
  45479. var yawObject = this.yawObject;
  45480. var pose;
  45481. var sceneEl = this.el.sceneEl;
  45482. // WebXR API updates applies headset pose to the object3D matrixWorld internally.
  45483. // Reflect values back on position, rotation, scale so setAttribute returns expected values.
  45484. if (sceneEl.is('vr-mode') && sceneEl.hasWebXR) {
  45485. pose = sceneEl.renderer.vr.getCameraPose();
  45486. if (pose) {
  45487. poseMatrix.elements = pose.transform.matrix;
  45488. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  45489. }
  45490. } else {
  45491. object3D.updateMatrix();
  45492. }
  45493. // In VR mode, THREE is in charge of updating the camera rotation.
  45494. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  45495. // Calculate polyfilled HMD quaternion.
  45496. this.polyfillControls.update();
  45497. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  45498. // On mobile, do camera rotation with touch events and sensors.
  45499. object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  45500. object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  45501. };
  45502. })(),
  45503. /**
  45504. * Translate mouse drag into rotation.
  45505. *
  45506. * Dragging up and down rotates the camera around the X-axis (yaw).
  45507. * Dragging left and right rotates the camera around the Y-axis (pitch).
  45508. */
  45509. onMouseMove: function (event) {
  45510. var direction;
  45511. var movementX;
  45512. var movementY;
  45513. var pitchObject = this.pitchObject;
  45514. var previousMouseEvent = this.previousMouseEvent;
  45515. var yawObject = this.yawObject;
  45516. // Not dragging or not enabled.
  45517. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  45518. // Calculate delta.
  45519. if (this.pointerLocked) {
  45520. movementX = event.movementX || event.mozMovementX || 0;
  45521. movementY = event.movementY || event.mozMovementY || 0;
  45522. } else {
  45523. movementX = event.screenX - previousMouseEvent.screenX;
  45524. movementY = event.screenY - previousMouseEvent.screenY;
  45525. }
  45526. this.previousMouseEvent = event;
  45527. // Calculate rotation.
  45528. direction = this.data.reverseMouseDrag ? 1 : -1;
  45529. yawObject.rotation.y += movementX * 0.002 * direction;
  45530. pitchObject.rotation.x += movementY * 0.002 * direction;
  45531. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  45532. },
  45533. /**
  45534. * Register mouse down to detect mouse drag.
  45535. */
  45536. onMouseDown: function (evt) {
  45537. if (!this.data.enabled) { return; }
  45538. // Handle only primary button.
  45539. if (evt.button !== 0) { return; }
  45540. var sceneEl = this.el.sceneEl;
  45541. var canvasEl = sceneEl && sceneEl.canvas;
  45542. this.mouseDown = true;
  45543. this.previousMouseEvent = evt;
  45544. this.showGrabbingCursor();
  45545. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  45546. if (canvasEl.requestPointerLock) {
  45547. canvasEl.requestPointerLock();
  45548. } else if (canvasEl.mozRequestPointerLock) {
  45549. canvasEl.mozRequestPointerLock();
  45550. }
  45551. }
  45552. },
  45553. /**
  45554. * Shows grabbing cursor on scene
  45555. */
  45556. showGrabbingCursor: function () {
  45557. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  45558. },
  45559. /**
  45560. * Hides grabbing cursor on scene
  45561. */
  45562. hideGrabbingCursor: function () {
  45563. this.el.sceneEl.canvas.style.cursor = '';
  45564. },
  45565. /**
  45566. * Register mouse up to detect release of mouse drag.
  45567. */
  45568. onMouseUp: function () {
  45569. this.mouseDown = false;
  45570. this.hideGrabbingCursor();
  45571. },
  45572. /**
  45573. * Register touch down to detect touch drag.
  45574. */
  45575. onTouchStart: function (evt) {
  45576. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  45577. this.touchStart = {
  45578. x: evt.touches[0].pageX,
  45579. y: evt.touches[0].pageY
  45580. };
  45581. this.touchStarted = true;
  45582. },
  45583. /**
  45584. * Translate touch move to Y-axis rotation.
  45585. */
  45586. onTouchMove: function (evt) {
  45587. var direction;
  45588. var canvas = this.el.sceneEl.canvas;
  45589. var deltaY;
  45590. var yawObject = this.yawObject;
  45591. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  45592. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  45593. direction = this.data.reverseTouchDrag ? 1 : -1;
  45594. // Limit touch orientaion to to yaw (y axis).
  45595. yawObject.rotation.y -= deltaY * 0.5 * direction;
  45596. this.touchStart = {
  45597. x: evt.touches[0].pageX,
  45598. y: evt.touches[0].pageY
  45599. };
  45600. },
  45601. /**
  45602. * Register touch end to detect release of touch drag.
  45603. */
  45604. onTouchEnd: function () {
  45605. this.touchStarted = false;
  45606. },
  45607. /**
  45608. * Save pose.
  45609. */
  45610. onEnterVR: function () {
  45611. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  45612. this.saveCameraPose();
  45613. this.el.object3D.position.set(0, 0, 0);
  45614. this.el.object3D.updateMatrix();
  45615. },
  45616. /**
  45617. * Restore the pose.
  45618. */
  45619. onExitVR: function () {
  45620. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  45621. this.restoreCameraPose();
  45622. this.previousHMDPosition.set(0, 0, 0);
  45623. },
  45624. /**
  45625. * Update Pointer Lock state.
  45626. */
  45627. onPointerLockChange: function () {
  45628. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  45629. },
  45630. /**
  45631. * Recover from Pointer Lock error.
  45632. */
  45633. onPointerLockError: function () {
  45634. this.pointerLocked = false;
  45635. },
  45636. // Exits pointer-locked mode.
  45637. exitPointerLock: function () {
  45638. document.exitPointerLock();
  45639. this.pointerLocked = false;
  45640. },
  45641. /**
  45642. * Toggle the feature of showing/hiding the grab cursor.
  45643. */
  45644. updateGrabCursor: function (enabled) {
  45645. var sceneEl = this.el.sceneEl;
  45646. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  45647. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  45648. if (!sceneEl.canvas) {
  45649. if (enabled) {
  45650. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  45651. } else {
  45652. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  45653. }
  45654. return;
  45655. }
  45656. if (enabled) {
  45657. enableGrabCursor();
  45658. return;
  45659. }
  45660. disableGrabCursor();
  45661. },
  45662. /**
  45663. * Save camera pose before entering VR to restore later if exiting.
  45664. */
  45665. saveCameraPose: function () {
  45666. var el = this.el;
  45667. this.savedPose.position.copy(el.object3D.position);
  45668. this.savedPose.rotation.copy(el.object3D.rotation);
  45669. this.hasSavedPose = true;
  45670. },
  45671. /**
  45672. * Reset camera pose to before entering VR.
  45673. */
  45674. restoreCameraPose: function () {
  45675. var el = this.el;
  45676. var savedPose = this.savedPose;
  45677. if (!this.hasSavedPose) { return; }
  45678. // Reset camera orientation.
  45679. el.object3D.position.copy(savedPose.position);
  45680. el.object3D.rotation.copy(savedPose.rotation);
  45681. this.hasSavedPose = false;
  45682. }
  45683. });
  45684. },{"../core/component":124,"../lib/three":172,"../utils":197,"../utils/":197}],87:[function(_dereq_,module,exports){
  45685. /* global Promise */
  45686. var utils = _dereq_('../utils/');
  45687. var component = _dereq_('../core/component');
  45688. var THREE = _dereq_('../lib/three');
  45689. var shader = _dereq_('../core/shader');
  45690. var error = utils.debug('components:material:error');
  45691. var registerComponent = component.registerComponent;
  45692. var shaders = shader.shaders;
  45693. var shaderNames = shader.shaderNames;
  45694. /**
  45695. * Material component.
  45696. *
  45697. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  45698. * three.js's implementation of PBR. Another standard shading model is `flat` which
  45699. * uses MeshBasicMaterial.
  45700. */
  45701. module.exports.Component = registerComponent('material', {
  45702. schema: {
  45703. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  45704. depthTest: {default: true},
  45705. depthWrite: {default: true},
  45706. flatShading: {default: false},
  45707. npot: {default: false},
  45708. offset: {type: 'vec2', default: {x: 0, y: 0}},
  45709. opacity: {default: 1.0, min: 0.0, max: 1.0},
  45710. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  45711. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  45712. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45713. transparent: {default: false},
  45714. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  45715. visible: {default: true},
  45716. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  45717. },
  45718. init: function () {
  45719. this.material = null;
  45720. },
  45721. /**
  45722. * Update or create material.
  45723. *
  45724. * @param {object|null} oldData
  45725. */
  45726. update: function (oldData) {
  45727. var data = this.data;
  45728. if (!this.shader || data.shader !== oldData.shader) {
  45729. this.updateShader(data.shader);
  45730. }
  45731. this.shader.update(this.data);
  45732. this.updateMaterial(oldData);
  45733. },
  45734. updateSchema: function (data) {
  45735. var currentShader;
  45736. var newShader;
  45737. var schema;
  45738. var shader;
  45739. newShader = data && data.shader;
  45740. currentShader = this.oldData && this.oldData.shader;
  45741. shader = newShader || currentShader;
  45742. schema = shaders[shader] && shaders[shader].schema;
  45743. if (!schema) { error('Unknown shader schema ' + shader); }
  45744. if (currentShader && newShader === currentShader) { return; }
  45745. this.extendSchema(schema);
  45746. this.updateBehavior();
  45747. },
  45748. updateBehavior: function () {
  45749. var key;
  45750. var sceneEl = this.el.sceneEl;
  45751. var schema = this.schema;
  45752. var self = this;
  45753. var tickProperties;
  45754. function tickTime (time, delta) {
  45755. var key;
  45756. for (key in tickProperties) {
  45757. tickProperties[key] = time;
  45758. }
  45759. self.shader.update(tickProperties);
  45760. }
  45761. this.tick = undefined;
  45762. tickProperties = {};
  45763. for (key in schema) {
  45764. if (schema[key].type === 'time') {
  45765. this.tick = tickTime;
  45766. tickProperties[key] = true;
  45767. }
  45768. }
  45769. if (!sceneEl) { return; }
  45770. if (this.tick) {
  45771. sceneEl.addBehavior(this);
  45772. } else {
  45773. sceneEl.removeBehavior(this);
  45774. }
  45775. },
  45776. updateShader: function (shaderName) {
  45777. var data = this.data;
  45778. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  45779. var shaderInstance;
  45780. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  45781. // Get material from A-Frame shader.
  45782. shaderInstance = this.shader = new Shader();
  45783. shaderInstance.el = this.el;
  45784. shaderInstance.init(data);
  45785. this.setMaterial(shaderInstance.material);
  45786. this.updateSchema(data);
  45787. },
  45788. /**
  45789. * Set and update base material properties.
  45790. * Set `needsUpdate` when needed.
  45791. */
  45792. updateMaterial: function (oldData) {
  45793. var data = this.data;
  45794. var material = this.material;
  45795. var oldDataHasKeys;
  45796. // Base material properties.
  45797. material.alphaTest = data.alphaTest;
  45798. material.depthTest = data.depthTest !== false;
  45799. material.depthWrite = data.depthWrite !== false;
  45800. material.opacity = data.opacity;
  45801. material.flatShading = data.flatShading;
  45802. material.side = parseSide(data.side);
  45803. material.transparent = data.transparent !== false || data.opacity < 1.0;
  45804. material.vertexColors = parseVertexColors(data.vertexColors);
  45805. material.visible = data.visible;
  45806. material.blending = parseBlending(data.blending);
  45807. // Check if material needs update.
  45808. for (oldDataHasKeys in oldData) { break; }
  45809. if (oldDataHasKeys &&
  45810. (oldData.alphaTest !== data.alphaTest ||
  45811. oldData.side !== data.side ||
  45812. oldData.vertexColors !== data.vertexColors)) {
  45813. material.needsUpdate = true;
  45814. }
  45815. },
  45816. /**
  45817. * Remove material on remove (callback).
  45818. * Dispose of it from memory and unsubscribe from scene updates.
  45819. */
  45820. remove: function () {
  45821. var defaultMaterial = new THREE.MeshBasicMaterial();
  45822. var material = this.material;
  45823. var object3D = this.el.getObject3D('mesh');
  45824. if (object3D) { object3D.material = defaultMaterial; }
  45825. disposeMaterial(material, this.system);
  45826. },
  45827. /**
  45828. * (Re)create new material. Has side-effects of setting `this.material` and updating
  45829. * material registration in scene.
  45830. *
  45831. * @param {object} data - Material component data.
  45832. * @param {object} type - Material type to create.
  45833. * @returns {object} Material.
  45834. */
  45835. setMaterial: function (material) {
  45836. var el = this.el;
  45837. var mesh;
  45838. var system = this.system;
  45839. if (this.material) { disposeMaterial(this.material, system); }
  45840. this.material = material;
  45841. system.registerMaterial(material);
  45842. // Set on mesh. If mesh does not exist, wait for it.
  45843. mesh = el.getObject3D('mesh');
  45844. if (mesh) {
  45845. mesh.material = material;
  45846. } else {
  45847. el.addEventListener('object3dset', function waitForMesh (evt) {
  45848. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  45849. el.getObject3D('mesh').material = material;
  45850. el.removeEventListener('object3dset', waitForMesh);
  45851. });
  45852. }
  45853. }
  45854. });
  45855. /**
  45856. * Return a three.js constant determining which material face sides to render
  45857. * based on the side parameter (passed as a component property).
  45858. *
  45859. * @param {string} [side=front] - `front`, `back`, or `double`.
  45860. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  45861. */
  45862. function parseSide (side) {
  45863. switch (side) {
  45864. case 'back': {
  45865. return THREE.BackSide;
  45866. }
  45867. case 'double': {
  45868. return THREE.DoubleSide;
  45869. }
  45870. default: {
  45871. // Including case `front`.
  45872. return THREE.FrontSide;
  45873. }
  45874. }
  45875. }
  45876. /**
  45877. * Return a three.js constant determining vertex coloring.
  45878. */
  45879. function parseVertexColors (coloring) {
  45880. switch (coloring) {
  45881. case 'face': {
  45882. return THREE.FaceColors;
  45883. }
  45884. case 'vertex': {
  45885. return THREE.VertexColors;
  45886. }
  45887. default: {
  45888. return THREE.NoColors;
  45889. }
  45890. }
  45891. }
  45892. /**
  45893. * Return a three.js constant determining blending
  45894. *
  45895. * @param {string} [blending=normal]
  45896. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  45897. * @returns {number}
  45898. */
  45899. function parseBlending (blending) {
  45900. switch (blending) {
  45901. case 'none': {
  45902. return THREE.NoBlending;
  45903. }
  45904. case 'additive': {
  45905. return THREE.AdditiveBlending;
  45906. }
  45907. case 'subtractive': {
  45908. return THREE.SubtractiveBlending;
  45909. }
  45910. case 'multiply': {
  45911. return THREE.MultiplyBlending;
  45912. }
  45913. default: {
  45914. return THREE.NormalBlending;
  45915. }
  45916. }
  45917. }
  45918. /**
  45919. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  45920. */
  45921. function disposeMaterial (material, system) {
  45922. material.dispose();
  45923. system.unregisterMaterial(material);
  45924. }
  45925. },{"../core/component":124,"../core/shader":134,"../lib/three":172,"../utils/":197}],88:[function(_dereq_,module,exports){
  45926. var debug = _dereq_('../utils/debug');
  45927. var registerComponent = _dereq_('../core/component').registerComponent;
  45928. var THREE = _dereq_('../lib/three');
  45929. var warn = debug('components:obj-model:warn');
  45930. module.exports.Component = registerComponent('obj-model', {
  45931. schema: {
  45932. mtl: {type: 'model'},
  45933. obj: {type: 'model'}
  45934. },
  45935. init: function () {
  45936. var self = this;
  45937. this.model = null;
  45938. this.objLoader = new THREE.OBJLoader();
  45939. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  45940. // Allow cross-origin images to be loaded.
  45941. this.mtlLoader.crossOrigin = '';
  45942. this.el.addEventListener('componentinitialized', function (evt) {
  45943. if (!self.model) { return; }
  45944. if (evt.detail.name !== 'material') { return; }
  45945. self.applyMaterial();
  45946. });
  45947. },
  45948. update: function () {
  45949. var data = this.data;
  45950. if (!data.obj) { return; }
  45951. this.resetMesh();
  45952. this.loadObj(data.obj, data.mtl);
  45953. },
  45954. remove: function () {
  45955. if (!this.model) { return; }
  45956. this.resetMesh();
  45957. },
  45958. resetMesh: function () {
  45959. this.el.removeObject3D('mesh');
  45960. },
  45961. loadObj: function (objUrl, mtlUrl) {
  45962. var self = this;
  45963. var el = this.el;
  45964. var mtlLoader = this.mtlLoader;
  45965. var objLoader = this.objLoader;
  45966. var rendererSystem = this.el.sceneEl.systems.renderer;
  45967. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  45968. if (mtlUrl) {
  45969. // .OBJ with an .MTL.
  45970. if (el.hasAttribute('material')) {
  45971. warn('Material component properties are ignored when a .MTL is provided');
  45972. }
  45973. mtlLoader.setResourcePath(BASE_PATH);
  45974. mtlLoader.load(mtlUrl, function (materials) {
  45975. materials.preload();
  45976. objLoader.setMaterials(materials);
  45977. objLoader.load(objUrl, function (objModel) {
  45978. self.model = objModel;
  45979. self.model.traverse(function (object) {
  45980. if (object.isMesh) {
  45981. var material = object.material;
  45982. if (material.color) rendererSystem.applyColorCorrection(material.color);
  45983. if (material.map) rendererSystem.applyColorCorrection(material.map);
  45984. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  45985. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  45986. }
  45987. });
  45988. el.setObject3D('mesh', objModel);
  45989. el.emit('model-loaded', {format: 'obj', model: objModel});
  45990. });
  45991. });
  45992. return;
  45993. }
  45994. // .OBJ only.
  45995. objLoader.load(objUrl, function loadObjOnly (objModel) {
  45996. self.model = objModel;
  45997. self.applyMaterial();
  45998. el.setObject3D('mesh', objModel);
  45999. el.emit('model-loaded', {format: 'obj', model: objModel});
  46000. });
  46001. },
  46002. /**
  46003. * Apply material from material component recursively.
  46004. */
  46005. applyMaterial: function () {
  46006. var material = this.el.components.material;
  46007. if (!material) { return; }
  46008. this.model.traverse(function (child) {
  46009. if (child instanceof THREE.Mesh) {
  46010. child.material = material.material;
  46011. }
  46012. });
  46013. }
  46014. });
  46015. },{"../core/component":124,"../lib/three":172,"../utils/debug":193}],89:[function(_dereq_,module,exports){
  46016. var registerComponent = _dereq_('../core/component').registerComponent;
  46017. var bind = _dereq_('../utils/bind');
  46018. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46019. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46020. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46021. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46022. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  46023. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  46024. /**
  46025. * Oculus Go controls.
  46026. * Interface with Oculus Go controller and map Gamepad events to
  46027. * controller buttons: trackpad, trigger
  46028. * Load a controller model and highlight the pressed buttons.
  46029. */
  46030. module.exports.Component = registerComponent('oculus-go-controls', {
  46031. schema: {
  46032. hand: {default: ''}, // This informs the degenerate arm model.
  46033. buttonColor: {type: 'color', default: '#FFFFFF'},
  46034. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  46035. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  46036. model: {default: true},
  46037. orientationOffset: {type: 'vec3'},
  46038. armModel: {default: true}
  46039. },
  46040. /**
  46041. * Button IDs:
  46042. * 0 - trackpad
  46043. * 1 - trigger
  46044. */
  46045. mapping: {
  46046. axes: {trackpad: [0, 1]},
  46047. buttons: ['trackpad', 'trigger']
  46048. },
  46049. bindMethods: function () {
  46050. this.onModelLoaded = bind(this.onModelLoaded, this);
  46051. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46052. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46053. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46054. this.onAxisMoved = bind(this.onAxisMoved, this);
  46055. },
  46056. init: function () {
  46057. var self = this;
  46058. this.onButtonChanged = bind(this.onButtonChanged, this);
  46059. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46060. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46061. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46062. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46063. this.controllerPresent = false;
  46064. this.lastControllerCheck = 0;
  46065. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46066. this.bindMethods();
  46067. },
  46068. addEventListeners: function () {
  46069. var el = this.el;
  46070. el.addEventListener('buttonchanged', this.onButtonChanged);
  46071. el.addEventListener('buttondown', this.onButtonDown);
  46072. el.addEventListener('buttonup', this.onButtonUp);
  46073. el.addEventListener('touchstart', this.onButtonTouchStart);
  46074. el.addEventListener('touchend', this.onButtonTouchEnd);
  46075. el.addEventListener('model-loaded', this.onModelLoaded);
  46076. el.addEventListener('axismove', this.onAxisMoved);
  46077. this.controllerEventsActive = true;
  46078. },
  46079. removeEventListeners: function () {
  46080. var el = this.el;
  46081. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46082. el.removeEventListener('buttondown', this.onButtonDown);
  46083. el.removeEventListener('buttonup', this.onButtonUp);
  46084. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46085. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46086. el.removeEventListener('model-loaded', this.onModelLoaded);
  46087. el.removeEventListener('axismove', this.onAxisMoved);
  46088. this.controllerEventsActive = false;
  46089. },
  46090. checkIfControllerPresent: function () {
  46091. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46092. this.data.hand ? {hand: this.data.hand} : {});
  46093. },
  46094. play: function () {
  46095. this.checkIfControllerPresent();
  46096. this.addControllersUpdateListener();
  46097. },
  46098. pause: function () {
  46099. this.removeEventListeners();
  46100. this.removeControllersUpdateListener();
  46101. },
  46102. injectTrackedControls: function () {
  46103. var el = this.el;
  46104. var data = this.data;
  46105. el.setAttribute('tracked-controls', {
  46106. armModel: data.armModel,
  46107. hand: data.hand,
  46108. idPrefix: GAMEPAD_ID_PREFIX,
  46109. orientationOffset: data.orientationOffset
  46110. });
  46111. if (!this.data.model) { return; }
  46112. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  46113. },
  46114. addControllersUpdateListener: function () {
  46115. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46116. },
  46117. removeControllersUpdateListener: function () {
  46118. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46119. },
  46120. onControllersUpdate: function () {
  46121. this.checkIfControllerPresent();
  46122. },
  46123. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  46124. onModelLoaded: function (evt) {
  46125. var controllerObject3D = evt.detail.model;
  46126. var buttonMeshes;
  46127. if (!this.data.model) { return; }
  46128. buttonMeshes = this.buttonMeshes = {};
  46129. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  46130. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  46131. },
  46132. onButtonChanged: function (evt) {
  46133. var button = this.mapping.buttons[evt.detail.id];
  46134. if (!button) return;
  46135. // Pass along changed event with button state, using button mapping for convenience.
  46136. this.el.emit(button + 'changed', evt.detail.state);
  46137. },
  46138. onAxisMoved: function (evt) {
  46139. emitIfAxesChanged(this, this.mapping.axes, evt);
  46140. },
  46141. updateModel: function (buttonName, evtName) {
  46142. if (!this.data.model) { return; }
  46143. this.updateButtonModel(buttonName, evtName);
  46144. },
  46145. updateButtonModel: function (buttonName, state) {
  46146. var buttonMeshes = this.buttonMeshes;
  46147. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46148. var color;
  46149. var button;
  46150. switch (state) {
  46151. case 'down':
  46152. color = this.data.buttonHighlightColor;
  46153. break;
  46154. case 'touchstart':
  46155. color = this.data.buttonTouchedColor;
  46156. break;
  46157. default:
  46158. color = this.data.buttonColor;
  46159. }
  46160. button = buttonMeshes[buttonName];
  46161. button.material.color.set(color);
  46162. this.rendererSystem.applyColorCorrection(button.material.color);
  46163. }
  46164. });
  46165. },{"../core/component":124,"../utils/bind":191,"../utils/tracked-controls":205}],90:[function(_dereq_,module,exports){
  46166. var bind = _dereq_('../utils/bind');
  46167. var registerComponent = _dereq_('../core/component').registerComponent;
  46168. var THREE = _dereq_('../lib/three');
  46169. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46170. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46171. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46172. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46173. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  46174. var TOUCH_CONTROLLER_MODEL_URL = {
  46175. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  46176. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  46177. };
  46178. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  46179. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  46180. var RAY_ORIGIN = {
  46181. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  46182. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  46183. };
  46184. /**
  46185. * Oculus Touch controls.
  46186. * Interface with Oculus Touch controllers and map Gamepad events to
  46187. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  46188. * Load a controller model and highlight the pressed buttons.
  46189. */
  46190. module.exports.Component = registerComponent('oculus-touch-controls', {
  46191. schema: {
  46192. hand: {default: 'left'},
  46193. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  46194. buttonTouchColor: {type: 'color', default: '#8AB'},
  46195. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  46196. model: {default: true},
  46197. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  46198. },
  46199. /**
  46200. * Button IDs:
  46201. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  46202. * 1 - trigger (with analog value, which goes up to 1)
  46203. * 2 - grip (with analog value, which goes up to 1)
  46204. * 3 - X (left) or A (right)
  46205. * 4 - Y (left) or B (right)
  46206. * 5 - surface (touch only)
  46207. */
  46208. mapping: {
  46209. left: {
  46210. axes: {thumbstick: [0, 1]},
  46211. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  46212. },
  46213. right: {
  46214. axes: {thumbstick: [0, 1]},
  46215. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  46216. }
  46217. },
  46218. bindMethods: function () {
  46219. this.onModelLoaded = bind(this.onModelLoaded, this);
  46220. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46221. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46222. this.onAxisMoved = bind(this.onAxisMoved, this);
  46223. },
  46224. init: function () {
  46225. var self = this;
  46226. this.onButtonChanged = bind(this.onButtonChanged, this);
  46227. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  46228. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  46229. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  46230. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  46231. this.controllerPresent = false;
  46232. this.lastControllerCheck = 0;
  46233. this.previousButtonValues = {};
  46234. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46235. this.bindMethods();
  46236. },
  46237. addEventListeners: function () {
  46238. var el = this.el;
  46239. el.addEventListener('buttonchanged', this.onButtonChanged);
  46240. el.addEventListener('buttondown', this.onButtonDown);
  46241. el.addEventListener('buttonup', this.onButtonUp);
  46242. el.addEventListener('touchstart', this.onButtonTouchStart);
  46243. el.addEventListener('touchend', this.onButtonTouchEnd);
  46244. el.addEventListener('axismove', this.onAxisMoved);
  46245. el.addEventListener('model-loaded', this.onModelLoaded);
  46246. this.controllerEventsActive = true;
  46247. },
  46248. removeEventListeners: function () {
  46249. var el = this.el;
  46250. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46251. el.removeEventListener('buttondown', this.onButtonDown);
  46252. el.removeEventListener('buttonup', this.onButtonUp);
  46253. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46254. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46255. el.removeEventListener('axismove', this.onAxisMoved);
  46256. el.removeEventListener('model-loaded', this.onModelLoaded);
  46257. this.controllerEventsActive = false;
  46258. },
  46259. checkIfControllerPresent: function () {
  46260. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  46261. hand: this.data.hand
  46262. });
  46263. },
  46264. play: function () {
  46265. this.checkIfControllerPresent();
  46266. this.addControllersUpdateListener();
  46267. },
  46268. pause: function () {
  46269. this.removeEventListeners();
  46270. this.removeControllersUpdateListener();
  46271. },
  46272. loadModel: function () {
  46273. var data = this.data;
  46274. if (!data.model) { return; }
  46275. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  46276. },
  46277. injectTrackedControls: function () {
  46278. var data = this.data;
  46279. this.el.setAttribute('tracked-controls', {
  46280. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  46281. controller: 0,
  46282. hand: data.hand,
  46283. orientationOffset: data.orientationOffset
  46284. });
  46285. this.loadModel();
  46286. },
  46287. addControllersUpdateListener: function () {
  46288. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46289. },
  46290. removeControllersUpdateListener: function () {
  46291. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46292. },
  46293. onControllersUpdate: function () {
  46294. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  46295. this.checkIfControllerPresent();
  46296. },
  46297. onButtonChanged: function (evt) {
  46298. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  46299. var buttonMeshes = this.buttonMeshes;
  46300. var analogValue;
  46301. if (!button) { return; }
  46302. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  46303. // Update trigger and/or grip meshes, if any.
  46304. if (buttonMeshes) {
  46305. if (button === 'trigger' && buttonMeshes.trigger) {
  46306. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  46307. }
  46308. if (button === 'grip' && buttonMeshes.grip) {
  46309. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  46310. }
  46311. }
  46312. // Pass along changed event with button state, using the buttom mapping for convenience.
  46313. this.el.emit(button + 'changed', evt.detail.state);
  46314. },
  46315. onModelLoaded: function (evt) {
  46316. var controllerObject3D = evt.detail.model;
  46317. var buttonMeshes;
  46318. if (!this.data.model) { return; }
  46319. buttonMeshes = this.buttonMeshes = {};
  46320. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  46321. this.originalXPositionGrip = buttonMeshes.grip.position.x;
  46322. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  46323. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  46324. this.originalXRotationTrigger = buttonMeshes.trigger.rotation.x;
  46325. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  46326. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  46327. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  46328. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  46329. // Offset pivot point
  46330. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  46331. this.el.emit('controllermodelready', {
  46332. name: 'oculus-touch-controls',
  46333. model: this.data.model,
  46334. rayOrigin: RAY_ORIGIN[this.data.hand]
  46335. });
  46336. },
  46337. onAxisMoved: function (evt) {
  46338. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  46339. },
  46340. updateModel: function (buttonName, evtName) {
  46341. if (!this.data.model) { return; }
  46342. this.updateButtonModel(buttonName, evtName);
  46343. },
  46344. updateButtonModel: function (buttonName, state) {
  46345. var button;
  46346. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  46347. var buttonMeshes = this.buttonMeshes;
  46348. if (!this.data.model) { return; }
  46349. if (buttonMeshes && buttonMeshes[buttonName]) {
  46350. button = buttonMeshes[buttonName];
  46351. button.material.color.set(color);
  46352. this.rendererSystem.applyColorCorrection(button.material.color);
  46353. }
  46354. }
  46355. });
  46356. },{"../core/component":124,"../lib/three":172,"../utils/bind":191,"../utils/tracked-controls":205}],91:[function(_dereq_,module,exports){
  46357. var registerComponent = _dereq_('../core/component').registerComponent;
  46358. module.exports.Component = registerComponent('position', {
  46359. schema: {type: 'vec3'},
  46360. update: function () {
  46361. var object3D = this.el.object3D;
  46362. var data = this.data;
  46363. object3D.position.set(data.x, data.y, data.z);
  46364. },
  46365. remove: function () {
  46366. // Pretty much for mixins.
  46367. this.el.object3D.position.set(0, 0, 0);
  46368. }
  46369. });
  46370. },{"../core/component":124}],92:[function(_dereq_,module,exports){
  46371. /* global MutationObserver */
  46372. var registerComponent = _dereq_('../core/component').registerComponent;
  46373. var THREE = _dereq_('../lib/three');
  46374. var utils = _dereq_('../utils/');
  46375. var warn = utils.debug('components:raycaster:warn');
  46376. // Defines selectors that should be 'safe' for the MutationObserver used to
  46377. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  46378. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  46379. // reliably detected and are therefore disallowed.
  46380. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  46381. // Configuration for the MutationObserver used to refresh the whitelist.
  46382. // Listens for addition/removal of elements and attributes within the scene.
  46383. var OBSERVER_CONFIG = {
  46384. childList: true,
  46385. attributes: true,
  46386. subtree: true
  46387. };
  46388. var EVENTS = {
  46389. INTERSECT: 'raycaster-intersected',
  46390. INTERSECTION: 'raycaster-intersection',
  46391. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  46392. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  46393. };
  46394. /**
  46395. * Raycaster component.
  46396. *
  46397. * Pass options to three.js Raycaster including which objects to test.
  46398. * Poll for intersections.
  46399. * Emit event on origin entity and on target entity on intersect.
  46400. *
  46401. * @member {array} intersectedEls - List of currently intersected entities.
  46402. * @member {array} objects - Cached list of meshes to intersect.
  46403. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  46404. * @member {object} raycaster - three.js Raycaster.
  46405. */
  46406. module.exports.Component = registerComponent('raycaster', {
  46407. schema: {
  46408. autoRefresh: {default: true},
  46409. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  46410. enabled: {default: true},
  46411. far: {default: 1000},
  46412. interval: {default: 0},
  46413. near: {default: 0},
  46414. objects: {default: ''},
  46415. origin: {type: 'vec3'},
  46416. showLine: {default: false},
  46417. useWorldCoordinates: {default: false}
  46418. },
  46419. multiple: true,
  46420. init: function () {
  46421. this.clearedIntersectedEls = [];
  46422. this.unitLineEndVec3 = new THREE.Vector3();
  46423. this.intersectedEls = [];
  46424. this.intersections = [];
  46425. this.newIntersectedEls = [];
  46426. this.newIntersections = [];
  46427. this.objects = [];
  46428. this.prevCheckTime = undefined;
  46429. this.prevIntersectedEls = [];
  46430. this.rawIntersections = [];
  46431. this.raycaster = new THREE.Raycaster();
  46432. this.updateOriginDirection();
  46433. this.setDirty = this.setDirty.bind(this);
  46434. this.updateLine = this.updateLine.bind(this);
  46435. this.observer = new MutationObserver(this.setDirty);
  46436. this.dirty = true;
  46437. this.lineEndVec3 = new THREE.Vector3();
  46438. this.otherLineEndVec3 = new THREE.Vector3();
  46439. this.lineData = {end: this.lineEndVec3};
  46440. this.getIntersection = this.getIntersection.bind(this);
  46441. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  46442. this.intersectedClearedDetail = {el: this.el};
  46443. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  46444. this.intersectionDetail = {};
  46445. },
  46446. /**
  46447. * Create or update raycaster object.
  46448. */
  46449. update: function (oldData) {
  46450. var data = this.data;
  46451. var el = this.el;
  46452. var raycaster = this.raycaster;
  46453. // Set raycaster properties.
  46454. raycaster.far = data.far;
  46455. raycaster.near = data.near;
  46456. // Draw line.
  46457. if (data.showLine &&
  46458. (data.far !== oldData.far || data.origin !== oldData.origin ||
  46459. data.direction !== oldData.direction || !oldData.showLine)) {
  46460. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  46461. // adjust line length.
  46462. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  46463. this.drawLine();
  46464. }
  46465. if (!data.showLine && oldData.showLine) {
  46466. el.removeAttribute('line');
  46467. }
  46468. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  46469. warn('[raycaster] Selector "' + data.objects +
  46470. '" may not update automatically with DOM changes.');
  46471. }
  46472. if (!data.objects) {
  46473. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  46474. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  46475. 'e.g., raycaster="objects: [data-raycastable]".');
  46476. }
  46477. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  46478. data.autoRefresh
  46479. ? this.addEventListeners()
  46480. : this.removeEventListeners();
  46481. }
  46482. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  46483. this.setDirty();
  46484. },
  46485. play: function () {
  46486. this.addEventListeners();
  46487. },
  46488. pause: function () {
  46489. this.removeEventListeners();
  46490. },
  46491. remove: function () {
  46492. if (this.data.showLine) {
  46493. this.el.removeAttribute('line');
  46494. }
  46495. this.clearAllIntersections();
  46496. },
  46497. addEventListeners: function () {
  46498. if (!this.data.autoRefresh) { return; }
  46499. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  46500. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  46501. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  46502. },
  46503. removeEventListeners: function () {
  46504. this.observer.disconnect();
  46505. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  46506. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  46507. },
  46508. /**
  46509. * Mark the object list as dirty, to be refreshed before next raycast.
  46510. */
  46511. setDirty: function () {
  46512. this.dirty = true;
  46513. },
  46514. /**
  46515. * Update list of objects to test for intersection.
  46516. */
  46517. refreshObjects: function () {
  46518. var data = this.data;
  46519. var els;
  46520. // If objects not defined, intersect with everything.
  46521. els = data.objects
  46522. ? this.el.sceneEl.querySelectorAll(data.objects)
  46523. : this.el.sceneEl.querySelectorAll('*');
  46524. this.objects = this.flattenObject3DMaps(els);
  46525. this.dirty = false;
  46526. },
  46527. /**
  46528. * Check for intersections and cleared intersections on an interval.
  46529. */
  46530. tick: function (time) {
  46531. var data = this.data;
  46532. var prevCheckTime = this.prevCheckTime;
  46533. if (!data.enabled) { return; }
  46534. // Only check for intersection if interval time has passed.
  46535. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  46536. // Update check time.
  46537. this.prevCheckTime = time;
  46538. this.checkIntersections();
  46539. },
  46540. /**
  46541. * Raycast for intersections and emit events for current and cleared inersections.
  46542. */
  46543. checkIntersections: function () {
  46544. var clearedIntersectedEls = this.clearedIntersectedEls;
  46545. var el = this.el;
  46546. var data = this.data;
  46547. var i;
  46548. var intersectedEls = this.intersectedEls;
  46549. var intersection;
  46550. var intersections = this.intersections;
  46551. var newIntersectedEls = this.newIntersectedEls;
  46552. var newIntersections = this.newIntersections;
  46553. var prevIntersectedEls = this.prevIntersectedEls;
  46554. var rawIntersections = this.rawIntersections;
  46555. // Refresh the object whitelist if needed.
  46556. if (this.dirty) { this.refreshObjects(); }
  46557. // Store old previously intersected entities.
  46558. copyArray(this.prevIntersectedEls, this.intersectedEls);
  46559. // Raycast.
  46560. this.updateOriginDirection();
  46561. rawIntersections.length = 0;
  46562. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  46563. // Only keep intersections against objects that have a reference to an entity.
  46564. intersections.length = 0;
  46565. intersectedEls.length = 0;
  46566. for (i = 0; i < rawIntersections.length; i++) {
  46567. intersection = rawIntersections[i];
  46568. // Don't intersect with own line.
  46569. if (data.showLine && intersection.object === el.getObject3D('line')) {
  46570. continue;
  46571. }
  46572. if (intersection.object.el) {
  46573. intersections.push(intersection);
  46574. intersectedEls.push(intersection.object.el);
  46575. }
  46576. }
  46577. // Get newly intersected entities.
  46578. newIntersections.length = 0;
  46579. newIntersectedEls.length = 0;
  46580. for (i = 0; i < intersections.length; i++) {
  46581. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  46582. newIntersections.push(intersections[i]);
  46583. newIntersectedEls.push(intersections[i].object.el);
  46584. }
  46585. }
  46586. // Emit intersection cleared on both entities per formerly intersected entity.
  46587. clearedIntersectedEls.length = 0;
  46588. for (i = 0; i < prevIntersectedEls.length; i++) {
  46589. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  46590. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  46591. this.intersectedClearedDetail);
  46592. clearedIntersectedEls.push(prevIntersectedEls[i]);
  46593. }
  46594. if (clearedIntersectedEls.length) {
  46595. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  46596. }
  46597. // Emit intersected on intersected entity per intersected entity.
  46598. for (i = 0; i < newIntersectedEls.length; i++) {
  46599. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  46600. }
  46601. // Emit all intersections at once on raycasting entity.
  46602. if (newIntersections.length) {
  46603. this.intersectionDetail.els = newIntersectedEls;
  46604. this.intersectionDetail.intersections = newIntersections;
  46605. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  46606. }
  46607. // Update line length.
  46608. if (data.showLine) { setTimeout(this.updateLine); }
  46609. },
  46610. updateLine: function () {
  46611. var el = this.el;
  46612. var intersections = this.intersections;
  46613. var lineLength;
  46614. if (intersections.length) {
  46615. if (intersections[0].object.el === el && intersections[1]) {
  46616. lineLength = intersections[1].distance;
  46617. } else {
  46618. lineLength = intersections[0].distance;
  46619. }
  46620. }
  46621. this.drawLine(lineLength);
  46622. },
  46623. /**
  46624. * Return the most recent intersection details for a given entity, if any.
  46625. * @param {AEntity} el
  46626. * @return {Object}
  46627. */
  46628. getIntersection: function (el) {
  46629. var i;
  46630. var intersection;
  46631. for (i = 0; i < this.intersections.length; i++) {
  46632. intersection = this.intersections[i];
  46633. if (intersection.object.el === el) { return intersection; }
  46634. }
  46635. return null;
  46636. },
  46637. /**
  46638. * Update origin and direction of raycaster using entity transforms and supplied origin or
  46639. * direction offsets.
  46640. */
  46641. updateOriginDirection: (function () {
  46642. var direction = new THREE.Vector3();
  46643. var originVec3 = new THREE.Vector3();
  46644. // Closure to make quaternion/vector3 objects private.
  46645. return function updateOriginDirection () {
  46646. var el = this.el;
  46647. var data = this.data;
  46648. if (data.useWorldCoordinates) {
  46649. this.raycaster.set(data.origin, data.direction);
  46650. return;
  46651. }
  46652. // Grab the position and rotation. (As a side effect, this updates el.object3D.matrixWorld.)
  46653. el.object3D.getWorldPosition(originVec3);
  46654. // If non-zero origin, translate the origin into world space.
  46655. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  46656. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  46657. }
  46658. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  46659. // provide. Apply the offset to the direction, then rotation from the object,
  46660. // and normalize.
  46661. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  46662. // Apply offset and direction, in world coordinates.
  46663. this.raycaster.set(originVec3, direction);
  46664. };
  46665. })(),
  46666. /**
  46667. * Create or update line to give raycaster visual representation.
  46668. * Customize the line through through line component.
  46669. * We draw the line in the raycaster component to customize the line to the
  46670. * raycaster's origin, direction, and far.
  46671. *
  46672. * Unlike the raycaster, we create the line as a child of the object. The line will
  46673. * be affected by the transforms of the objects, so we don't have to calculate transforms
  46674. * like we do with the raycaster.
  46675. *
  46676. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  46677. * point. If not provided, length will default to the max length, `raycaster.far`.
  46678. */
  46679. drawLine: function (length) {
  46680. var data = this.data;
  46681. var el = this.el;
  46682. var endVec3;
  46683. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  46684. endVec3 = this.lineData.end === this.lineEndVec3
  46685. ? this.otherLineEndVec3
  46686. : this.lineEndVec3;
  46687. // Treat Infinity as 1000m for the line.
  46688. if (length === undefined) {
  46689. length = data.far === Infinity ? 1000 : data.far;
  46690. }
  46691. // Update the length of the line if given. `unitLineEndVec3` is the direction
  46692. // given by data.direction, then we apply a scalar to give it a length.
  46693. this.lineData.start = data.origin;
  46694. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  46695. el.setAttribute('line', this.lineData);
  46696. },
  46697. /**
  46698. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  46699. * Children are flattened by one level, removing the THREE.Group wrapper,
  46700. * so that non-recursive raycasting remains useful.
  46701. *
  46702. * Only push children defined as component attachemnts (e.g., setObject3D),
  46703. * NOT actual children in the scene graph hierarchy.
  46704. *
  46705. * @param {Array<Element>} els
  46706. * @return {Array<THREE.Object3D>}
  46707. */
  46708. flattenObject3DMaps: function (els) {
  46709. var key;
  46710. var i;
  46711. var objects = this.objects;
  46712. // Push meshes and other attachments onto list of objects to intersect.
  46713. objects.length = 0;
  46714. for (i = 0; i < els.length; i++) {
  46715. if (els[i].isEntity && els[i].object3D) {
  46716. for (key in els[i].object3DMap) {
  46717. objects.push(els[i].getObject3D(key));
  46718. }
  46719. }
  46720. }
  46721. return objects;
  46722. },
  46723. clearAllIntersections: function () {
  46724. var i;
  46725. for (i = 0; i < this.intersectedEls.length; i++) {
  46726. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  46727. this.intersectedClearedDetail);
  46728. }
  46729. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  46730. this.intersectedEls.length = 0;
  46731. this.intersections.length = 0;
  46732. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  46733. }
  46734. });
  46735. /**
  46736. * Copy contents of one array to another without allocating new array.
  46737. */
  46738. function copyArray (a, b) {
  46739. var i;
  46740. a.length = b.length;
  46741. for (i = 0; i < b.length; i++) {
  46742. a[i] = b[i];
  46743. }
  46744. }
  46745. },{"../core/component":124,"../lib/three":172,"../utils/":197}],93:[function(_dereq_,module,exports){
  46746. var degToRad = _dereq_('../lib/three').Math.degToRad;
  46747. var registerComponent = _dereq_('../core/component').registerComponent;
  46748. module.exports.Component = registerComponent('rotation', {
  46749. schema: {type: 'vec3'},
  46750. /**
  46751. * Updates object3D rotation.
  46752. */
  46753. update: function () {
  46754. var data = this.data;
  46755. var object3D = this.el.object3D;
  46756. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  46757. object3D.rotation.order = 'YXZ';
  46758. },
  46759. remove: function () {
  46760. // Pretty much for mixins.
  46761. this.el.object3D.rotation.set(0, 0, 0);
  46762. }
  46763. });
  46764. },{"../core/component":124,"../lib/three":172}],94:[function(_dereq_,module,exports){
  46765. var registerComponent = _dereq_('../core/component').registerComponent;
  46766. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  46767. var zeroScale = 0.00001;
  46768. module.exports.Component = registerComponent('scale', {
  46769. schema: {
  46770. type: 'vec3',
  46771. default: {x: 1, y: 1, z: 1}
  46772. },
  46773. update: function () {
  46774. var data = this.data;
  46775. var object3D = this.el.object3D;
  46776. var x = data.x === 0 ? zeroScale : data.x;
  46777. var y = data.y === 0 ? zeroScale : data.y;
  46778. var z = data.z === 0 ? zeroScale : data.z;
  46779. object3D.scale.set(x, y, z);
  46780. },
  46781. remove: function () {
  46782. // Pretty much for mixins.
  46783. this.el.object3D.scale.set(1, 1, 1);
  46784. }
  46785. });
  46786. },{"../core/component":124}],95:[function(_dereq_,module,exports){
  46787. /* global THREE */
  46788. var register = _dereq_('../../core/component').registerComponent;
  46789. module.exports.Component = register('background', {
  46790. schema: {
  46791. color: {type: 'color', default: 'black'},
  46792. transparent: {default: false}
  46793. },
  46794. update: function () {
  46795. var data = this.data;
  46796. var object3D = this.el.object3D;
  46797. if (data.transparent) {
  46798. object3D.background = null;
  46799. return;
  46800. }
  46801. object3D.background = new THREE.Color(data.color);
  46802. }
  46803. });
  46804. },{"../../core/component":124}],96:[function(_dereq_,module,exports){
  46805. var register = _dereq_('../../core/component').registerComponent;
  46806. module.exports.Component = register('debug', {
  46807. schema: {default: true}
  46808. });
  46809. },{"../../core/component":124}],97:[function(_dereq_,module,exports){
  46810. var registerComponent = _dereq_('../../core/component').registerComponent;
  46811. /**
  46812. * Component to embed an a-frame scene within the layout of a 2D page.
  46813. */
  46814. module.exports.Component = registerComponent('embedded', {
  46815. dependencies: ['vr-mode-ui'],
  46816. schema: {default: true},
  46817. update: function () {
  46818. var sceneEl = this.el;
  46819. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  46820. if (this.data === true) {
  46821. if (enterVREl) { enterVREl.classList.add('embedded'); }
  46822. sceneEl.removeFullScreenStyles();
  46823. } else {
  46824. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  46825. sceneEl.addFullScreenStyles();
  46826. }
  46827. }
  46828. });
  46829. },{"../../core/component":124}],98:[function(_dereq_,module,exports){
  46830. var register = _dereq_('../../core/component').registerComponent;
  46831. var THREE = _dereq_('../../lib/three');
  46832. var debug = _dereq_('../../utils/debug');
  46833. var warn = debug('components:fog:warn');
  46834. /**
  46835. * Fog component.
  46836. * Applies only to the scene entity.
  46837. */
  46838. module.exports.Component = register('fog', {
  46839. schema: {
  46840. color: {type: 'color', default: '#000'},
  46841. density: {default: 0.00025},
  46842. far: {default: 1000, min: 0},
  46843. near: {default: 1, min: 0},
  46844. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  46845. },
  46846. update: function () {
  46847. var data = this.data;
  46848. var el = this.el;
  46849. var fog = this.el.object3D.fog;
  46850. if (!el.isScene) {
  46851. warn('Fog component can only be applied to <a-scene>');
  46852. return;
  46853. }
  46854. // (Re)create fog if fog doesn't exist or fog type changed.
  46855. if (!fog || data.type !== fog.name) {
  46856. el.object3D.fog = getFog(data);
  46857. el.systems.material.updateMaterials();
  46858. return;
  46859. }
  46860. // Fog data changed. Update fog.
  46861. Object.keys(this.schema).forEach(function (key) {
  46862. var value = data[key];
  46863. if (key === 'color') { value = new THREE.Color(value); }
  46864. fog[key] = value;
  46865. });
  46866. },
  46867. /**
  46868. * Remove fog on remove (callback).
  46869. */
  46870. remove: function () {
  46871. var fog = this.el.object3D.fog;
  46872. if (!fog) { return; }
  46873. fog.far = 0;
  46874. fog.near = 0.1;
  46875. }
  46876. });
  46877. /**
  46878. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  46879. *
  46880. * @param {object} data - Fog data.
  46881. * @returns {object} fog
  46882. */
  46883. function getFog (data) {
  46884. var fog;
  46885. if (data.type === 'exponential') {
  46886. fog = new THREE.FogExp2(data.color, data.density);
  46887. } else {
  46888. fog = new THREE.Fog(data.color, data.near, data.far);
  46889. }
  46890. fog.name = data.type;
  46891. return fog;
  46892. }
  46893. },{"../../core/component":124,"../../lib/three":172,"../../utils/debug":193}],99:[function(_dereq_,module,exports){
  46894. (function (process){
  46895. /* global AFRAME */
  46896. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  46897. var pkg = _dereq_('../../../package');
  46898. var registerComponent = _dereq_('../../core/component').registerComponent;
  46899. var utils = _dereq_('../../utils/');
  46900. /**
  46901. * 0.4.2 to 0.4.x
  46902. * Will need to update this when A-Frame goes to 1.x.x.
  46903. */
  46904. function getFuzzyPatchVersion (version) {
  46905. var split = version.split('.');
  46906. split[2] = 'x';
  46907. return split.join('.');
  46908. }
  46909. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  46910. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  46911. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  46912. var LOADING_MESSAGE = 'Loading Inspector';
  46913. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  46914. module.exports.Component = registerComponent('inspector', {
  46915. schema: {
  46916. url: {default: INSPECTOR_URL}
  46917. },
  46918. init: function () {
  46919. this.firstPlay = true;
  46920. this.onKeydown = this.onKeydown.bind(this);
  46921. this.onMessage = this.onMessage.bind(this);
  46922. this.initOverlay();
  46923. window.addEventListener('keydown', this.onKeydown);
  46924. window.addEventListener('message', this.onMessage);
  46925. },
  46926. play: function () {
  46927. var urlParam;
  46928. if (!this.firstPlay) { return; }
  46929. urlParam = utils.getUrlParameter('inspector');
  46930. if (urlParam !== 'false' && !!urlParam) {
  46931. this.openInspector();
  46932. this.firstPlay = false;
  46933. }
  46934. },
  46935. initOverlay: function () {
  46936. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  46937. this.loadingMessageEl = document.createElement('div');
  46938. this.loadingMessageEl.classList.add('a-inspector-loader');
  46939. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  46940. },
  46941. remove: function () {
  46942. this.removeEventListeners();
  46943. },
  46944. /**
  46945. * <ctrl> + <alt> + i keyboard shortcut.
  46946. */
  46947. onKeydown: function (evt) {
  46948. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  46949. if (!shortcutPressed) { return; }
  46950. this.openInspector();
  46951. },
  46952. showLoader: function () {
  46953. document.body.appendChild(this.loadingMessageEl);
  46954. },
  46955. hideLoader: function () {
  46956. document.body.removeChild(this.loadingMessageEl);
  46957. },
  46958. /**
  46959. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  46960. */
  46961. onMessage: function (evt) {
  46962. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  46963. },
  46964. openInspector: function (focusEl) {
  46965. var self = this;
  46966. var script;
  46967. // Already injected. Open.
  46968. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  46969. AFRAME.INSPECTOR.open(focusEl);
  46970. return;
  46971. }
  46972. this.showLoader();
  46973. // Inject.
  46974. script = document.createElement('script');
  46975. script.src = this.data.url;
  46976. script.setAttribute('data-name', 'aframe-inspector');
  46977. script.setAttribute(AFRAME_INJECTED, '');
  46978. script.onload = function () {
  46979. AFRAME.INSPECTOR.open(focusEl);
  46980. self.hideLoader();
  46981. self.removeEventListeners();
  46982. };
  46983. script.onerror = function () {
  46984. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  46985. };
  46986. document.head.appendChild(script);
  46987. AFRAME.inspectorInjected = true;
  46988. },
  46989. removeEventListeners: function () {
  46990. window.removeEventListener('keydown', this.onKeydown);
  46991. window.removeEventListener('message', this.onMessage);
  46992. }
  46993. });
  46994. }).call(this,_dereq_('_process'))
  46995. },{"../../../package":72,"../../constants":116,"../../core/component":124,"../../utils/":197,"_process":49}],100:[function(_dereq_,module,exports){
  46996. var registerComponent = _dereq_('../../core/component').registerComponent;
  46997. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  46998. module.exports.Component = registerComponent('keyboard-shortcuts', {
  46999. schema: {
  47000. enterVR: {default: true},
  47001. exitVR: {default: true}
  47002. },
  47003. init: function () {
  47004. this.onKeyup = this.onKeyup.bind(this);
  47005. },
  47006. update: function (oldData) {
  47007. var data = this.data;
  47008. this.enterVREnabled = data.enterVR;
  47009. },
  47010. play: function () {
  47011. window.addEventListener('keyup', this.onKeyup, false);
  47012. },
  47013. pause: function () {
  47014. window.removeEventListener('keyup', this.onKeyup);
  47015. },
  47016. onKeyup: function (evt) {
  47017. var scene = this.el;
  47018. if (!shouldCaptureKeyEvent(evt)) { return; }
  47019. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  47020. scene.enterVR();
  47021. }
  47022. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  47023. scene.exitVR();
  47024. }
  47025. }
  47026. });
  47027. },{"../../core/component":124,"../../utils/":197}],101:[function(_dereq_,module,exports){
  47028. var debug = _dereq_('../../utils/debug');
  47029. var registerComponent = _dereq_('../../core/component').registerComponent;
  47030. var warn = debug('components:pool:warn');
  47031. /**
  47032. * Pool component to reuse entities.
  47033. * Avoids creating and destroying the same kind of entities.
  47034. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  47035. *
  47036. * @member {array} availableEls - Available entities in the pool.
  47037. * @member {array} usedEls - Entities of the pool in use.
  47038. */
  47039. module.exports.Component = registerComponent('pool', {
  47040. schema: {
  47041. container: {default: ''},
  47042. mixin: {default: ''},
  47043. size: {default: 0},
  47044. dynamic: {default: false}
  47045. },
  47046. multiple: true,
  47047. initPool: function () {
  47048. var i;
  47049. this.availableEls = [];
  47050. this.usedEls = [];
  47051. if (!this.data.mixin) {
  47052. warn('No mixin provided for pool component.');
  47053. }
  47054. if (this.data.container) {
  47055. this.container = document.querySelector(this.data.container);
  47056. if (!this.container) {
  47057. warn('Container ' + this.data.container + ' not found.');
  47058. }
  47059. }
  47060. this.container = this.container || this.el;
  47061. for (i = 0; i < this.data.size; ++i) {
  47062. this.createEntity();
  47063. }
  47064. },
  47065. update: function (oldData) {
  47066. var data = this.data;
  47067. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  47068. this.initPool();
  47069. }
  47070. },
  47071. /**
  47072. * Add a new entity to the list of available entities.
  47073. */
  47074. createEntity: function () {
  47075. var el;
  47076. el = document.createElement('a-entity');
  47077. el.play = this.wrapPlay(el.play);
  47078. el.setAttribute('mixin', this.data.mixin);
  47079. el.object3D.visible = false;
  47080. el.pause();
  47081. this.container.appendChild(el);
  47082. this.availableEls.push(el);
  47083. },
  47084. /**
  47085. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  47086. * entities that are not in use.
  47087. */
  47088. wrapPlay: function (playMethod) {
  47089. var usedEls = this.usedEls;
  47090. return function () {
  47091. if (usedEls.indexOf(this) === -1) { return; }
  47092. playMethod.call(this);
  47093. };
  47094. },
  47095. /**
  47096. * Used to request one of the available entities of the pool.
  47097. */
  47098. requestEntity: function () {
  47099. var el;
  47100. if (this.availableEls.length === 0) {
  47101. if (this.data.dynamic === false) {
  47102. warn('Requested entity from empty pool: ' + this.attrName);
  47103. return;
  47104. } else {
  47105. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  47106. 'automatically. You might want to increase its initial size: ' + this.attrName);
  47107. }
  47108. this.createEntity();
  47109. }
  47110. el = this.availableEls.shift();
  47111. this.usedEls.push(el);
  47112. el.object3D.visible = true;
  47113. return el;
  47114. },
  47115. /**
  47116. * Used to return a used entity to the pool.
  47117. */
  47118. returnEntity: function (el) {
  47119. var index = this.usedEls.indexOf(el);
  47120. if (index === -1) {
  47121. warn('The returned entity was not previously pooled from ' + this.attrName);
  47122. return;
  47123. }
  47124. this.usedEls.splice(index, 1);
  47125. this.availableEls.push(el);
  47126. el.object3D.visible = false;
  47127. el.pause();
  47128. return el;
  47129. }
  47130. });
  47131. },{"../../core/component":124,"../../utils/debug":193}],102:[function(_dereq_,module,exports){
  47132. /* global ImageData, URL */
  47133. var registerComponent = _dereq_('../../core/component').registerComponent;
  47134. var THREE = _dereq_('../../lib/three');
  47135. var VERTEX_SHADER = [
  47136. 'attribute vec3 position;',
  47137. 'attribute vec2 uv;',
  47138. 'uniform mat4 projectionMatrix;',
  47139. 'uniform mat4 modelViewMatrix;',
  47140. 'varying vec2 vUv;',
  47141. 'void main() {',
  47142. ' vUv = vec2( 1.- uv.x, uv.y );',
  47143. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  47144. '}'
  47145. ].join('\n');
  47146. var FRAGMENT_SHADER = [
  47147. 'precision mediump float;',
  47148. 'uniform samplerCube map;',
  47149. 'varying vec2 vUv;',
  47150. '#define M_PI 3.141592653589793238462643383279',
  47151. 'void main() {',
  47152. ' vec2 uv = vUv;',
  47153. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  47154. ' float latitude = uv.y * M_PI;',
  47155. ' vec3 dir = vec3(',
  47156. ' - sin( longitude ) * sin( latitude ),',
  47157. ' cos( latitude ),',
  47158. ' - cos( longitude ) * sin( latitude )',
  47159. ' );',
  47160. ' normalize( dir );',
  47161. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  47162. '}'
  47163. ].join('\n');
  47164. /**
  47165. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  47166. * It can be configured to either take 360&deg; captures (`equirectangular`)
  47167. * or regular screenshots (`projection`)
  47168. *
  47169. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  47170. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  47171. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  47172. * WebGLRenderTarget with an ortographic camera.
  47173. */
  47174. module.exports.Component = registerComponent('screenshot', {
  47175. schema: {
  47176. width: {default: 4096},
  47177. height: {default: 2048},
  47178. camera: {type: 'selector'}
  47179. },
  47180. init: function () {
  47181. var el = this.el;
  47182. var self = this;
  47183. if (el.renderer) {
  47184. setup();
  47185. } else {
  47186. el.addEventListener('render-target-loaded', setup);
  47187. }
  47188. function setup () {
  47189. var gl = el.renderer.getContext();
  47190. if (!gl) { return; }
  47191. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  47192. self.material = new THREE.RawShaderMaterial({
  47193. uniforms: {map: {type: 't', value: null}},
  47194. vertexShader: VERTEX_SHADER,
  47195. fragmentShader: FRAGMENT_SHADER,
  47196. side: THREE.DoubleSide
  47197. });
  47198. self.quad = new THREE.Mesh(
  47199. new THREE.PlaneBufferGeometry(1, 1),
  47200. self.material
  47201. );
  47202. self.quad.visible = false;
  47203. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  47204. self.canvas = document.createElement('canvas');
  47205. self.ctx = self.canvas.getContext('2d');
  47206. el.object3D.add(self.quad);
  47207. self.onKeyDown = self.onKeyDown.bind(self);
  47208. }
  47209. },
  47210. getRenderTarget: function (width, height) {
  47211. return new THREE.WebGLRenderTarget(width, height, {
  47212. minFilter: THREE.LinearFilter,
  47213. magFilter: THREE.LinearFilter,
  47214. wrapS: THREE.ClampToEdgeWrapping,
  47215. wrapT: THREE.ClampToEdgeWrapping,
  47216. format: THREE.RGBAFormat,
  47217. type: THREE.UnsignedByteType
  47218. });
  47219. },
  47220. resize: function (width, height) {
  47221. // Resize quad.
  47222. this.quad.scale.set(width, height, 1);
  47223. // Resize camera.
  47224. this.camera.left = -1 * width / 2;
  47225. this.camera.right = width / 2;
  47226. this.camera.top = height / 2;
  47227. this.camera.bottom = -1 * height / 2;
  47228. this.camera.updateProjectionMatrix();
  47229. // Resize canvas.
  47230. this.canvas.width = width;
  47231. this.canvas.height = height;
  47232. },
  47233. play: function () {
  47234. window.addEventListener('keydown', this.onKeyDown);
  47235. },
  47236. /**
  47237. * <ctrl> + <alt> + s = Regular screenshot.
  47238. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  47239. */
  47240. onKeyDown: function (evt) {
  47241. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  47242. if (!this.data || !shortcutPressed) { return; }
  47243. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  47244. this.capture(projection);
  47245. },
  47246. /**
  47247. * Capture a screenshot of the scene.
  47248. *
  47249. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  47250. */
  47251. setCapture: function (projection) {
  47252. var el = this.el;
  47253. var size;
  47254. var camera;
  47255. var cubeCamera;
  47256. // Configure camera.
  47257. if (projection === 'perspective') {
  47258. // Quad is only used in equirectangular mode. Hide it in this case.
  47259. this.quad.visible = false;
  47260. // Use scene camera.
  47261. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  47262. size = {width: this.data.width, height: this.data.height};
  47263. } else {
  47264. // Use ortho camera.
  47265. camera = this.camera;
  47266. // Create cube camera and copy position from scene camera.
  47267. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  47268. Math.min(this.cubeMapSize, 2048));
  47269. // Copy camera position into cube camera;
  47270. el.camera.getWorldPosition(cubeCamera.position);
  47271. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  47272. // Render scene with cube camera.
  47273. cubeCamera.update(el.renderer, el.object3D);
  47274. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  47275. size = {width: this.data.width, height: this.data.height};
  47276. // Use quad to project image taken by the cube camera.
  47277. this.quad.visible = true;
  47278. }
  47279. return {
  47280. camera: camera,
  47281. size: size,
  47282. projection: projection
  47283. };
  47284. },
  47285. /**
  47286. * Maintained for backwards compatibility.
  47287. */
  47288. capture: function (projection) {
  47289. var isVREnabled = this.el.renderer.vr.enabled;
  47290. var renderer = this.el.renderer;
  47291. var params;
  47292. // Disable VR.
  47293. renderer.vr.enabled = false;
  47294. params = this.setCapture(projection);
  47295. this.renderCapture(params.camera, params.size, params.projection);
  47296. // Trigger file download.
  47297. this.saveCapture();
  47298. // Restore VR.
  47299. renderer.vr.enabled = isVREnabled;
  47300. },
  47301. /**
  47302. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  47303. */
  47304. getCanvas: function (projection) {
  47305. var isVREnabled = this.el.renderer.vr.enabled;
  47306. var renderer = this.el.renderer;
  47307. // Disable VR.
  47308. var params = this.setCapture(projection);
  47309. renderer.vr.enabled = false;
  47310. this.renderCapture(params.camera, params.size, params.projection);
  47311. // Restore VR.
  47312. renderer.vr.enabled = isVREnabled;
  47313. return this.canvas;
  47314. },
  47315. renderCapture: function (camera, size, projection) {
  47316. var autoClear = this.el.renderer.autoClear;
  47317. var el = this.el;
  47318. var imageData;
  47319. var output;
  47320. var pixels;
  47321. var renderer = el.renderer;
  47322. // Create rendering target and buffer to store the read pixels.
  47323. output = this.getRenderTarget(size.width, size.height);
  47324. pixels = new Uint8Array(4 * size.width * size.height);
  47325. // Resize quad, camera, and canvas.
  47326. this.resize(size.width, size.height);
  47327. // Render scene to render target.
  47328. renderer.autoClear = true;
  47329. renderer.clear();
  47330. renderer.setRenderTarget(output);
  47331. renderer.render(el.object3D, camera);
  47332. renderer.autoClear = autoClear;
  47333. // Read image pizels back.
  47334. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  47335. renderer.setRenderTarget(null);
  47336. if (projection === 'perspective') {
  47337. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  47338. }
  47339. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  47340. // Hide quad after projecting the image.
  47341. this.quad.visible = false;
  47342. // Copy pixels into canvas.
  47343. this.ctx.putImageData(imageData, 0, 0);
  47344. },
  47345. flipPixelsVertically: function (pixels, width, height) {
  47346. var flippedPixels = pixels.slice(0);
  47347. for (var x = 0; x < width; ++x) {
  47348. for (var y = 0; y < height; ++y) {
  47349. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  47350. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  47351. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  47352. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  47353. }
  47354. }
  47355. return flippedPixels;
  47356. },
  47357. /**
  47358. * Download capture to file.
  47359. */
  47360. saveCapture: function () {
  47361. this.canvas.toBlob(function (blob) {
  47362. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  47363. var linkEl = document.createElement('a');
  47364. var url = URL.createObjectURL(blob);
  47365. linkEl.href = url;
  47366. linkEl.setAttribute('download', fileName);
  47367. linkEl.innerHTML = 'downloading...';
  47368. linkEl.style.display = 'none';
  47369. document.body.appendChild(linkEl);
  47370. setTimeout(function () {
  47371. linkEl.click();
  47372. document.body.removeChild(linkEl);
  47373. }, 1);
  47374. }, 'image/png');
  47375. }
  47376. });
  47377. },{"../../core/component":124,"../../lib/three":172}],103:[function(_dereq_,module,exports){
  47378. var registerComponent = _dereq_('../../core/component').registerComponent;
  47379. var RStats = _dereq_('../../../vendor/rStats');
  47380. var utils = _dereq_('../../utils');
  47381. _dereq_('../../../vendor/rStats.extras');
  47382. _dereq_('../../lib/rStatsAframe');
  47383. var AFrameStats = window.aframeStats;
  47384. var bind = utils.bind;
  47385. var HIDDEN_CLASS = 'a-hidden';
  47386. var ThreeStats = window.threeStats;
  47387. /**
  47388. * Stats appended to document.body by RStats.
  47389. */
  47390. module.exports.Component = registerComponent('stats', {
  47391. schema: {default: true},
  47392. init: function () {
  47393. var scene = this.el;
  47394. if (utils.getUrlParameter('stats') === 'false') { return; }
  47395. this.stats = createStats(scene);
  47396. this.statsEl = document.querySelector('.rs-base');
  47397. this.hideBound = bind(this.hide, this);
  47398. this.showBound = bind(this.show, this);
  47399. scene.addEventListener('enter-vr', this.hideBound);
  47400. scene.addEventListener('exit-vr', this.showBound);
  47401. },
  47402. update: function () {
  47403. if (!this.stats) { return; }
  47404. return (!this.data) ? this.hide() : this.show();
  47405. },
  47406. remove: function () {
  47407. this.el.removeEventListener('enter-vr', this.hideBound);
  47408. this.el.removeEventListener('exit-vr', this.showBound);
  47409. if (!this.statsEl) { return; } // Scene detached.
  47410. this.statsEl.parentNode.removeChild(this.statsEl);
  47411. },
  47412. tick: function () {
  47413. var stats = this.stats;
  47414. if (!stats) { return; }
  47415. stats('rAF').tick();
  47416. stats('FPS').frame();
  47417. stats().update();
  47418. },
  47419. hide: function () {
  47420. this.statsEl.classList.add(HIDDEN_CLASS);
  47421. },
  47422. show: function () {
  47423. this.statsEl.classList.remove(HIDDEN_CLASS);
  47424. }
  47425. });
  47426. function createStats (scene) {
  47427. var threeStats = new ThreeStats(scene.renderer);
  47428. var aframeStats = new AFrameStats(scene);
  47429. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  47430. return new RStats({
  47431. css: [], // Our stylesheet is injected from `src/index.js`.
  47432. values: {
  47433. fps: {caption: 'fps', below: 30}
  47434. },
  47435. groups: [
  47436. {caption: 'Framerate', values: ['fps', 'raf']}
  47437. ],
  47438. plugins: plugins
  47439. });
  47440. }
  47441. },{"../../../vendor/rStats":207,"../../../vendor/rStats.extras":206,"../../core/component":124,"../../lib/rStatsAframe":171,"../../utils":197}],104:[function(_dereq_,module,exports){
  47442. var registerComponent = _dereq_('../../core/component').registerComponent;
  47443. var constants = _dereq_('../../constants/');
  47444. var utils = _dereq_('../../utils/');
  47445. var bind = utils.bind;
  47446. var ENTER_VR_CLASS = 'a-enter-vr';
  47447. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  47448. var HIDDEN_CLASS = 'a-hidden';
  47449. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  47450. /**
  47451. * UI for entering VR mode.
  47452. */
  47453. module.exports.Component = registerComponent('vr-mode-ui', {
  47454. dependencies: ['canvas'],
  47455. schema: {
  47456. enabled: {default: true},
  47457. enterVRButton: {default: ''}
  47458. },
  47459. init: function () {
  47460. var self = this;
  47461. var sceneEl = this.el;
  47462. if (utils.getUrlParameter('ui') === 'false') { return; }
  47463. this.insideLoader = false;
  47464. this.enterVREl = null;
  47465. this.orientationModalEl = null;
  47466. this.bindMethods();
  47467. // Hide/show VR UI when entering/exiting VR mode.
  47468. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  47469. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  47470. window.addEventListener('message', function (event) {
  47471. if (event.data.type === 'loaderReady') {
  47472. self.insideLoader = true;
  47473. self.remove();
  47474. }
  47475. });
  47476. // Modal that tells the user to change orientation if in portrait.
  47477. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  47478. },
  47479. bindMethods: function () {
  47480. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  47481. this.onModalClick = bind(this.onModalClick, this);
  47482. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  47483. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  47484. },
  47485. /**
  47486. * Exit VR when modal clicked.
  47487. */
  47488. onModalClick: function () {
  47489. this.el.exitVR();
  47490. },
  47491. /**
  47492. * Enter VR when modal clicked.
  47493. */
  47494. onEnterVRButtonClick: function () {
  47495. this.el.enterVR();
  47496. },
  47497. update: function () {
  47498. var data = this.data;
  47499. var sceneEl = this.el;
  47500. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  47501. return this.remove();
  47502. }
  47503. if (this.enterVREl || this.orientationModalEl) { return; }
  47504. // Add UI if enabled and not already present.
  47505. if (data.enterVRButton) {
  47506. // Custom button.
  47507. this.enterVREl = document.querySelector(data.enterVRButton);
  47508. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  47509. } else {
  47510. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  47511. sceneEl.appendChild(this.enterVREl);
  47512. }
  47513. this.orientationModalEl = createOrientationModal(this.onModalClick);
  47514. sceneEl.appendChild(this.orientationModalEl);
  47515. this.updateEnterVRInterface();
  47516. },
  47517. remove: function () {
  47518. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  47519. if (uiElement && uiElement.parentNode) {
  47520. uiElement.parentNode.removeChild(uiElement);
  47521. }
  47522. });
  47523. },
  47524. updateEnterVRInterface: function () {
  47525. this.toggleEnterVRButtonIfNeeded();
  47526. this.toggleOrientationModalIfNeeded();
  47527. },
  47528. toggleEnterVRButtonIfNeeded: function () {
  47529. var sceneEl = this.el;
  47530. if (!this.enterVREl) { return; }
  47531. if (sceneEl.is('vr-mode')) {
  47532. this.enterVREl.classList.add(HIDDEN_CLASS);
  47533. } else {
  47534. this.enterVREl.classList.remove(HIDDEN_CLASS);
  47535. }
  47536. },
  47537. toggleOrientationModalIfNeeded: function () {
  47538. var sceneEl = this.el;
  47539. var orientationModalEl = this.orientationModalEl;
  47540. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  47541. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  47542. // Show if in VR mode on portrait.
  47543. orientationModalEl.classList.remove(HIDDEN_CLASS);
  47544. } else {
  47545. orientationModalEl.classList.add(HIDDEN_CLASS);
  47546. }
  47547. }
  47548. });
  47549. /**
  47550. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  47551. *
  47552. * Structure: <div><button></div>
  47553. *
  47554. * @param {function} onClick - click event handler
  47555. * @returns {Element} Wrapper <div>.
  47556. */
  47557. function createEnterVRButton (onClick) {
  47558. var vrButton;
  47559. var wrapper;
  47560. // Create elements.
  47561. wrapper = document.createElement('div');
  47562. wrapper.classList.add(ENTER_VR_CLASS);
  47563. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  47564. vrButton = document.createElement('button');
  47565. vrButton.className = ENTER_VR_BTN_CLASS;
  47566. vrButton.setAttribute('title',
  47567. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  47568. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  47569. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  47570. // Insert elements.
  47571. wrapper.appendChild(vrButton);
  47572. vrButton.addEventListener('click', function (evt) {
  47573. onClick();
  47574. evt.stopPropagation();
  47575. });
  47576. return wrapper;
  47577. }
  47578. /**
  47579. * Creates a modal dialog to request the user to switch to landscape orientation.
  47580. *
  47581. * @param {function} onClick - click event handler
  47582. * @returns {Element} Wrapper <div>.
  47583. */
  47584. function createOrientationModal (onClick) {
  47585. var modal = document.createElement('div');
  47586. modal.className = ORIENTATION_MODAL_CLASS;
  47587. modal.classList.add(HIDDEN_CLASS);
  47588. modal.setAttribute(constants.AFRAME_INJECTED, '');
  47589. var exit = document.createElement('button');
  47590. exit.setAttribute(constants.AFRAME_INJECTED, '');
  47591. exit.innerHTML = 'Exit VR';
  47592. // Exit VR on close.
  47593. exit.addEventListener('click', onClick);
  47594. modal.appendChild(exit);
  47595. return modal;
  47596. }
  47597. },{"../../constants/":116,"../../core/component":124,"../../utils/":197}],105:[function(_dereq_,module,exports){
  47598. var component = _dereq_('../core/component');
  47599. var THREE = _dereq_('../lib/three');
  47600. var bind = _dereq_('../utils/bind');
  47601. var registerComponent = component.registerComponent;
  47602. /**
  47603. * Shadow component.
  47604. *
  47605. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  47606. * shadows as specified by the `cast` and `receive` properties.
  47607. */
  47608. module.exports.Component = registerComponent('shadow', {
  47609. schema: {
  47610. cast: {default: true},
  47611. receive: {default: true}
  47612. },
  47613. init: function () {
  47614. this.onMeshChanged = bind(this.update, this);
  47615. this.el.addEventListener('object3dset', this.onMeshChanged);
  47616. this.system.setShadowMapEnabled(true);
  47617. },
  47618. update: function () {
  47619. var data = this.data;
  47620. this.updateDescendants(data.cast, data.receive);
  47621. },
  47622. remove: function () {
  47623. var el = this.el;
  47624. el.removeEventListener('object3dset', this.onMeshChanged);
  47625. this.updateDescendants(false, false);
  47626. },
  47627. updateDescendants: function (cast, receive) {
  47628. var sceneEl = this.el.sceneEl;
  47629. this.el.object3D.traverse(function (node) {
  47630. if (!(node instanceof THREE.Mesh)) { return; }
  47631. node.castShadow = cast;
  47632. node.receiveShadow = receive;
  47633. // If scene has already rendered, materials must be updated.
  47634. if (sceneEl.hasLoaded && node.material) {
  47635. var materials = Array.isArray(node.material) ? node.material : [node.material];
  47636. for (var i = 0; i < materials.length; i++) {
  47637. materials[i].needsUpdate = true;
  47638. }
  47639. }
  47640. });
  47641. }
  47642. });
  47643. },{"../core/component":124,"../lib/three":172,"../utils/bind":191}],106:[function(_dereq_,module,exports){
  47644. var registerComponent = _dereq_('../core/component').registerComponent;
  47645. var debug = _dereq_('../utils/debug');
  47646. var THREE = _dereq_('../lib/three');
  47647. var warn = debug('components:sound:warn');
  47648. /**
  47649. * Sound component.
  47650. */
  47651. module.exports.Component = registerComponent('sound', {
  47652. schema: {
  47653. autoplay: {default: false},
  47654. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  47655. loop: {default: false},
  47656. maxDistance: {default: 10000},
  47657. on: {default: ''},
  47658. poolSize: {default: 1},
  47659. positional: {default: true},
  47660. refDistance: {default: 1},
  47661. rolloffFactor: {default: 1},
  47662. src: {type: 'audio'},
  47663. volume: {default: 1}
  47664. },
  47665. multiple: true,
  47666. init: function () {
  47667. var self = this;
  47668. this.listener = null;
  47669. this.audioLoader = new THREE.AudioLoader();
  47670. this.pool = new THREE.Group();
  47671. this.loaded = false;
  47672. this.mustPlay = false;
  47673. // Don't pass evt because playSound takes a function as parameter.
  47674. this.playSoundBound = function () { self.playSound(); };
  47675. },
  47676. update: function (oldData) {
  47677. var data = this.data;
  47678. var i;
  47679. var sound;
  47680. var srcChanged = data.src !== oldData.src;
  47681. // Create new sound if not yet created or changing `src`.
  47682. if (srcChanged) {
  47683. if (!data.src) { return; }
  47684. this.setupSound();
  47685. }
  47686. for (i = 0; i < this.pool.children.length; i++) {
  47687. sound = this.pool.children[i];
  47688. if (data.positional) {
  47689. sound.setDistanceModel(data.distanceModel);
  47690. sound.setMaxDistance(data.maxDistance);
  47691. sound.setRefDistance(data.refDistance);
  47692. sound.setRolloffFactor(data.rolloffFactor);
  47693. }
  47694. sound.setLoop(data.loop);
  47695. sound.setVolume(data.volume);
  47696. sound.isPaused = false;
  47697. }
  47698. if (data.on !== oldData.on) {
  47699. this.updateEventListener(oldData.on);
  47700. }
  47701. // All sound values set. Load in `src`.
  47702. if (srcChanged) {
  47703. var self = this;
  47704. this.loaded = false;
  47705. this.audioLoader.load(data.src, function (buffer) {
  47706. for (i = 0; i < self.pool.children.length; i++) {
  47707. sound = self.pool.children[i];
  47708. sound.setBuffer(buffer);
  47709. }
  47710. self.loaded = true;
  47711. // Remove this key from cache, otherwise we can't play it again
  47712. THREE.Cache.remove(data.src);
  47713. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  47714. self.el.emit('sound-loaded', self.evtDetail, false);
  47715. });
  47716. }
  47717. },
  47718. pause: function () {
  47719. this.stopSound();
  47720. this.removeEventListener();
  47721. },
  47722. play: function () {
  47723. if (this.data.autoplay) { this.playSound(); }
  47724. this.updateEventListener();
  47725. },
  47726. remove: function () {
  47727. var i;
  47728. var sound;
  47729. this.removeEventListener();
  47730. if (this.el.getObject3D(this.attrName)) {
  47731. this.el.removeObject3D(this.attrName);
  47732. }
  47733. try {
  47734. for (i = 0; i < this.pool.children.length; i++) {
  47735. sound = this.pool.children[i];
  47736. sound.disconnect();
  47737. }
  47738. } catch (e) {
  47739. // disconnect() will throw if it was never connected initially.
  47740. warn('Audio source not properly disconnected');
  47741. }
  47742. },
  47743. /**
  47744. * Update listener attached to the user defined on event.
  47745. */
  47746. updateEventListener: function (oldEvt) {
  47747. var el = this.el;
  47748. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  47749. el.addEventListener(this.data.on, this.playSoundBound);
  47750. },
  47751. removeEventListener: function () {
  47752. this.el.removeEventListener(this.data.on, this.playSoundBound);
  47753. },
  47754. /**
  47755. * Removes current sound object, creates new sound object, adds to entity.
  47756. *
  47757. * @returns {object} sound
  47758. */
  47759. setupSound: function () {
  47760. var el = this.el;
  47761. var i;
  47762. var sceneEl = el.sceneEl;
  47763. var self = this;
  47764. var sound;
  47765. if (this.pool.children.length > 0) {
  47766. this.stopSound();
  47767. el.removeObject3D('sound');
  47768. }
  47769. // Only want one AudioListener. Cache it on the scene.
  47770. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  47771. sceneEl.audioListener = listener;
  47772. if (sceneEl.camera) {
  47773. sceneEl.camera.add(listener);
  47774. }
  47775. // Wait for camera if necessary.
  47776. sceneEl.addEventListener('camera-set-active', function (evt) {
  47777. evt.detail.cameraEl.getObject3D('camera').add(listener);
  47778. });
  47779. // Create [poolSize] audio instances and attach them to pool
  47780. this.pool = new THREE.Group();
  47781. for (i = 0; i < this.data.poolSize; i++) {
  47782. sound = this.data.positional
  47783. ? new THREE.PositionalAudio(listener)
  47784. : new THREE.Audio(listener);
  47785. this.pool.add(sound);
  47786. }
  47787. el.setObject3D(this.attrName, this.pool);
  47788. for (i = 0; i < this.pool.children.length; i++) {
  47789. sound = this.pool.children[i];
  47790. sound.onEnded = function () {
  47791. this.isPlaying = false;
  47792. self.el.emit('sound-ended', self.evtDetail, false);
  47793. };
  47794. }
  47795. },
  47796. /**
  47797. * Pause all the sounds in the pool.
  47798. */
  47799. pauseSound: function () {
  47800. var i;
  47801. var sound;
  47802. this.isPlaying = false;
  47803. for (i = 0; i < this.pool.children.length; i++) {
  47804. sound = this.pool.children[i];
  47805. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  47806. continue;
  47807. }
  47808. sound.isPaused = true;
  47809. sound.pause();
  47810. }
  47811. },
  47812. /**
  47813. * Look for an unused sound in the pool and play it if found.
  47814. */
  47815. playSound: function (processSound) {
  47816. var found;
  47817. var i;
  47818. var sound;
  47819. if (!this.loaded) {
  47820. warn('Sound not loaded yet. It will be played once it finished loading');
  47821. this.mustPlay = true;
  47822. return;
  47823. }
  47824. found = false;
  47825. this.isPlaying = true;
  47826. for (i = 0; i < this.pool.children.length; i++) {
  47827. sound = this.pool.children[i];
  47828. if (!sound.isPlaying && sound.buffer && !found) {
  47829. if (processSound) { processSound(sound); }
  47830. sound.play();
  47831. sound.isPaused = false;
  47832. found = true;
  47833. continue;
  47834. }
  47835. }
  47836. if (!found) {
  47837. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  47838. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  47839. return;
  47840. }
  47841. this.mustPlay = false;
  47842. },
  47843. /**
  47844. * Stop all the sounds in the pool.
  47845. */
  47846. stopSound: function () {
  47847. var i;
  47848. var sound;
  47849. this.isPlaying = false;
  47850. for (i = 0; i < this.pool.children.length; i++) {
  47851. sound = this.pool.children[i];
  47852. if (!sound.source || !sound.source.buffer) { return; }
  47853. sound.stop();
  47854. }
  47855. }
  47856. });
  47857. },{"../core/component":124,"../lib/three":172,"../utils/debug":193}],107:[function(_dereq_,module,exports){
  47858. var createTextGeometry = _dereq_('three-bmfont-text');
  47859. var loadBMFont = _dereq_('load-bmfont');
  47860. var registerComponent = _dereq_('../core/component').registerComponent;
  47861. var coreShader = _dereq_('../core/shader');
  47862. var THREE = _dereq_('../lib/three');
  47863. var utils = _dereq_('../utils/');
  47864. var error = utils.debug('components:text:error');
  47865. var shaders = coreShader.shaders;
  47866. var warn = utils.debug('components:text:warn');
  47867. // 1 to match other A-Frame default widths.
  47868. var DEFAULT_WIDTH = 1;
  47869. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  47870. var MAX_ANISOTROPY = 16;
  47871. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  47872. var FONTS = {
  47873. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  47874. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  47875. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  47876. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  47877. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  47878. monoid: FONT_BASE_URL + 'Monoid.fnt',
  47879. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  47880. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  47881. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  47882. };
  47883. var MSDF_FONTS = ['roboto'];
  47884. var DEFAULT_FONT = 'roboto';
  47885. module.exports.FONTS = FONTS;
  47886. var cache = new PromiseCache();
  47887. var fontWidthFactors = {};
  47888. var textures = {};
  47889. // Regular expression for detecting a URLs with a protocol prefix.
  47890. var protocolRe = /^\w+:/;
  47891. /**
  47892. * SDF-based text component.
  47893. * Based on https://github.com/Jam3/three-bmfont-text.
  47894. *
  47895. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  47896. * original `sdf` shader.
  47897. */
  47898. module.exports.Component = registerComponent('text', {
  47899. multiple: true,
  47900. schema: {
  47901. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  47902. alphaTest: {default: 0.5},
  47903. // `anchor` defaults to center to match geometries.
  47904. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  47905. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  47906. color: {type: 'color', default: '#FFF'},
  47907. font: {type: 'string', default: DEFAULT_FONT},
  47908. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  47909. fontImage: {type: 'string'},
  47910. // `height` has no default, will be populated at layout.
  47911. height: {type: 'number'},
  47912. letterSpacing: {type: 'number', default: 0},
  47913. // `lineHeight` defaults to font's `lineHeight` value.
  47914. lineHeight: {type: 'number'},
  47915. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  47916. negate: {type: 'boolean', default: true},
  47917. opacity: {type: 'number', default: 1.0},
  47918. shader: {default: 'sdf', oneOf: shaders},
  47919. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  47920. tabSize: {default: 4},
  47921. transparent: {default: true},
  47922. value: {type: 'string'},
  47923. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  47924. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  47925. width: {type: 'number'},
  47926. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  47927. wrapCount: {type: 'number', default: 40},
  47928. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  47929. wrapPixels: {type: 'number'},
  47930. // `xOffset` to add padding.
  47931. xOffset: {type: 'number', default: 0},
  47932. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  47933. yOffset: {type: 'number', default: 0},
  47934. // `zOffset` will provide a small z offset to avoid z-fighting.
  47935. zOffset: {type: 'number', default: 0.001}
  47936. },
  47937. init: function () {
  47938. this.shaderData = {};
  47939. this.geometry = createTextGeometry();
  47940. this.createOrUpdateMaterial();
  47941. this.mesh = new THREE.Mesh(this.geometry, this.material);
  47942. this.el.setObject3D(this.attrName, this.mesh);
  47943. },
  47944. update: function (oldData) {
  47945. var data = this.data;
  47946. var font = this.currentFont;
  47947. if (textures[data.font]) {
  47948. this.texture = textures[data.font];
  47949. } else {
  47950. // Create texture per font.
  47951. this.texture = textures[data.font] = new THREE.Texture();
  47952. this.texture.anisotropy = MAX_ANISOTROPY;
  47953. }
  47954. // Update material.
  47955. this.createOrUpdateMaterial();
  47956. // New font. `updateFont` will later change data and layout.
  47957. if (oldData.font !== data.font) {
  47958. this.updateFont();
  47959. return;
  47960. }
  47961. // Update geometry and layout.
  47962. if (font) {
  47963. this.updateGeometry(this.geometry, font);
  47964. this.updateLayout();
  47965. }
  47966. },
  47967. /**
  47968. * Clean up geometry, material, texture, mesh, objects.
  47969. */
  47970. remove: function () {
  47971. this.geometry.dispose();
  47972. this.geometry = null;
  47973. this.el.removeObject3D(this.attrName);
  47974. this.material.dispose();
  47975. this.material = null;
  47976. this.texture.dispose();
  47977. this.texture = null;
  47978. if (this.shaderObject) {
  47979. delete this.shaderObject;
  47980. }
  47981. },
  47982. /**
  47983. * Update the shader of the material.
  47984. */
  47985. createOrUpdateMaterial: function () {
  47986. var data = this.data;
  47987. var hasChangedShader;
  47988. var material = this.material;
  47989. var NewShader;
  47990. var shaderData = this.shaderData;
  47991. var shaderName;
  47992. // Infer shader if using a stock font (or from `-msdf` filename convention).
  47993. shaderName = data.shader;
  47994. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  47995. shaderName = 'msdf';
  47996. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  47997. shaderName = 'sdf';
  47998. }
  47999. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  48000. shaderData.alphaTest = data.alphaTest;
  48001. shaderData.color = data.color;
  48002. shaderData.map = this.texture;
  48003. shaderData.opacity = data.opacity;
  48004. shaderData.side = parseSide(data.side);
  48005. shaderData.transparent = data.transparent;
  48006. shaderData.negate = data.negate;
  48007. // Shader has not changed, do an update.
  48008. if (!hasChangedShader) {
  48009. // Update shader material.
  48010. this.shaderObject.update(shaderData);
  48011. // Apparently, was not set on `init` nor `update`.
  48012. material.transparent = shaderData.transparent;
  48013. material.side = shaderData.side;
  48014. return;
  48015. }
  48016. // Shader has changed. Create a shader material.
  48017. NewShader = createShader(this.el, shaderName, shaderData);
  48018. this.material = NewShader.material;
  48019. this.shaderObject = NewShader.shader;
  48020. // Set new shader material.
  48021. this.material.side = shaderData.side;
  48022. if (this.mesh) { this.mesh.material = this.material; }
  48023. },
  48024. /**
  48025. * Load font for geometry, load font image for material, and apply.
  48026. */
  48027. updateFont: function () {
  48028. var data = this.data;
  48029. var el = this.el;
  48030. var fontSrc;
  48031. var geometry = this.geometry;
  48032. var self = this;
  48033. if (!data.font) { warn('No font specified. Using the default font.'); }
  48034. // Make invisible during font swap.
  48035. this.mesh.visible = false;
  48036. // Look up font URL to use, and perform cached load.
  48037. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  48038. cache.get(fontSrc, function doLoadFont () {
  48039. return loadFont(fontSrc, data.yOffset);
  48040. }).then(function setFont (font) {
  48041. var fontImgSrc;
  48042. if (font.pages.length !== 1) {
  48043. throw new Error('Currently only single-page bitmap fonts are supported.');
  48044. }
  48045. if (!fontWidthFactors[fontSrc]) {
  48046. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  48047. }
  48048. // Update geometry given font metrics.
  48049. self.updateGeometry(geometry, font);
  48050. // Set font and update layout.
  48051. self.currentFont = font;
  48052. self.updateLayout();
  48053. // Look up font image URL to use, and perform cached load.
  48054. fontImgSrc = self.getFontImageSrc();
  48055. cache.get(fontImgSrc, function () {
  48056. return loadTexture(fontImgSrc);
  48057. }).then(function (image) {
  48058. // Make mesh visible and apply font image as texture.
  48059. var texture = self.texture;
  48060. texture.image = image;
  48061. texture.needsUpdate = true;
  48062. textures[data.font] = texture;
  48063. self.texture = texture;
  48064. self.mesh.visible = true;
  48065. el.emit('textfontset', {font: data.font, fontObj: font});
  48066. }).catch(function (err) {
  48067. error(err.message);
  48068. error(err.stack);
  48069. });
  48070. }).catch(function (err) {
  48071. error(err.message);
  48072. error(err.stack);
  48073. });
  48074. },
  48075. getFontImageSrc: function () {
  48076. if (this.data.fontImage) { return this.data.fontImage; }
  48077. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  48078. var imageSrc = this.currentFont.pages[0];
  48079. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  48080. // path on disk and try to infer the path from the font source instead.
  48081. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  48082. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  48083. }
  48084. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  48085. },
  48086. /**
  48087. * Update layout with anchor, alignment, baseline, and considering any meshes.
  48088. */
  48089. updateLayout: function () {
  48090. var anchor;
  48091. var baseline;
  48092. var el = this.el;
  48093. var data = this.data;
  48094. var geometry = this.geometry;
  48095. var geometryComponent;
  48096. var height;
  48097. var layout;
  48098. var mesh = this.mesh;
  48099. var textRenderWidth;
  48100. var textScale;
  48101. var width;
  48102. var x;
  48103. var y;
  48104. if (!geometry.layout) { return; }
  48105. // Determine width to use (defined width, geometry's width, or default width).
  48106. geometryComponent = el.getAttribute('geometry');
  48107. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  48108. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  48109. // Note that experimental factor will never be correct for variable width fonts.
  48110. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  48111. this.currentFont.widthFactor);
  48112. textScale = width / textRenderWidth;
  48113. // Determine height to use.
  48114. layout = geometry.layout;
  48115. height = textScale * (layout.height + layout.descender);
  48116. // Update geometry dimensions to match text layout if width and height are set to 0.
  48117. // For example, scales a plane to fit text.
  48118. if (geometryComponent && geometryComponent.primitive === 'plane') {
  48119. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  48120. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  48121. }
  48122. // Calculate X position to anchor text left, center, or right.
  48123. anchor = data.anchor === 'align' ? data.align : data.anchor;
  48124. if (anchor === 'left') {
  48125. x = 0;
  48126. } else if (anchor === 'right') {
  48127. x = -1 * layout.width;
  48128. } else if (anchor === 'center') {
  48129. x = -1 * layout.width / 2;
  48130. } else {
  48131. throw new TypeError('Invalid text.anchor property value', anchor);
  48132. }
  48133. // Calculate Y position to anchor text top, center, or bottom.
  48134. baseline = data.baseline;
  48135. if (baseline === 'bottom') {
  48136. y = 0;
  48137. } else if (baseline === 'top') {
  48138. y = -1 * layout.height + layout.ascender;
  48139. } else if (baseline === 'center') {
  48140. y = -1 * layout.height / 2;
  48141. } else {
  48142. throw new TypeError('Invalid text.baseline property value', baseline);
  48143. }
  48144. // Position and scale mesh to apply layout.
  48145. mesh.position.x = x * textScale + data.xOffset;
  48146. mesh.position.y = y * textScale;
  48147. // Place text slightly in front to avoid Z-fighting.
  48148. mesh.position.z = data.zOffset;
  48149. mesh.scale.set(textScale, -1 * textScale, textScale);
  48150. },
  48151. /**
  48152. * Grab font from the constant.
  48153. * Set as a method for test stubbing purposes.
  48154. */
  48155. lookupFont: function (key) {
  48156. return FONTS[key];
  48157. },
  48158. /**
  48159. * Update the text geometry using `three-bmfont-text.update`.
  48160. */
  48161. updateGeometry: (function () {
  48162. var geometryUpdateBase = {};
  48163. var geometryUpdateData = {};
  48164. var newLineRegex = /\\n/g;
  48165. var tabRegex = /\\t/g;
  48166. return function (geometry, font) {
  48167. var data = this.data;
  48168. geometryUpdateData.font = font;
  48169. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  48170. ? data.lineHeight
  48171. : font.common.lineHeight;
  48172. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  48173. .replace(tabRegex, '\t');
  48174. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  48175. font.widthFactor);
  48176. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  48177. };
  48178. })()
  48179. });
  48180. /**
  48181. * Due to using negative scale, we return the opposite side specified.
  48182. * https://github.com/mrdoob/three.js/pull/12787/
  48183. */
  48184. function parseSide (side) {
  48185. switch (side) {
  48186. case 'back': {
  48187. return THREE.FrontSide;
  48188. }
  48189. case 'double': {
  48190. return THREE.DoubleSide;
  48191. }
  48192. default: {
  48193. return THREE.BackSide;
  48194. }
  48195. }
  48196. }
  48197. /**
  48198. * @returns {Promise}
  48199. */
  48200. function loadFont (src, yOffset) {
  48201. return new Promise(function (resolve, reject) {
  48202. loadBMFont(src, function (err, font) {
  48203. if (err) {
  48204. error('Error loading font', src);
  48205. reject(err);
  48206. return;
  48207. }
  48208. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  48209. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  48210. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  48211. resolve(font);
  48212. });
  48213. });
  48214. }
  48215. /**
  48216. * @returns {Promise}
  48217. */
  48218. function loadTexture (src) {
  48219. return new Promise(function (resolve, reject) {
  48220. new THREE.ImageLoader().load(src, function (image) {
  48221. resolve(image);
  48222. }, undefined, function () {
  48223. error('Error loading font image', src);
  48224. reject(null);
  48225. });
  48226. });
  48227. }
  48228. function createShader (el, shaderName, data) {
  48229. var shader;
  48230. var shaderObject;
  48231. // Set up Shader.
  48232. shaderObject = new shaders[shaderName].Shader();
  48233. shaderObject.el = el;
  48234. shaderObject.init(data);
  48235. shaderObject.update(data);
  48236. // Get material.
  48237. shader = shaderObject.material;
  48238. // Apparently, was not set on `init` nor `update`.
  48239. shader.transparent = data.transparent;
  48240. return {
  48241. material: shader,
  48242. shader: shaderObject
  48243. };
  48244. }
  48245. /**
  48246. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  48247. * Note that experimental factor will never be correct for variable width fonts.
  48248. */
  48249. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  48250. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  48251. }
  48252. /**
  48253. * Compute default font width factor to use.
  48254. */
  48255. function computeFontWidthFactor (font) {
  48256. var sum = 0;
  48257. var digitsum = 0;
  48258. var digits = 0;
  48259. font.chars.map(function (ch) {
  48260. sum += ch.xadvance;
  48261. if (ch.id >= 48 && ch.id <= 57) {
  48262. digits++;
  48263. digitsum += ch.xadvance;
  48264. }
  48265. });
  48266. return digits ? digitsum / digits : sum / font.chars.length;
  48267. }
  48268. /**
  48269. * Get or create a promise given a key and promise generator.
  48270. * @todo Move to a utility and use in other parts of A-Frame.
  48271. */
  48272. function PromiseCache () {
  48273. var cache = this.cache = {};
  48274. this.get = function (key, promiseGenerator) {
  48275. if (key in cache) {
  48276. return cache[key];
  48277. }
  48278. cache[key] = promiseGenerator();
  48279. return cache[key];
  48280. };
  48281. }
  48282. },{"../core/component":124,"../core/shader":134,"../lib/three":172,"../utils/":197,"load-bmfont":37,"three-bmfont-text":62}],108:[function(_dereq_,module,exports){
  48283. var registerComponent = _dereq_('../core/component').registerComponent;
  48284. var controllerUtils = _dereq_('../utils/tracked-controls');
  48285. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  48286. var THREE = _dereq_('../lib/three');
  48287. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  48288. // Vector from eyes to elbow (divided by user height).
  48289. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  48290. // Vector from eyes to elbow (divided by user height).
  48291. var FOREARM = {x: 0, y: 0, z: -0.175};
  48292. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  48293. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  48294. var EVENTS = {
  48295. AXISMOVE: 'axismove',
  48296. BUTTONCHANGED: 'buttonchanged',
  48297. BUTTONDOWN: 'buttondown',
  48298. BUTTONUP: 'buttonup',
  48299. TOUCHSTART: 'touchstart',
  48300. TOUCHEND: 'touchend'
  48301. };
  48302. /**
  48303. * Tracked controls component.
  48304. * Wrap the gamepad API for pose and button states.
  48305. * Select the appropriate controller and apply pose to the entity.
  48306. * Observe button states and emit appropriate events.
  48307. *
  48308. * @property {number} controller - Index of controller in array returned by Gamepad API.
  48309. * Only used if hand property is not set.
  48310. * @property {string} id - Selected controller among those returned by Gamepad API.
  48311. * @property {number} hand - If multiple controllers found with id, choose the one with the
  48312. * given value for hand. If set, we ignore 'controller' property
  48313. */
  48314. module.exports.Component = registerComponent('tracked-controls-webvr', {
  48315. schema: {
  48316. autoHide: {default: true},
  48317. controller: {default: 0},
  48318. id: {type: 'string', default: ''},
  48319. hand: {type: 'string', default: ''},
  48320. idPrefix: {type: 'string', default: ''},
  48321. orientationOffset: {type: 'vec3'},
  48322. // Arm model parameters when not 6DoF.
  48323. armModel: {default: true},
  48324. headElement: {type: 'selector'}
  48325. },
  48326. init: function () {
  48327. // Copy variables back to tracked-controls for backwards compatibility.
  48328. // Some 3rd components rely on them.
  48329. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  48330. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  48331. this.changedAxes = [];
  48332. this.targetControllerNumber = this.data.controller;
  48333. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  48334. this.deltaControllerPosition = new THREE.Vector3();
  48335. this.controllerQuaternion = new THREE.Quaternion();
  48336. this.controllerEuler = new THREE.Euler();
  48337. this.updateGamepad();
  48338. this.buttonEventDetails = {};
  48339. },
  48340. tick: function (time, delta) {
  48341. var mesh = this.el.getObject3D('mesh');
  48342. // Update mesh animations.
  48343. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  48344. this.updateGamepad();
  48345. this.updatePose();
  48346. this.updateButtons();
  48347. },
  48348. /**
  48349. * Return default user height to use for non-6DOF arm model.
  48350. */
  48351. defaultUserHeight: function () {
  48352. return DEFAULT_CAMERA_HEIGHT;
  48353. },
  48354. /**
  48355. * Return head element to use for non-6DOF arm model.
  48356. */
  48357. getHeadElement: function () {
  48358. return this.data.headElement || this.el.sceneEl.camera.el;
  48359. },
  48360. /**
  48361. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  48362. */
  48363. updateGamepad: function () {
  48364. var data = this.data;
  48365. var controller = controllerUtils.findMatchingControllerWebVR(
  48366. this.system.controllers,
  48367. data.id,
  48368. data.idPrefix,
  48369. data.hand,
  48370. data.controller
  48371. );
  48372. this.controller = controller;
  48373. // Legacy handle to the controller for old components.
  48374. this.el.components['tracked-controls'].controller = controller;
  48375. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  48376. },
  48377. /**
  48378. * Applies an artificial arm model to simulate elbow to wrist positioning
  48379. * based on the orientation of the controller.
  48380. *
  48381. * @param {object} controllerPosition - Existing vector to update with controller position.
  48382. */
  48383. applyArmModel: function (controllerPosition) {
  48384. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  48385. var controller = this.controller;
  48386. var controllerEuler = this.controllerEuler;
  48387. var controllerQuaternion = this.controllerQuaternion;
  48388. var deltaControllerPosition = this.deltaControllerPosition;
  48389. var hand;
  48390. var headEl;
  48391. var headObject3D;
  48392. var pose;
  48393. var userHeight;
  48394. headEl = this.getHeadElement();
  48395. headObject3D = headEl.object3D;
  48396. userHeight = this.defaultUserHeight();
  48397. pose = controller.pose;
  48398. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  48399. // Use camera position as head position.
  48400. controllerPosition.copy(headObject3D.position);
  48401. // Set offset for degenerate "arm model" to elbow.
  48402. deltaControllerPosition.set(
  48403. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  48404. EYES_TO_ELBOW.y, // Lower than our eyes.
  48405. EYES_TO_ELBOW.z); // Slightly out in front.
  48406. // Scale offset by user height.
  48407. deltaControllerPosition.multiplyScalar(userHeight);
  48408. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  48409. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  48410. // Apply rotated offset to position.
  48411. controllerPosition.add(deltaControllerPosition);
  48412. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  48413. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  48414. // Scale offset by user height.
  48415. deltaControllerPosition.multiplyScalar(userHeight);
  48416. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  48417. if (pose.orientation) {
  48418. controllerQuaternion.fromArray(pose.orientation);
  48419. } else {
  48420. controllerQuaternion.copy(headObject3D.quaternion);
  48421. }
  48422. controllerEuler.setFromQuaternion(controllerQuaternion);
  48423. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  48424. deltaControllerPosition.applyEuler(controllerEuler);
  48425. // Apply rotated offset to position.
  48426. controllerPosition.add(deltaControllerPosition);
  48427. },
  48428. /**
  48429. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  48430. */
  48431. updatePose: function () {
  48432. var controller = this.controller;
  48433. var data = this.data;
  48434. var object3D = this.el.object3D;
  48435. var pose;
  48436. var vrDisplay = this.system.vrDisplay;
  48437. var standingMatrix;
  48438. if (!controller) { return; }
  48439. // Compose pose from Gamepad.
  48440. pose = controller.pose;
  48441. if (pose.position) {
  48442. object3D.position.fromArray(pose.position);
  48443. } else {
  48444. // Controller not 6DOF, apply arm model.
  48445. if (data.armModel) { this.applyArmModel(object3D.position); }
  48446. }
  48447. if (pose.orientation) {
  48448. object3D.quaternion.fromArray(pose.orientation);
  48449. }
  48450. // Apply transforms, if 6DOF and in VR.
  48451. if (vrDisplay && pose.position) {
  48452. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  48453. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  48454. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  48455. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  48456. }
  48457. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  48458. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  48459. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  48460. },
  48461. /**
  48462. * Handle button changes including axes, presses, touches, values.
  48463. */
  48464. updateButtons: function () {
  48465. var buttonState;
  48466. var controller = this.controller;
  48467. var id;
  48468. if (!controller) { return; }
  48469. // Check every button.
  48470. for (id = 0; id < controller.buttons.length; ++id) {
  48471. // Initialize button state.
  48472. if (!this.buttonStates[id]) {
  48473. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  48474. }
  48475. if (!this.buttonEventDetails[id]) {
  48476. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  48477. }
  48478. buttonState = controller.buttons[id];
  48479. this.handleButton(id, buttonState);
  48480. }
  48481. // Check axes.
  48482. this.handleAxes();
  48483. },
  48484. /**
  48485. * Handle presses and touches for a single button.
  48486. *
  48487. * @param {number} id - Index of button in Gamepad button array.
  48488. * @param {number} buttonState - Value of button state from 0 to 1.
  48489. * @returns {boolean} Whether button has changed in any way.
  48490. */
  48491. handleButton: function (id, buttonState) {
  48492. var changed;
  48493. changed = this.handlePress(id, buttonState) |
  48494. this.handleTouch(id, buttonState) |
  48495. this.handleValue(id, buttonState);
  48496. if (!changed) { return false; }
  48497. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  48498. return true;
  48499. },
  48500. /**
  48501. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  48502. * Compare each component of the axis to the previous value to determine change.
  48503. *
  48504. * @returns {boolean} Whether axes changed.
  48505. */
  48506. handleAxes: function () {
  48507. var changed = false;
  48508. var controllerAxes = this.controller.axes;
  48509. var i;
  48510. var previousAxis = this.axis;
  48511. var changedAxes = this.changedAxes;
  48512. // Check if axis changed.
  48513. this.changedAxes.length = 0;
  48514. for (i = 0; i < controllerAxes.length; ++i) {
  48515. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  48516. if (changedAxes[i]) { changed = true; }
  48517. }
  48518. if (!changed) { return false; }
  48519. this.axis.length = 0;
  48520. for (i = 0; i < controllerAxes.length; i++) {
  48521. this.axis.push(controllerAxes[i]);
  48522. }
  48523. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  48524. return true;
  48525. },
  48526. /**
  48527. * Determine whether a button press has occured and emit events as appropriate.
  48528. *
  48529. * @param {string} id - ID of the button to check.
  48530. * @param {object} buttonState - State of the button to check.
  48531. * @returns {boolean} Whether button press state changed.
  48532. */
  48533. handlePress: function (id, buttonState) {
  48534. var evtName;
  48535. var previousButtonState = this.buttonStates[id];
  48536. // Not changed.
  48537. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  48538. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  48539. this.el.emit(evtName, this.buttonEventDetails[id], false);
  48540. previousButtonState.pressed = buttonState.pressed;
  48541. return true;
  48542. },
  48543. /**
  48544. * Determine whether a button touch has occured and emit events as appropriate.
  48545. *
  48546. * @param {string} id - ID of the button to check.
  48547. * @param {object} buttonState - State of the button to check.
  48548. * @returns {boolean} Whether button touch state changed.
  48549. */
  48550. handleTouch: function (id, buttonState) {
  48551. var evtName;
  48552. var previousButtonState = this.buttonStates[id];
  48553. // Not changed.
  48554. if (buttonState.touched === previousButtonState.touched) { return false; }
  48555. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  48556. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  48557. previousButtonState.touched = buttonState.touched;
  48558. return true;
  48559. },
  48560. /**
  48561. * Determine whether a button value has changed.
  48562. *
  48563. * @param {string} id - Id of the button to check.
  48564. * @param {object} buttonState - State of the button to check.
  48565. * @returns {boolean} Whether button value changed.
  48566. */
  48567. handleValue: function (id, buttonState) {
  48568. var previousButtonState = this.buttonStates[id];
  48569. // Not changed.
  48570. if (buttonState.value === previousButtonState.value) { return false; }
  48571. previousButtonState.value = buttonState.value;
  48572. return true;
  48573. }
  48574. });
  48575. },{"../constants":116,"../core/component":124,"../lib/three":172,"../utils/tracked-controls":205}],109:[function(_dereq_,module,exports){
  48576. var controllerUtils = _dereq_('../utils/tracked-controls');
  48577. var registerComponent = _dereq_('../core/component').registerComponent;
  48578. module.exports.Component = registerComponent('tracked-controls-webxr', {
  48579. schema: {
  48580. hand: {type: 'string', default: ''}
  48581. },
  48582. init: function () {
  48583. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  48584. this.updateController = this.updateController.bind(this);
  48585. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  48586. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  48587. this.buttonEventDetails = {id: 'trigger', state: {pressed: false}};
  48588. },
  48589. play: function () {
  48590. var sceneEl = this.el.sceneEl;
  48591. this.updateController();
  48592. this.addSessionEventListeners();
  48593. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  48594. sceneEl.addEventListener('controllersupdated', this.updateController);
  48595. },
  48596. pause: function () {
  48597. var sceneEl = this.el.sceneEl;
  48598. this.removeSessionEventListeners();
  48599. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  48600. sceneEl.removeEventListener('controllersupdated', this.updateController);
  48601. },
  48602. addSessionEventListeners: function () {
  48603. var sceneEl = this.el.sceneEl;
  48604. if (!sceneEl.xrSession) { return; }
  48605. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  48606. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  48607. },
  48608. removeSessionEventListeners: function () {
  48609. var sceneEl = this.el.sceneEl;
  48610. if (!sceneEl.xrSession) { return; }
  48611. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  48612. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  48613. },
  48614. emitButtonDownEvent: function (evt) {
  48615. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  48616. this.buttonEventDetails.state.pressed = true;
  48617. this.el.emit('buttondown', this.buttonEventDetails);
  48618. this.el.emit('buttonchanged', this.buttonEventDetails);
  48619. this.el.emit('triggerdown');
  48620. },
  48621. emitButtonUpEvent: function (evt) {
  48622. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  48623. this.buttonEventDetails.state.pressed = false;
  48624. this.el.emit('buttonup', this.buttonEventDetails);
  48625. this.el.emit('buttonchanged', this.buttonEventDetails);
  48626. this.el.emit('triggerup');
  48627. },
  48628. /**
  48629. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  48630. */
  48631. updateController: function () {
  48632. this.controller = controllerUtils.findMatchingControllerWebXR(
  48633. this.system.controllers,
  48634. this.data.hand
  48635. );
  48636. // Legacy handle to the controller for old components.
  48637. this.el.components['tracked-controls'].controller = this.controller;
  48638. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  48639. },
  48640. tick: function () {
  48641. var pose;
  48642. var sceneEl = this.el.sceneEl;
  48643. var object3D = this.el.object3D;
  48644. if (!this.controller || !sceneEl.frame) { return; }
  48645. pose = sceneEl.frame.getPose(this.controller.targetRaySpace, this.system.referenceSpace);
  48646. if (!pose) { return; }
  48647. object3D.matrix.elements = pose.transform.matrix;
  48648. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  48649. }
  48650. });
  48651. },{"../core/component":124,"../utils/tracked-controls":205}],110:[function(_dereq_,module,exports){
  48652. var registerComponent = _dereq_('../core/component').registerComponent;
  48653. /**
  48654. * Tracked controls.
  48655. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  48656. *
  48657. * @property {number} controller - Index of controller in array returned by Gamepad API.
  48658. * Only used if hand property is not set.
  48659. * @property {string} id - Selected controller among those returned by Gamepad API.
  48660. * @property {number} hand - If multiple controllers found with id, choose the one with the
  48661. * given value for hand. If set, we ignore 'controller' property
  48662. */
  48663. module.exports.Component = registerComponent('tracked-controls', {
  48664. schema: {
  48665. autoHide: {default: true},
  48666. controller: {default: 0},
  48667. id: {type: 'string', default: ''},
  48668. hand: {type: 'string', default: ''},
  48669. idPrefix: {type: 'string', default: ''},
  48670. orientationOffset: {type: 'vec3'},
  48671. // Arm model parameters when not 6DoF.
  48672. armModel: {default: true},
  48673. headElement: {type: 'selector'}
  48674. },
  48675. update: function () {
  48676. var data = this.data;
  48677. var el = this.el;
  48678. if (el.sceneEl.hasWebXR) {
  48679. el.setAttribute('tracked-controls-webxr', data);
  48680. } else {
  48681. el.setAttribute('tracked-controls-webvr', data);
  48682. }
  48683. }
  48684. });
  48685. },{"../core/component":124}],111:[function(_dereq_,module,exports){
  48686. var registerComponent = _dereq_('../core/component').registerComponent;
  48687. /**
  48688. * Visibility component.
  48689. */
  48690. module.exports.Component = registerComponent('visible', {
  48691. schema: {default: true},
  48692. update: function () {
  48693. this.el.object3D.visible = this.data;
  48694. }
  48695. });
  48696. },{"../core/component":124}],112:[function(_dereq_,module,exports){
  48697. var registerComponent = _dereq_('../core/component').registerComponent;
  48698. var bind = _dereq_('../utils/bind');
  48699. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48700. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48701. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48702. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48703. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  48704. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  48705. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  48706. /**
  48707. * Vive controls.
  48708. * Interface with Vive controllers and map Gamepad events to controller buttons:
  48709. * trackpad, trigger, grip, menu, system
  48710. * Load a controller model and highlight the pressed buttons.
  48711. */
  48712. module.exports.Component = registerComponent('vive-controls', {
  48713. schema: {
  48714. hand: {default: 'left'},
  48715. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  48716. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  48717. model: {default: true},
  48718. orientationOffset: {type: 'vec3'}
  48719. },
  48720. /**
  48721. * Button IDs:
  48722. * 0 - trackpad
  48723. * 1 - trigger (intensity value from 0.5 to 1)
  48724. * 2 - grip
  48725. * 3 - menu (dispatch but better for menu options)
  48726. * 4 - system (never dispatched on this layer)
  48727. */
  48728. mapping: {
  48729. axes: {trackpad: [0, 1]},
  48730. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  48731. },
  48732. init: function () {
  48733. var self = this;
  48734. this.controllerPresent = false;
  48735. this.lastControllerCheck = 0;
  48736. this.onButtonChanged = bind(this.onButtonChanged, this);
  48737. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48738. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48739. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48740. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48741. this.previousButtonValues = {};
  48742. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48743. this.bindMethods();
  48744. },
  48745. play: function () {
  48746. this.checkIfControllerPresent();
  48747. this.addControllersUpdateListener();
  48748. },
  48749. pause: function () {
  48750. this.removeEventListeners();
  48751. this.removeControllersUpdateListener();
  48752. },
  48753. bindMethods: function () {
  48754. this.onModelLoaded = bind(this.onModelLoaded, this);
  48755. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48756. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48757. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48758. this.onAxisMoved = bind(this.onAxisMoved, this);
  48759. },
  48760. addEventListeners: function () {
  48761. var el = this.el;
  48762. el.addEventListener('buttonchanged', this.onButtonChanged);
  48763. el.addEventListener('buttondown', this.onButtonDown);
  48764. el.addEventListener('buttonup', this.onButtonUp);
  48765. el.addEventListener('touchend', this.onButtonTouchEnd);
  48766. el.addEventListener('touchstart', this.onButtonTouchStart);
  48767. el.addEventListener('model-loaded', this.onModelLoaded);
  48768. el.addEventListener('axismove', this.onAxisMoved);
  48769. this.controllerEventsActive = true;
  48770. },
  48771. removeEventListeners: function () {
  48772. var el = this.el;
  48773. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48774. el.removeEventListener('buttondown', this.onButtonDown);
  48775. el.removeEventListener('buttonup', this.onButtonUp);
  48776. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48777. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48778. el.removeEventListener('model-loaded', this.onModelLoaded);
  48779. el.removeEventListener('axismove', this.onAxisMoved);
  48780. this.controllerEventsActive = false;
  48781. },
  48782. /**
  48783. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  48784. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  48785. { hand: data.hand });
  48786. * Until then, use hardcoded index.
  48787. */
  48788. checkIfControllerPresent: function () {
  48789. var data = this.data;
  48790. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  48791. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  48792. },
  48793. injectTrackedControls: function () {
  48794. var el = this.el;
  48795. var data = this.data;
  48796. // If we have an OpenVR Gamepad, use the fixed mapping.
  48797. el.setAttribute('tracked-controls', {
  48798. idPrefix: GAMEPAD_ID_PREFIX,
  48799. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  48800. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  48801. orientationOffset: data.orientationOffset
  48802. });
  48803. // Load model.
  48804. if (!this.data.model) { return; }
  48805. this.el.setAttribute('obj-model', {
  48806. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  48807. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  48808. });
  48809. },
  48810. addControllersUpdateListener: function () {
  48811. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48812. },
  48813. removeControllersUpdateListener: function () {
  48814. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48815. },
  48816. onControllersUpdate: function () {
  48817. this.checkIfControllerPresent();
  48818. },
  48819. /**
  48820. * Rotate the trigger button based on how hard the trigger is pressed.
  48821. */
  48822. onButtonChanged: function (evt) {
  48823. var button = this.mapping.buttons[evt.detail.id];
  48824. var buttonMeshes = this.buttonMeshes;
  48825. var analogValue;
  48826. if (!button) { return; }
  48827. if (button === 'trigger') {
  48828. analogValue = evt.detail.state.value;
  48829. // Update trigger rotation depending on button value.
  48830. if (buttonMeshes && buttonMeshes.trigger) {
  48831. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  48832. }
  48833. }
  48834. // Pass along changed event with button state, using button mapping for convenience.
  48835. this.el.emit(button + 'changed', evt.detail.state);
  48836. },
  48837. onModelLoaded: function (evt) {
  48838. var buttonMeshes;
  48839. var controllerObject3D = evt.detail.model;
  48840. var self = this;
  48841. if (!this.data.model) { return; }
  48842. // Store button meshes object to be able to change their colors.
  48843. buttonMeshes = this.buttonMeshes = {};
  48844. buttonMeshes.grip = {
  48845. left: controllerObject3D.getObjectByName('leftgrip'),
  48846. right: controllerObject3D.getObjectByName('rightgrip')
  48847. };
  48848. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  48849. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  48850. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  48851. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  48852. // Set default colors.
  48853. Object.keys(buttonMeshes).forEach(function (buttonName) {
  48854. self.setButtonColor(buttonName, self.data.buttonColor);
  48855. });
  48856. // Offset pivot point.
  48857. controllerObject3D.position.set(0, -0.015, 0.04);
  48858. },
  48859. onAxisMoved: function (evt) {
  48860. emitIfAxesChanged(this, this.mapping.axes, evt);
  48861. },
  48862. updateModel: function (buttonName, evtName) {
  48863. var color;
  48864. var isTouch;
  48865. if (!this.data.model) { return; }
  48866. isTouch = evtName.indexOf('touch') !== -1;
  48867. // Don't change color for trackpad touch.
  48868. if (isTouch) { return; }
  48869. // Update colors.
  48870. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  48871. this.setButtonColor(buttonName, color);
  48872. },
  48873. setButtonColor: function (buttonName, color) {
  48874. var buttonMeshes = this.buttonMeshes;
  48875. var rendererSystem = this.rendererSystem;
  48876. if (!buttonMeshes) { return; }
  48877. // Need to do both left and right sides for grip.
  48878. if (buttonName === 'grip') {
  48879. buttonMeshes.grip.left.material.color.set(color);
  48880. buttonMeshes.grip.right.material.color.set(color);
  48881. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  48882. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  48883. return;
  48884. }
  48885. buttonMeshes[buttonName].material.color.set(color);
  48886. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  48887. }
  48888. });
  48889. },{"../core/component":124,"../utils/bind":191,"../utils/tracked-controls":205}],113:[function(_dereq_,module,exports){
  48890. var registerComponent = _dereq_('../core/component').registerComponent;
  48891. var bind = _dereq_('../utils/bind');
  48892. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48893. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48894. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48895. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48896. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  48897. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  48898. /**
  48899. * Vive Focus controls.
  48900. * Interface with Vive Focus controller and map Gamepad events to
  48901. * controller buttons: trackpad, trigger
  48902. * Load a controller model and highlight the pressed buttons.
  48903. */
  48904. module.exports.Component = registerComponent('vive-focus-controls', {
  48905. schema: {
  48906. hand: {default: ''}, // This informs the degenerate arm model.
  48907. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  48908. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  48909. model: {default: true},
  48910. orientationOffset: {type: 'vec3'},
  48911. armModel: {default: true}
  48912. },
  48913. /**
  48914. * Button IDs:
  48915. * 0 - trackpad
  48916. * 1 - trigger
  48917. */
  48918. mapping: {
  48919. axes: {trackpad: [0, 1]},
  48920. buttons: ['trigger', 'trackpad']
  48921. },
  48922. bindMethods: function () {
  48923. this.onModelLoaded = bind(this.onModelLoaded, this);
  48924. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48925. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48926. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48927. this.onAxisMoved = bind(this.onAxisMoved, this);
  48928. },
  48929. init: function () {
  48930. var self = this;
  48931. this.onButtonChanged = bind(this.onButtonChanged, this);
  48932. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48933. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48934. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48935. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48936. this.controllerPresent = false;
  48937. this.lastControllerCheck = 0;
  48938. this.bindMethods();
  48939. },
  48940. addEventListeners: function () {
  48941. var el = this.el;
  48942. el.addEventListener('buttonchanged', this.onButtonChanged);
  48943. el.addEventListener('buttondown', this.onButtonDown);
  48944. el.addEventListener('buttonup', this.onButtonUp);
  48945. el.addEventListener('touchstart', this.onButtonTouchStart);
  48946. el.addEventListener('touchend', this.onButtonTouchEnd);
  48947. el.addEventListener('model-loaded', this.onModelLoaded);
  48948. el.addEventListener('axismove', this.onAxisMoved);
  48949. this.controllerEventsActive = true;
  48950. this.addControllersUpdateListener();
  48951. },
  48952. removeEventListeners: function () {
  48953. var el = this.el;
  48954. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48955. el.removeEventListener('buttondown', this.onButtonDown);
  48956. el.removeEventListener('buttonup', this.onButtonUp);
  48957. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48958. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48959. el.removeEventListener('model-loaded', this.onModelLoaded);
  48960. el.removeEventListener('axismove', this.onAxisMoved);
  48961. this.controllerEventsActive = false;
  48962. this.removeControllersUpdateListener();
  48963. },
  48964. checkIfControllerPresent: function () {
  48965. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  48966. this.data.hand ? {hand: this.data.hand} : {});
  48967. },
  48968. play: function () {
  48969. this.checkIfControllerPresent();
  48970. this.addControllersUpdateListener();
  48971. },
  48972. pause: function () {
  48973. this.removeEventListeners();
  48974. this.removeControllersUpdateListener();
  48975. },
  48976. injectTrackedControls: function () {
  48977. var el = this.el;
  48978. var data = this.data;
  48979. el.setAttribute('tracked-controls', {
  48980. armModel: data.armModel,
  48981. idPrefix: GAMEPAD_ID_PREFIX,
  48982. orientationOffset: data.orientationOffset
  48983. });
  48984. if (!this.data.model) { return; }
  48985. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  48986. },
  48987. addControllersUpdateListener: function () {
  48988. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48989. },
  48990. removeControllersUpdateListener: function () {
  48991. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48992. },
  48993. onControllersUpdate: function () {
  48994. this.checkIfControllerPresent();
  48995. },
  48996. onModelLoaded: function (evt) {
  48997. var controllerObject3D = evt.detail.model;
  48998. var buttonMeshes;
  48999. if (!this.data.model) { return; }
  49000. buttonMeshes = this.buttonMeshes = {};
  49001. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  49002. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  49003. if (buttonMeshes.triggerPressed) {
  49004. buttonMeshes.triggerPressed.visible = false;
  49005. }
  49006. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  49007. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  49008. if (buttonMeshes.trackpadPressed) {
  49009. buttonMeshes.trackpadPressed.visible = false;
  49010. }
  49011. },
  49012. // No analog buttons, only emits 0/1 values
  49013. onButtonChanged: function (evt) {
  49014. var button = this.mapping.buttons[evt.detail.id];
  49015. if (!button) return;
  49016. // Pass along changed event with button state, using button mapping for convenience.
  49017. this.el.emit(button + 'changed', evt.detail.state);
  49018. },
  49019. onAxisMoved: function (evt) {
  49020. emitIfAxesChanged(this, this.mapping.axes, evt);
  49021. },
  49022. updateModel: function (buttonName, evtName) {
  49023. if (!this.data.model) { return; }
  49024. this.updateButtonModel(buttonName, evtName);
  49025. },
  49026. updateButtonModel: function (buttonName, state) {
  49027. var buttonMeshes = this.buttonMeshes;
  49028. var pressedName = buttonName + 'Pressed';
  49029. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  49030. return;
  49031. }
  49032. var color;
  49033. switch (state) {
  49034. case 'down':
  49035. color = this.data.buttonHighlightColor;
  49036. break;
  49037. case 'touchstart':
  49038. color = this.data.buttonTouchedColor;
  49039. break;
  49040. }
  49041. if (color) {
  49042. buttonMeshes[pressedName].material.color.set(color);
  49043. }
  49044. buttonMeshes[pressedName].visible = !!color;
  49045. buttonMeshes[buttonName].visible = !color;
  49046. }
  49047. });
  49048. },{"../core/component":124,"../utils/bind":191,"../utils/tracked-controls":205}],114:[function(_dereq_,module,exports){
  49049. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  49050. var registerComponent = _dereq_('../core/component').registerComponent;
  49051. var THREE = _dereq_('../lib/three');
  49052. var utils = _dereq_('../utils/');
  49053. var bind = utils.bind;
  49054. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  49055. var CLAMP_VELOCITY = 0.00001;
  49056. var MAX_DELTA = 0.2;
  49057. var KEYS = [
  49058. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  49059. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  49060. ];
  49061. /**
  49062. * WASD component to control entities using WASD keys.
  49063. */
  49064. module.exports.Component = registerComponent('wasd-controls', {
  49065. schema: {
  49066. acceleration: {default: 65},
  49067. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  49068. adEnabled: {default: true},
  49069. adInverted: {default: false},
  49070. enabled: {default: true},
  49071. fly: {default: false},
  49072. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  49073. wsEnabled: {default: true},
  49074. wsInverted: {default: false}
  49075. },
  49076. init: function () {
  49077. // To keep track of the pressed keys.
  49078. this.keys = {};
  49079. this.easing = 1.1;
  49080. this.velocity = new THREE.Vector3();
  49081. // Bind methods and add event listeners.
  49082. this.onBlur = bind(this.onBlur, this);
  49083. this.onFocus = bind(this.onFocus, this);
  49084. this.onKeyDown = bind(this.onKeyDown, this);
  49085. this.onKeyUp = bind(this.onKeyUp, this);
  49086. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  49087. this.attachVisibilityEventListeners();
  49088. },
  49089. tick: function (time, delta) {
  49090. var data = this.data;
  49091. var el = this.el;
  49092. var velocity = this.velocity;
  49093. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  49094. isEmptyObject(this.keys)) { return; }
  49095. // Update velocity.
  49096. delta = delta / 1000;
  49097. this.updateVelocity(delta);
  49098. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  49099. // Get movement vector and translate position.
  49100. el.object3D.position.add(this.getMovementVector(delta));
  49101. },
  49102. remove: function () {
  49103. this.removeKeyEventListeners();
  49104. this.removeVisibilityEventListeners();
  49105. },
  49106. play: function () {
  49107. this.attachKeyEventListeners();
  49108. },
  49109. pause: function () {
  49110. this.keys = {};
  49111. this.removeKeyEventListeners();
  49112. },
  49113. updateVelocity: function (delta) {
  49114. var acceleration;
  49115. var adAxis;
  49116. var adSign;
  49117. var data = this.data;
  49118. var keys = this.keys;
  49119. var velocity = this.velocity;
  49120. var wsAxis;
  49121. var wsSign;
  49122. adAxis = data.adAxis;
  49123. wsAxis = data.wsAxis;
  49124. // If FPS too low, reset velocity.
  49125. if (delta > MAX_DELTA) {
  49126. velocity[adAxis] = 0;
  49127. velocity[wsAxis] = 0;
  49128. return;
  49129. }
  49130. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  49131. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  49132. // Velocity Easing.
  49133. if (velocity[adAxis] !== 0) {
  49134. velocity[adAxis] -= velocity[adAxis] * scaledEasing;
  49135. }
  49136. if (velocity[wsAxis] !== 0) {
  49137. velocity[wsAxis] -= velocity[wsAxis] * scaledEasing;
  49138. }
  49139. // Clamp velocity easing.
  49140. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  49141. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  49142. if (!data.enabled) { return; }
  49143. // Update velocity using keys pressed.
  49144. acceleration = data.acceleration;
  49145. if (data.adEnabled) {
  49146. adSign = data.adInverted ? -1 : 1;
  49147. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  49148. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  49149. }
  49150. if (data.wsEnabled) {
  49151. wsSign = data.wsInverted ? -1 : 1;
  49152. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  49153. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  49154. }
  49155. },
  49156. getMovementVector: (function () {
  49157. var directionVector = new THREE.Vector3(0, 0, 0);
  49158. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  49159. return function (delta) {
  49160. var rotation = this.el.getAttribute('rotation');
  49161. var velocity = this.velocity;
  49162. var xRotation;
  49163. directionVector.copy(velocity);
  49164. directionVector.multiplyScalar(delta);
  49165. // Absolute.
  49166. if (!rotation) { return directionVector; }
  49167. xRotation = this.data.fly ? rotation.x : 0;
  49168. // Transform direction relative to heading.
  49169. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  49170. directionVector.applyEuler(rotationEuler);
  49171. return directionVector;
  49172. };
  49173. })(),
  49174. attachVisibilityEventListeners: function () {
  49175. window.addEventListener('blur', this.onBlur);
  49176. window.addEventListener('focus', this.onFocus);
  49177. document.addEventListener('visibilitychange', this.onVisibilityChange);
  49178. },
  49179. removeVisibilityEventListeners: function () {
  49180. window.removeEventListener('blur', this.onBlur);
  49181. window.removeEventListener('focus', this.onFocus);
  49182. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  49183. },
  49184. attachKeyEventListeners: function () {
  49185. window.addEventListener('keydown', this.onKeyDown);
  49186. window.addEventListener('keyup', this.onKeyUp);
  49187. },
  49188. removeKeyEventListeners: function () {
  49189. window.removeEventListener('keydown', this.onKeyDown);
  49190. window.removeEventListener('keyup', this.onKeyUp);
  49191. },
  49192. onBlur: function () {
  49193. this.pause();
  49194. },
  49195. onFocus: function () {
  49196. this.play();
  49197. },
  49198. onVisibilityChange: function () {
  49199. if (document.hidden) {
  49200. this.onBlur();
  49201. } else {
  49202. this.onFocus();
  49203. }
  49204. },
  49205. onKeyDown: function (event) {
  49206. var code;
  49207. if (!shouldCaptureKeyEvent(event)) { return; }
  49208. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  49209. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  49210. },
  49211. onKeyUp: function (event) {
  49212. var code;
  49213. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  49214. delete this.keys[code];
  49215. }
  49216. });
  49217. function isEmptyObject (keys) {
  49218. var key;
  49219. for (key in keys) { return false; }
  49220. return true;
  49221. }
  49222. },{"../constants":116,"../core/component":124,"../lib/three":172,"../utils/":197}],115:[function(_dereq_,module,exports){
  49223. /* global THREE */
  49224. var registerComponent = _dereq_('../core/component').registerComponent;
  49225. var bind = _dereq_('../utils/bind');
  49226. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49227. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49228. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49229. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49230. var utils = _dereq_('../utils/');
  49231. var debug = utils.debug('components:windows-motion-controls:debug');
  49232. var warn = utils.debug('components:windows-motion-controls:warn');
  49233. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  49234. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  49235. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  49236. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  49237. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  49238. /**
  49239. * Windows Motion Controller controls.
  49240. * Interface with Windows Motion Controller controllers and map Gamepad events to
  49241. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  49242. * Load a controller model and transform the pressed buttons.
  49243. */
  49244. module.exports.Component = registerComponent('windows-motion-controls', {
  49245. schema: {
  49246. hand: {default: DEFAULT_HANDEDNESS},
  49247. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  49248. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  49249. pair: {default: 0},
  49250. // If true, loads the controller glTF asset.
  49251. model: {default: true},
  49252. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  49253. hideDisconnected: {default: true}
  49254. },
  49255. mapping: {
  49256. // A-Frame specific semantic axis names
  49257. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  49258. // A-Frame specific semantic button names
  49259. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  49260. // A mapping of the semantic name to node name in the glTF model file,
  49261. // that should be transformed by axis value.
  49262. // This array mirrors the browser Gamepad.axes array, such that
  49263. // the mesh corresponding to axis 0 is in this array index 0.
  49264. axisMeshNames: [
  49265. 'THUMBSTICK_X',
  49266. 'THUMBSTICK_Y',
  49267. 'TOUCHPAD_TOUCH_X',
  49268. 'TOUCHPAD_TOUCH_Y'
  49269. ],
  49270. // A mapping of the semantic name to button node name in the glTF model file,
  49271. // that should be transformed by button value.
  49272. buttonMeshNames: {
  49273. 'trigger': 'SELECT',
  49274. 'menu': 'MENU',
  49275. 'grip': 'GRASP',
  49276. 'thumbstick': 'THUMBSTICK_PRESS',
  49277. 'trackpad': 'TOUCHPAD_PRESS'
  49278. },
  49279. pointingPoseMeshName: 'POINTING_POSE'
  49280. },
  49281. bindMethods: function () {
  49282. this.onModelError = bind(this.onModelError, this);
  49283. this.onModelLoaded = bind(this.onModelLoaded, this);
  49284. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49285. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49286. this.onAxisMoved = bind(this.onAxisMoved, this);
  49287. },
  49288. init: function () {
  49289. var self = this;
  49290. var el = this.el;
  49291. this.onButtonChanged = bind(this.onButtonChanged, this);
  49292. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49293. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49294. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49295. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49296. this.onControllerConnected = function () { self.setModelVisibility(true); };
  49297. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  49298. this.controllerPresent = false;
  49299. this.lastControllerCheck = 0;
  49300. this.previousButtonValues = {};
  49301. this.bindMethods();
  49302. // Cache for submeshes that we have looked up by name.
  49303. this.loadedMeshInfo = {
  49304. buttonMeshes: null,
  49305. axisMeshes: null
  49306. };
  49307. // Pointing poses
  49308. this.rayOrigin = {
  49309. origin: new THREE.Vector3(),
  49310. direction: new THREE.Vector3(0, 0, -1),
  49311. createdFromMesh: false
  49312. };
  49313. el.addEventListener('controllerconnected', this.onControllerConnected);
  49314. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  49315. },
  49316. addEventListeners: function () {
  49317. var el = this.el;
  49318. el.addEventListener('buttonchanged', this.onButtonChanged);
  49319. el.addEventListener('buttondown', this.onButtonDown);
  49320. el.addEventListener('buttonup', this.onButtonUp);
  49321. el.addEventListener('touchstart', this.onButtonTouchStart);
  49322. el.addEventListener('touchend', this.onButtonTouchEnd);
  49323. el.addEventListener('axismove', this.onAxisMoved);
  49324. el.addEventListener('model-error', this.onModelError);
  49325. el.addEventListener('model-loaded', this.onModelLoaded);
  49326. this.controllerEventsActive = true;
  49327. },
  49328. removeEventListeners: function () {
  49329. var el = this.el;
  49330. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49331. el.removeEventListener('buttondown', this.onButtonDown);
  49332. el.removeEventListener('buttonup', this.onButtonUp);
  49333. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49334. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49335. el.removeEventListener('axismove', this.onAxisMoved);
  49336. el.removeEventListener('model-error', this.onModelError);
  49337. el.removeEventListener('model-loaded', this.onModelLoaded);
  49338. this.controllerEventsActive = false;
  49339. },
  49340. checkIfControllerPresent: function () {
  49341. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  49342. hand: this.data.hand,
  49343. index: this.data.pair
  49344. });
  49345. },
  49346. play: function () {
  49347. this.checkIfControllerPresent();
  49348. this.addControllersUpdateListener();
  49349. },
  49350. pause: function () {
  49351. this.removeEventListeners();
  49352. this.removeControllersUpdateListener();
  49353. },
  49354. updateControllerModel: function () {
  49355. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  49356. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  49357. this.modelReady();
  49358. return;
  49359. }
  49360. var sourceUrl = this.createControllerModelUrl();
  49361. this.loadModel(sourceUrl);
  49362. },
  49363. /**
  49364. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  49365. * art assets.
  49366. */
  49367. createControllerModelUrl: function (forceDefault) {
  49368. // Determine the device specific folder based on the ID suffix
  49369. var trackedControlsComponent = this.el.components['tracked-controls'];
  49370. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  49371. var device = 'default';
  49372. var hand = this.data.hand;
  49373. var filename;
  49374. if (controller) {
  49375. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  49376. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  49377. // In this case, we want to load the universal model, so need to get the '' from the controller.
  49378. hand = controller.hand;
  49379. if (!forceDefault) {
  49380. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  49381. device = ((match && match[0]) || device);
  49382. }
  49383. }
  49384. // Hand
  49385. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  49386. // Final url
  49387. return MODEL_BASE_URL + device + '/' + filename;
  49388. },
  49389. injectTrackedControls: function () {
  49390. var data = this.data;
  49391. this.el.setAttribute('tracked-controls', {
  49392. idPrefix: GAMEPAD_ID_PREFIX,
  49393. controller: data.pair,
  49394. hand: data.hand,
  49395. armModel: false
  49396. });
  49397. this.updateControllerModel();
  49398. },
  49399. addControllersUpdateListener: function () {
  49400. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49401. },
  49402. removeControllersUpdateListener: function () {
  49403. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49404. },
  49405. onControllersUpdate: function () {
  49406. this.checkIfControllerPresent();
  49407. },
  49408. onModelError: function (evt) {
  49409. var defaultUrl = this.createControllerModelUrl(true);
  49410. if (evt.detail.src !== defaultUrl) {
  49411. warn('Failed to load controller model for device, attempting to load default.');
  49412. this.loadModel(defaultUrl);
  49413. } else {
  49414. warn('Failed to load default controller model.');
  49415. }
  49416. },
  49417. loadModel: function (url) {
  49418. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  49419. // removed and re-loaded if the given url changes.
  49420. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  49421. },
  49422. onModelLoaded: function (evt) {
  49423. var rootNode = this.controllerModel = evt.detail.model;
  49424. var loadedMeshInfo = this.loadedMeshInfo;
  49425. var i;
  49426. var meshName;
  49427. var mesh;
  49428. var meshInfo;
  49429. debug('Processing model');
  49430. // Reset the caches
  49431. loadedMeshInfo.buttonMeshes = {};
  49432. loadedMeshInfo.axisMeshes = {};
  49433. // Cache our meshes so we aren't traversing the hierarchy per frame
  49434. if (rootNode) {
  49435. // Button Meshes
  49436. for (i = 0; i < this.mapping.buttons.length; i++) {
  49437. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  49438. if (!meshName) {
  49439. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  49440. continue;
  49441. }
  49442. mesh = rootNode.getObjectByName(meshName);
  49443. if (!mesh) {
  49444. warn('Missing button mesh with name: ' + meshName);
  49445. continue;
  49446. }
  49447. meshInfo = {
  49448. index: i,
  49449. value: getImmediateChildByName(mesh, 'VALUE'),
  49450. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  49451. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  49452. };
  49453. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  49454. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  49455. } else {
  49456. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  49457. warn('Missing button submesh under mesh with name: ' + meshName +
  49458. '(VALUE: ' + !!meshInfo.value +
  49459. ', PRESSED: ' + !!meshInfo.pressed +
  49460. ', UNPRESSED:' + !!meshInfo.unpressed +
  49461. ')');
  49462. }
  49463. }
  49464. // Axis Meshes
  49465. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  49466. meshName = this.mapping.axisMeshNames[i];
  49467. if (!meshName) {
  49468. debug('Skipping unknown axis at index: ' + i);
  49469. continue;
  49470. }
  49471. mesh = rootNode.getObjectByName(meshName);
  49472. if (!mesh) {
  49473. warn('Missing axis mesh with name: ' + meshName);
  49474. continue;
  49475. }
  49476. meshInfo = {
  49477. index: i,
  49478. value: getImmediateChildByName(mesh, 'VALUE'),
  49479. min: getImmediateChildByName(mesh, 'MIN'),
  49480. max: getImmediateChildByName(mesh, 'MAX')
  49481. };
  49482. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  49483. loadedMeshInfo.axisMeshes[i] = meshInfo;
  49484. } else {
  49485. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  49486. warn('Missing axis submesh under mesh with name: ' + meshName +
  49487. '(VALUE: ' + !!meshInfo.value +
  49488. ', MIN: ' + !!meshInfo.min +
  49489. ', MAX:' + !!meshInfo.max +
  49490. ')');
  49491. }
  49492. }
  49493. this.calculateRayOriginFromMesh(rootNode);
  49494. // Determine if the model has to be visible or not.
  49495. this.setModelVisibility();
  49496. }
  49497. debug('Model load complete.');
  49498. // Look through only immediate children. This will return null if no mesh exists with the given name.
  49499. function getImmediateChildByName (object3d, value) {
  49500. for (var i = 0, l = object3d.children.length; i < l; i++) {
  49501. var obj = object3d.children[i];
  49502. if (obj && obj['name'] === value) {
  49503. return obj;
  49504. }
  49505. }
  49506. return undefined;
  49507. }
  49508. },
  49509. calculateRayOriginFromMesh: (function () {
  49510. var quaternion = new THREE.Quaternion();
  49511. return function (rootNode) {
  49512. var mesh;
  49513. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  49514. // in the glTF (assumes that root node is at world origin)
  49515. this.rayOrigin.origin.set(0, 0, 0);
  49516. this.rayOrigin.direction.set(0, 0, -1);
  49517. this.rayOrigin.createdFromMesh = true;
  49518. // Try to read Pointing pose from the source model
  49519. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  49520. if (mesh) {
  49521. var parent = rootNode.parent;
  49522. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  49523. if (parent) {
  49524. rootNode.parent = null;
  49525. rootNode.updateMatrixWorld(true);
  49526. rootNode.parent = parent;
  49527. }
  49528. mesh.getWorldPosition(this.rayOrigin.origin);
  49529. mesh.getWorldQuaternion(quaternion);
  49530. this.rayOrigin.direction.applyQuaternion(quaternion);
  49531. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  49532. if (parent) {
  49533. rootNode.updateMatrixWorld(true);
  49534. }
  49535. } else {
  49536. debug('Mesh does not contain pointing origin data, defaulting to none.');
  49537. }
  49538. // Emit event stating that our pointing ray is now accurate.
  49539. this.modelReady();
  49540. };
  49541. })(),
  49542. lerpAxisTransform: (function () {
  49543. var quaternion = new THREE.Quaternion();
  49544. return function (axis, axisValue) {
  49545. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  49546. if (!axisMeshInfo) return;
  49547. var min = axisMeshInfo.min;
  49548. var max = axisMeshInfo.max;
  49549. var target = axisMeshInfo.value;
  49550. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  49551. var lerpValue = axisValue * 0.5 + 0.5;
  49552. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  49553. target.position.lerpVectors(min.position, max.position, lerpValue);
  49554. };
  49555. })(),
  49556. lerpButtonTransform: (function () {
  49557. var quaternion = new THREE.Quaternion();
  49558. return function (buttonName, buttonValue) {
  49559. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  49560. if (!buttonMeshInfo) return;
  49561. var min = buttonMeshInfo.unpressed;
  49562. var max = buttonMeshInfo.pressed;
  49563. var target = buttonMeshInfo.value;
  49564. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  49565. target.position.lerpVectors(min.position, max.position, buttonValue);
  49566. };
  49567. })(),
  49568. modelReady: function () {
  49569. this.el.emit('controllermodelready', {
  49570. name: 'windows-motion-controls',
  49571. model: this.data.model,
  49572. rayOrigin: this.rayOrigin
  49573. });
  49574. },
  49575. onButtonChanged: function (evt) {
  49576. var buttonName = this.mapping.buttons[evt.detail.id];
  49577. if (buttonName) {
  49578. // Update the button mesh transform
  49579. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  49580. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  49581. }
  49582. // Only emit events for buttons that we know how to map from index to name
  49583. this.el.emit(buttonName + 'changed', evt.detail.state);
  49584. }
  49585. },
  49586. onAxisMoved: function (evt) {
  49587. var numAxes = this.mapping.axisMeshNames.length;
  49588. // Only attempt to update meshes if we have valid data.
  49589. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  49590. for (var axis = 0; axis < numAxes; axis++) {
  49591. // Update the button mesh transform
  49592. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  49593. }
  49594. }
  49595. emitIfAxesChanged(this, this.mapping.axes, evt);
  49596. },
  49597. setModelVisibility: function (visible) {
  49598. var model = this.el.getObject3D('mesh');
  49599. visible = visible !== undefined ? visible : this.modelVisible;
  49600. this.modelVisible = visible;
  49601. if (!model) { return; }
  49602. model.visible = visible;
  49603. }
  49604. });
  49605. },{"../constants":116,"../core/component":124,"../utils/":197,"../utils/bind":191,"../utils/tracked-controls":205}],116:[function(_dereq_,module,exports){
  49606. module.exports = {
  49607. AFRAME_INJECTED: 'aframe-injected',
  49608. DEFAULT_CAMERA_HEIGHT: 1.6,
  49609. DEFAULT_HANDEDNESS: 'right',
  49610. keyboardevent: _dereq_('./keyboardevent')
  49611. };
  49612. },{"./keyboardevent":117}],117:[function(_dereq_,module,exports){
  49613. module.exports = {
  49614. // Tiny KeyboardEvent.code polyfill.
  49615. KEYCODE_TO_CODE: {
  49616. '38': 'ArrowUp',
  49617. '37': 'ArrowLeft',
  49618. '40': 'ArrowDown',
  49619. '39': 'ArrowRight',
  49620. '87': 'KeyW',
  49621. '65': 'KeyA',
  49622. '83': 'KeyS',
  49623. '68': 'KeyD'
  49624. }
  49625. };
  49626. },{}],118:[function(_dereq_,module,exports){
  49627. var ANode = _dereq_('./a-node');
  49628. var bind = _dereq_('../utils/bind');
  49629. var debug = _dereq_('../utils/debug');
  49630. var registerElement = _dereq_('./a-register-element').registerElement;
  49631. var THREE = _dereq_('../lib/three');
  49632. var fileLoader = new THREE.FileLoader();
  49633. var warn = debug('core:a-assets:warn');
  49634. var GLTF_HEADER_MAGIC = 'glTF';
  49635. /**
  49636. * Asset management system. Handles blocking on asset loading.
  49637. */
  49638. module.exports = registerElement('a-assets', {
  49639. prototype: Object.create(ANode.prototype, {
  49640. createdCallback: {
  49641. value: function () {
  49642. this.isAssets = true;
  49643. this.fileLoader = fileLoader;
  49644. this.timeout = null;
  49645. }
  49646. },
  49647. attachedCallback: {
  49648. value: function () {
  49649. var self = this;
  49650. var i;
  49651. var loaded = [];
  49652. var mediaEl;
  49653. var mediaEls;
  49654. var imgEl;
  49655. var imgEls;
  49656. var timeout;
  49657. if (!this.parentNode.isScene) {
  49658. throw new Error('<a-assets> must be a child of a <a-scene>.');
  49659. }
  49660. // Wait for <img>s.
  49661. imgEls = this.querySelectorAll('img');
  49662. for (i = 0; i < imgEls.length; i++) {
  49663. imgEl = fixUpMediaElement(imgEls[i]);
  49664. loaded.push(new Promise(function (resolve, reject) {
  49665. // Set in cache because we won't be needing to call three.js loader if we have.
  49666. // a loaded media element.
  49667. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  49668. imgEl.onload = resolve;
  49669. imgEl.onerror = reject;
  49670. }));
  49671. }
  49672. // Wait for <audio>s and <video>s.
  49673. mediaEls = this.querySelectorAll('audio, video');
  49674. for (i = 0; i < mediaEls.length; i++) {
  49675. mediaEl = fixUpMediaElement(mediaEls[i]);
  49676. if (!mediaEl.src && !mediaEl.srcObject) {
  49677. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  49678. }
  49679. loaded.push(mediaElementLoaded(mediaEl));
  49680. }
  49681. // Trigger loaded for scene to start rendering.
  49682. Promise.all(loaded).then(bind(this.load, this));
  49683. // Timeout to start loading anyways.
  49684. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  49685. this.timeout = setTimeout(function () {
  49686. if (self.hasLoaded) { return; }
  49687. warn('Asset loading timed out in ', timeout, 'ms');
  49688. self.emit('timeout');
  49689. self.load();
  49690. }, timeout);
  49691. }
  49692. },
  49693. detachedCallback: {
  49694. value: function () {
  49695. if (this.timeout) { clearTimeout(this.timeout); }
  49696. }
  49697. },
  49698. load: {
  49699. value: function () {
  49700. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  49701. return el.isAssetItem && el.hasAttribute('src');
  49702. });
  49703. }
  49704. }
  49705. })
  49706. });
  49707. /**
  49708. * Preload using XHRLoader for any type of asset.
  49709. */
  49710. registerElement('a-asset-item', {
  49711. prototype: Object.create(ANode.prototype, {
  49712. createdCallback: {
  49713. value: function () {
  49714. this.data = null;
  49715. this.isAssetItem = true;
  49716. }
  49717. },
  49718. attachedCallback: {
  49719. value: function () {
  49720. var self = this;
  49721. var src = this.getAttribute('src');
  49722. var responseType = this.getAttribute('response-type');
  49723. fileLoader.setResponseType(responseType || 'text');
  49724. fileLoader.load(src, function handleOnLoad (response) {
  49725. // if the response type is not given, check for the GLTF header
  49726. // and convert the response to an arraybuffer if it is present.
  49727. if (!responseType && (response.indexOf(GLTF_HEADER_MAGIC) === 0)) {
  49728. self.data = getArrayBuffer(response);
  49729. } else {
  49730. self.data = response;
  49731. }
  49732. /*
  49733. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  49734. previous one closes, the second request never finishes.
  49735. setTimeout finishes the first request and lets the logic triggered by load open
  49736. subsequent requests.
  49737. setTimeout can be removed once the fix for the bug below ships:
  49738. 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
  49739. */
  49740. setTimeout(function load () { ANode.prototype.load.call(self); });
  49741. }, function handleOnProgress (xhr) {
  49742. self.emit('progress', {
  49743. loadedBytes: xhr.loaded,
  49744. totalBytes: xhr.total,
  49745. xhr: xhr
  49746. });
  49747. }, function handleOnError (xhr) {
  49748. self.emit('error', {xhr: xhr});
  49749. });
  49750. }
  49751. }
  49752. })
  49753. });
  49754. /**
  49755. * Create a Promise that resolves once the media element has finished buffering.
  49756. *
  49757. * @param {Element} el - HTMLMediaElement.
  49758. * @returns {Promise}
  49759. */
  49760. function mediaElementLoaded (el) {
  49761. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  49762. return;
  49763. }
  49764. // If media specifies autoplay or preload, wait until media is completely buffered.
  49765. return new Promise(function (resolve, reject) {
  49766. if (el.readyState === 4) { return resolve(); } // Already loaded.
  49767. if (el.error) { return reject(); } // Error.
  49768. el.addEventListener('loadeddata', checkProgress, false);
  49769. el.addEventListener('progress', checkProgress, false);
  49770. el.addEventListener('error', reject, false);
  49771. function checkProgress () {
  49772. // Add up the seconds buffered.
  49773. var secondsBuffered = 0;
  49774. for (var i = 0; i < el.buffered.length; i++) {
  49775. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  49776. }
  49777. // Compare seconds buffered to media duration.
  49778. if (secondsBuffered >= el.duration) {
  49779. // Set in cache because we won't be needing to call three.js loader if we have.
  49780. // a loaded media element.
  49781. // Store video elements only. three.js loader is used for audio elements.
  49782. // See assetParse too.
  49783. if (el.tagName === 'VIDEO') {
  49784. THREE.Cache.files[el.getAttribute('src')] = el;
  49785. }
  49786. resolve();
  49787. }
  49788. }
  49789. });
  49790. }
  49791. /**
  49792. * Automatically add attributes to media elements where convenient.
  49793. * crossorigin, playsinline.
  49794. */
  49795. function fixUpMediaElement (mediaEl) {
  49796. // Cross-origin.
  49797. var newMediaEl = setCrossOrigin(mediaEl);
  49798. // Plays inline for mobile.
  49799. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  49800. newMediaEl.setAttribute('playsinline', '');
  49801. newMediaEl.setAttribute('webkit-playsinline', '');
  49802. }
  49803. if (newMediaEl !== mediaEl) {
  49804. mediaEl.parentNode.appendChild(newMediaEl);
  49805. mediaEl.parentNode.removeChild(mediaEl);
  49806. }
  49807. return newMediaEl;
  49808. }
  49809. /**
  49810. * Automatically set `crossorigin` if not defined on the media element.
  49811. * If it is not defined, we must create and re-append a new media element <img> and
  49812. * have the browser re-request it with `crossorigin` set.
  49813. *
  49814. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  49815. * @returns {Element} Media element to be used to listen to for loaded events.
  49816. */
  49817. function setCrossOrigin (mediaEl) {
  49818. var newMediaEl;
  49819. var src;
  49820. // Already has crossorigin set.
  49821. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  49822. src = mediaEl.getAttribute('src');
  49823. if (src !== null) {
  49824. // Does not have protocol.
  49825. if (src.indexOf('://') === -1) { return mediaEl; }
  49826. // Determine if cross origin is actually needed.
  49827. if (extractDomain(src) === window.location.host) { return mediaEl; }
  49828. }
  49829. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  49830. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  49831. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  49832. mediaEl.crossOrigin = 'anonymous';
  49833. newMediaEl = mediaEl.cloneNode(true);
  49834. return newMediaEl;
  49835. }
  49836. /**
  49837. * Extract domain out of URL.
  49838. *
  49839. * @param {string} url
  49840. * @returns {string}
  49841. */
  49842. function extractDomain (url) {
  49843. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  49844. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  49845. // Find and remove port number.
  49846. return domain.substring(0, domain.indexOf(':'));
  49847. }
  49848. /**
  49849. * getArrayBuffer accepts a string and returns it as an array buffer.
  49850. * @param {string} string
  49851. * @returns {arraybuffer}
  49852. */
  49853. function getArrayBuffer (string) {
  49854. // utf-16 has 2 bytes for each char
  49855. var buffer = new ArrayBuffer(string.length * 2);
  49856. var view = new Uint16Array(buffer);
  49857. for (var i = 0, len = string.length; i < len; i++) {
  49858. view[i] = string.charCodeAt(i);
  49859. }
  49860. return buffer;
  49861. }
  49862. module.exports.getArrayBuffer = getArrayBuffer;
  49863. },{"../lib/three":172,"../utils/bind":191,"../utils/debug":193,"./a-node":122,"./a-register-element":123}],119:[function(_dereq_,module,exports){
  49864. var debug = _dereq_('../utils/debug');
  49865. var registerElement = _dereq_('./a-register-element').registerElement;
  49866. var warn = debug('core:cubemap:warn');
  49867. /**
  49868. * Cubemap element that handles validation and exposes list of URLs.
  49869. * Does not listen to updates.
  49870. */
  49871. module.exports = registerElement('a-cubemap', {
  49872. prototype: Object.create(window.HTMLElement.prototype, {
  49873. /**
  49874. * Calculates this.srcs.
  49875. */
  49876. attachedCallback: {
  49877. value: function () {
  49878. this.srcs = this.validate();
  49879. },
  49880. writable: window.debug
  49881. },
  49882. /**
  49883. * Checks for exactly six elements with [src].
  49884. * Does not check explicitly for <img>s in case user does not want
  49885. * prefetching.
  49886. *
  49887. * @returns {Array|null} - six URLs if valid, else null.
  49888. */
  49889. validate: {
  49890. value: function () {
  49891. var elements = this.querySelectorAll('[src]');
  49892. var i;
  49893. var srcs = [];
  49894. if (elements.length === 6) {
  49895. for (i = 0; i < elements.length; i++) {
  49896. srcs.push(elements[i].getAttribute('src'));
  49897. }
  49898. return srcs;
  49899. }
  49900. // Else if there are not six elements, throw a warning.
  49901. warn(
  49902. '<a-cubemap> did not contain exactly six elements each with a ' +
  49903. '`src` attribute.');
  49904. },
  49905. writable: window.debug
  49906. }
  49907. })
  49908. });
  49909. },{"../utils/debug":193,"./a-register-element":123}],120:[function(_dereq_,module,exports){
  49910. var ANode = _dereq_('./a-node');
  49911. var COMPONENTS = _dereq_('./component').components;
  49912. var registerElement = _dereq_('./a-register-element').registerElement;
  49913. var THREE = _dereq_('../lib/three');
  49914. var utils = _dereq_('../utils/');
  49915. var AEntity;
  49916. var debug = utils.debug('core:a-entity:debug');
  49917. var warn = utils.debug('core:a-entity:warn');
  49918. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49919. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  49920. var ONCE = {once: true};
  49921. /**
  49922. * Entity is a container object that components are plugged into to comprise everything in
  49923. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  49924. *
  49925. * To be able to take components, the scene element inherits from the entity definition.
  49926. *
  49927. * @member {object} components - entity's currently initialized components.
  49928. * @member {object} object3D - three.js object.
  49929. * @member {array} states
  49930. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  49931. */
  49932. var proto = Object.create(ANode.prototype, {
  49933. createdCallback: {
  49934. value: function () {
  49935. this.components = {};
  49936. // To avoid double initializations and infinite loops.
  49937. this.initializingComponents = {};
  49938. this.componentsToUpdate = {};
  49939. this.isEntity = true;
  49940. this.isPlaying = false;
  49941. this.object3D = new THREE.Group();
  49942. this.object3D.el = this;
  49943. this.object3DMap = {};
  49944. this.parentEl = null;
  49945. this.rotationObj = {};
  49946. this.states = [];
  49947. }
  49948. },
  49949. /**
  49950. * Handle changes coming from the browser DOM inspector.
  49951. */
  49952. attributeChangedCallback: {
  49953. value: function (attr, oldVal, newVal) {
  49954. var component = this.components[attr];
  49955. // If the empty string is passed by the component initialization
  49956. // logic we ignore the component update.
  49957. if (component && component.justInitialized && newVal === '') {
  49958. delete component.justInitialized;
  49959. return;
  49960. }
  49961. // When a component is removed after calling el.removeAttribute('material')
  49962. if (!component && newVal === null) { return; }
  49963. this.setEntityAttribute(attr, oldVal, newVal);
  49964. }
  49965. },
  49966. /**
  49967. * Add to parent, load, play.
  49968. */
  49969. attachedCallback: {
  49970. value: function () {
  49971. var assetsEl; // Asset management system element.
  49972. var sceneEl = this.sceneEl;
  49973. var self = this; // Component.
  49974. this.addToParent();
  49975. // Don't .load() scene on attachedCallback.
  49976. if (this.isScene) { return; }
  49977. // Gracefully not error when outside of <a-scene> (e.g., tests).
  49978. if (!sceneEl) {
  49979. this.load();
  49980. return;
  49981. }
  49982. // Wait for asset management system to finish before loading.
  49983. assetsEl = sceneEl.querySelector('a-assets');
  49984. if (assetsEl && !assetsEl.hasLoaded) {
  49985. assetsEl.addEventListener('loaded', function () { self.load(); });
  49986. return;
  49987. }
  49988. this.load();
  49989. }
  49990. },
  49991. /**
  49992. * Tell parent to remove this element's object3D from its object3D.
  49993. * Do not call on scene element because that will cause a call to document.body.remove().
  49994. */
  49995. detachedCallback: {
  49996. value: function () {
  49997. var componentName;
  49998. if (!this.parentEl) { return; }
  49999. // Remove components.
  50000. for (componentName in this.components) {
  50001. this.removeComponent(componentName, false);
  50002. }
  50003. if (this.isScene) { return; }
  50004. this.removeFromParent();
  50005. ANode.prototype.detachedCallback.call(this);
  50006. // Remove cyclic reference.
  50007. this.object3D.el = null;
  50008. }
  50009. },
  50010. getObject3D: {
  50011. value: function (type) {
  50012. return this.object3DMap[type];
  50013. }
  50014. },
  50015. /**
  50016. * Set a THREE.Object3D into the map.
  50017. *
  50018. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  50019. * @param {object} obj - A THREE.Object3D.
  50020. */
  50021. setObject3D: {
  50022. value: function (type, obj) {
  50023. var oldObj;
  50024. var self = this;
  50025. if (!(obj instanceof THREE.Object3D)) {
  50026. throw new Error(
  50027. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  50028. 'THREE.Object3D.'
  50029. );
  50030. }
  50031. // Remove existing object of the type.
  50032. oldObj = this.getObject3D(type);
  50033. if (oldObj) { this.object3D.remove(oldObj); }
  50034. // Set references to A-Frame entity.
  50035. obj.el = this;
  50036. if (obj.children.length) {
  50037. obj.traverse(function bindEl (child) {
  50038. child.el = self;
  50039. });
  50040. }
  50041. // Add.
  50042. this.object3D.add(obj);
  50043. this.object3DMap[type] = obj;
  50044. this.emit('object3dset', {object: obj, type: type});
  50045. }
  50046. },
  50047. /**
  50048. * Remove object from scene and entity object3D map.
  50049. */
  50050. removeObject3D: {
  50051. value: function (type) {
  50052. var obj = this.getObject3D(type);
  50053. if (!obj) {
  50054. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  50055. return;
  50056. }
  50057. this.object3D.remove(obj);
  50058. delete this.object3DMap[type];
  50059. this.emit('object3dremove', {type: type});
  50060. }
  50061. },
  50062. /**
  50063. * Gets or creates an object3D of a given type.
  50064. *
  50065. * @param {string} type - Type of the object3D.
  50066. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  50067. * @returns {object}
  50068. */
  50069. getOrCreateObject3D: {
  50070. value: function (type, Constructor) {
  50071. var object3D = this.getObject3D(type);
  50072. if (!object3D && Constructor) {
  50073. object3D = new Constructor();
  50074. this.setObject3D(type, object3D);
  50075. }
  50076. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  50077. 'and `object3dset` event instead.');
  50078. return object3D;
  50079. }
  50080. },
  50081. /**
  50082. * Add child entity.
  50083. *
  50084. * @param {Element} el - Child entity.
  50085. */
  50086. add: {
  50087. value: function (el) {
  50088. if (!el.object3D) {
  50089. throw new Error("Trying to add an element that doesn't have an `object3D`");
  50090. }
  50091. this.object3D.add(el.object3D);
  50092. this.emit('child-attached', {el: el});
  50093. }
  50094. },
  50095. /**
  50096. * Tell parentNode to add this entity to itself.
  50097. */
  50098. addToParent: {
  50099. value: function () {
  50100. var parentNode = this.parentEl = this.parentNode;
  50101. // `!parentNode` check primarily for unit tests.
  50102. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  50103. parentNode.add(this);
  50104. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  50105. }
  50106. },
  50107. /**
  50108. * Tell parentNode to remove this entity from itself.
  50109. */
  50110. removeFromParent: {
  50111. value: function () {
  50112. var parentEl = this.parentEl;
  50113. this.parentEl.remove(this);
  50114. this.attachedToParent = false;
  50115. this.parentEl = null;
  50116. parentEl.emit('child-detached', {el: this});
  50117. }
  50118. },
  50119. load: {
  50120. value: function () {
  50121. var self = this;
  50122. if (this.hasLoaded || !this.parentEl) { return; }
  50123. ANode.prototype.load.call(this, function entityLoadCallback () {
  50124. // Check if entity was detached while it was waiting to load.
  50125. if (!self.parentEl) { return; }
  50126. self.updateComponents();
  50127. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  50128. });
  50129. },
  50130. writable: window.debug
  50131. },
  50132. /**
  50133. * Remove child entity.
  50134. *
  50135. * @param {Element} el - Child entity.
  50136. */
  50137. remove: {
  50138. value: function (el) {
  50139. if (el) {
  50140. this.object3D.remove(el.object3D);
  50141. } else {
  50142. this.parentNode.removeChild(this);
  50143. }
  50144. }
  50145. },
  50146. /**
  50147. * @returns {array} Direct children that are entities.
  50148. */
  50149. getChildEntities: {
  50150. value: function () {
  50151. var children = this.children;
  50152. var childEntities = [];
  50153. for (var i = 0; i < children.length; i++) {
  50154. var child = children[i];
  50155. if (child instanceof AEntity) {
  50156. childEntities.push(child);
  50157. }
  50158. }
  50159. return childEntities;
  50160. }
  50161. },
  50162. /**
  50163. * Initialize component.
  50164. *
  50165. * @param {string} attrName - Attribute name asociated to the component.
  50166. * @param {object} data - Component data
  50167. * @param {boolean} isDependency - True if the component is a dependency.
  50168. */
  50169. initComponent: {
  50170. value: function (attrName, data, isDependency) {
  50171. var component;
  50172. var componentId;
  50173. var componentInfo;
  50174. var componentName;
  50175. var isComponentDefined;
  50176. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  50177. componentName = componentInfo[0];
  50178. componentId = componentInfo.length > 2
  50179. ? componentInfo.slice(1).join('__')
  50180. : componentInfo[1];
  50181. // Not a registered component.
  50182. if (!COMPONENTS[componentName]) { return; }
  50183. // Component is not a dependency and is undefined.
  50184. // If a component is a dependency, then it is okay to have no data.
  50185. isComponentDefined = checkComponentDefined(this, attrName) ||
  50186. data !== undefined;
  50187. if (!isComponentDefined && !isDependency) { return; }
  50188. // Component already initialized.
  50189. if (attrName in this.components) { return; }
  50190. // Initialize dependencies first
  50191. this.initComponentDependencies(componentName);
  50192. // If component name has an id we check component type multiplic
  50193. if (componentId && !COMPONENTS[componentName].multiple) {
  50194. throw new Error('Trying to initialize multiple ' +
  50195. 'components of type `' + componentName +
  50196. '`. There can only be one component of this type per entity.');
  50197. }
  50198. component = new COMPONENTS[componentName].Component(this, data, componentId);
  50199. if (this.isPlaying) { component.play(); }
  50200. // Components are reflected in the DOM as attributes but the state is not shown
  50201. // hence we set the attribute to empty string.
  50202. // The flag justInitialized is for attributeChangedCallback to not overwrite
  50203. // the component with the empty string.
  50204. if (!this.hasAttribute(attrName)) {
  50205. component.justInitialized = true;
  50206. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  50207. }
  50208. debug('Component initialized: %s', attrName);
  50209. },
  50210. writable: window.debug
  50211. },
  50212. /**
  50213. * Initialize dependencies of a component.
  50214. *
  50215. * @param {string} name - Root component name.
  50216. */
  50217. initComponentDependencies: {
  50218. value: function (name) {
  50219. var self = this;
  50220. var component = COMPONENTS[name];
  50221. var dependencies;
  50222. var i;
  50223. // Not a component.
  50224. if (!component) { return; }
  50225. // No dependencies.
  50226. dependencies = COMPONENTS[name].dependencies;
  50227. if (!dependencies) { return; }
  50228. // Initialize dependencies.
  50229. for (i = 0; i < dependencies.length; i++) {
  50230. // Call getAttribute to initialize the data from the DOM.
  50231. self.initComponent(
  50232. dependencies[i],
  50233. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  50234. true
  50235. );
  50236. }
  50237. }
  50238. },
  50239. removeComponent: {
  50240. value: function (name, destroy) {
  50241. var component;
  50242. component = this.components[name];
  50243. if (!component) { return; }
  50244. // Wait for component to initialize.
  50245. if (!component.initialized) {
  50246. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  50247. if (evt.detail.name !== name) { return; }
  50248. this.removeComponent(name, destroy);
  50249. this.removeEventListener('componentinitialized', tryRemoveLater);
  50250. });
  50251. return;
  50252. }
  50253. component.pause();
  50254. component.remove();
  50255. // Keep component attached to entity in case of just full entity detach.
  50256. if (destroy) {
  50257. component.destroy();
  50258. delete this.components[name];
  50259. }
  50260. this.emit('componentremoved', component.evtDetail, false);
  50261. },
  50262. writable: window.debug
  50263. },
  50264. /**
  50265. * Initialize or update all components.
  50266. * Build data using initial components, defined attributes, mixins, and defaults.
  50267. * Update default components before the rest.
  50268. *
  50269. * @member {function} getExtraComponents - Can be implemented to include component data
  50270. * from other sources (e.g., implemented by primitives).
  50271. */
  50272. updateComponents: {
  50273. value: function () {
  50274. var data;
  50275. var extraComponents;
  50276. var i;
  50277. var name;
  50278. var componentsToUpdate = this.componentsToUpdate;
  50279. if (!this.hasLoaded) { return; }
  50280. // Gather mixin-defined components.
  50281. for (i = 0; i < this.mixinEls.length; i++) {
  50282. for (name in this.mixinEls[i].componentCache) {
  50283. if (isComponent(name)) { componentsToUpdate[name] = true; }
  50284. }
  50285. }
  50286. // Gather from extra initial component data if defined (e.g., primitives).
  50287. if (this.getExtraComponents) {
  50288. extraComponents = this.getExtraComponents();
  50289. for (name in extraComponents) {
  50290. if (isComponent(name)) { componentsToUpdate[name] = true; }
  50291. }
  50292. }
  50293. // Gather entity-defined components.
  50294. for (i = 0; i < this.attributes.length; ++i) {
  50295. name = this.attributes[i].name;
  50296. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  50297. if (isComponent(name)) { componentsToUpdate[name] = true; }
  50298. }
  50299. // object3D components first (position, rotation, scale, visible).
  50300. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  50301. name = OBJECT3D_COMPONENTS[i];
  50302. if (!this.hasAttribute(name)) { continue; }
  50303. this.updateComponent(name, this.getDOMAttribute(name));
  50304. }
  50305. // Initialize or update rest of components.
  50306. for (name in componentsToUpdate) {
  50307. data = mergeComponentData(this.getDOMAttribute(name),
  50308. extraComponents && extraComponents[name]);
  50309. this.updateComponent(name, data);
  50310. delete componentsToUpdate[name];
  50311. }
  50312. },
  50313. writable: window.debug
  50314. },
  50315. /**
  50316. * Initialize, update, or remove a single component.
  50317. *
  50318. * When initializing, we set the component on `this.components`.
  50319. *
  50320. * @param {string} attr - Component name.
  50321. * @param {object} attrValue - Value of the DOM attribute.
  50322. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  50323. */
  50324. updateComponent: {
  50325. value: function (attr, attrValue, clobber) {
  50326. var component = this.components[attr];
  50327. if (component) {
  50328. // Remove component.
  50329. if (attrValue === null && !checkComponentDefined(this, attr)) {
  50330. this.removeComponent(attr, true);
  50331. return;
  50332. }
  50333. // Component already initialized. Update component.
  50334. component.updateProperties(attrValue, clobber);
  50335. return;
  50336. }
  50337. // Component not yet initialized. Initialize component.
  50338. this.initComponent(attr, attrValue, false);
  50339. }
  50340. },
  50341. /**
  50342. * If `attr` is a component name, detach the component from the entity.
  50343. *
  50344. * If `propertyName` is given, reset the component property value to its default.
  50345. *
  50346. * @param {string} attr - Attribute name, which could also be a component name.
  50347. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  50348. */
  50349. removeAttribute: {
  50350. value: function (attr, propertyName) {
  50351. var component = this.components[attr];
  50352. // Remove component.
  50353. if (component && propertyName === undefined) {
  50354. this.removeComponent(attr, true);
  50355. }
  50356. // Reset component property value.
  50357. if (component && propertyName !== undefined) {
  50358. component.resetProperty(propertyName);
  50359. return;
  50360. }
  50361. // Remove mixins.
  50362. if (attr === 'mixin') {
  50363. this.mixinUpdate('');
  50364. }
  50365. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  50366. }
  50367. },
  50368. /**
  50369. * Start dynamic behavior associated with entity such as dynamic components and animations.
  50370. * Tell all children entities to also play.
  50371. */
  50372. play: {
  50373. value: function () {
  50374. var entities;
  50375. var i;
  50376. var key;
  50377. // Already playing.
  50378. if (this.isPlaying || !this.hasLoaded) { return; }
  50379. this.isPlaying = true;
  50380. // Wake up all components.
  50381. for (key in this.components) { this.components[key].play(); }
  50382. // Tell all child entities to play.
  50383. entities = this.getChildEntities();
  50384. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  50385. this.emit('play');
  50386. },
  50387. writable: true
  50388. },
  50389. /**
  50390. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  50391. * Tell all children entities to also pause.
  50392. */
  50393. pause: {
  50394. value: function () {
  50395. var entities;
  50396. var i;
  50397. var key;
  50398. if (!this.isPlaying) { return; }
  50399. this.isPlaying = false;
  50400. // Sleep all components.
  50401. for (key in this.components) { this.components[key].pause(); }
  50402. // Tell all child entities to pause.
  50403. entities = this.getChildEntities();
  50404. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  50405. this.emit('pause');
  50406. },
  50407. writable: true
  50408. },
  50409. /**
  50410. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  50411. *
  50412. * @param {string} attr
  50413. * @param {string} oldVal
  50414. * @param {string|object} newVal
  50415. */
  50416. setEntityAttribute: {
  50417. value: function (attr, oldVal, newVal) {
  50418. if (COMPONENTS[attr] || this.components[attr]) {
  50419. this.updateComponent(attr, newVal);
  50420. return;
  50421. }
  50422. if (attr === 'mixin') {
  50423. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  50424. if (newVal === this.computedMixinStr) { return; }
  50425. this.mixinUpdate(newVal, oldVal);
  50426. }
  50427. }
  50428. },
  50429. /**
  50430. * When mixins updated, trigger init or optimized-update of relevant components.
  50431. */
  50432. mixinUpdate: {
  50433. value: (function () {
  50434. var componentsUpdated = [];
  50435. return function (newMixins, oldMixins) {
  50436. var component;
  50437. var mixinEl;
  50438. var mixinIds;
  50439. var i;
  50440. var self = this;
  50441. if (!this.hasLoaded) {
  50442. this.addEventListener('loaded', function () {
  50443. self.mixinUpdate(newMixins, oldMixins);
  50444. }, ONCE);
  50445. return;
  50446. }
  50447. oldMixins = oldMixins || this.getAttribute('mixin');
  50448. mixinIds = this.updateMixins(newMixins, oldMixins);
  50449. // Loop over current mixins.
  50450. componentsUpdated.length = 0;
  50451. for (i = 0; i < this.mixinEls.length; i++) {
  50452. for (component in this.mixinEls[i].componentCache) {
  50453. if (componentsUpdated.indexOf(component) === -1) {
  50454. if (this.components[component]) {
  50455. // Update. Just rebuild data.
  50456. this.components[component].handleMixinUpdate();
  50457. } else {
  50458. // Init. buildData will gather mixin values.
  50459. this.initComponent(component, null);
  50460. }
  50461. componentsUpdated.push(component);
  50462. }
  50463. }
  50464. }
  50465. // Loop over old mixins to call for data rebuild.
  50466. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  50467. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  50468. if (!mixinEl) { continue; }
  50469. for (component in mixinEl.componentCache) {
  50470. if (componentsUpdated.indexOf(component) === -1) {
  50471. if (this.components[component]) {
  50472. if (this.getDOMAttribute(component)) {
  50473. // Update component if explicitly defined.
  50474. this.components[component].handleMixinUpdate();
  50475. } else {
  50476. // Remove component if not explicitly defined.
  50477. this.removeComponent(component, true);
  50478. }
  50479. }
  50480. }
  50481. }
  50482. }
  50483. };
  50484. })()
  50485. },
  50486. /**
  50487. * setAttribute can:
  50488. *
  50489. * 1. Set a single property of a multi-property component.
  50490. * 2. Set multiple properties of a multi-property component.
  50491. * 3. Replace properties of a multi-property component.
  50492. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  50493. *
  50494. * @param {string} attrName - Component or attribute name.
  50495. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  50496. * object of properties.
  50497. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  50498. * it is a boolean indicating whether to clobber previous values (defaults to false).
  50499. */
  50500. setAttribute: {
  50501. value: (function () {
  50502. var singlePropUpdate = {};
  50503. return function (attrName, arg1, arg2) {
  50504. var newAttrValue;
  50505. var clobber;
  50506. var componentName;
  50507. var delimiterIndex;
  50508. var isDebugMode;
  50509. var key;
  50510. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  50511. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  50512. // Not a component. Normal set attribute.
  50513. if (!COMPONENTS[componentName]) {
  50514. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  50515. ANode.prototype.setAttribute.call(this, attrName, arg1);
  50516. return;
  50517. }
  50518. // Initialize component first if not yet initialized.
  50519. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  50520. this.updateComponent(
  50521. attrName,
  50522. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  50523. }
  50524. // Determine new attributes from the arguments
  50525. if (typeof arg2 !== 'undefined' &&
  50526. typeof arg1 === 'string' &&
  50527. arg1.length > 0 &&
  50528. typeof utils.styleParser.parse(arg1) === 'string') {
  50529. // Update a single property of a multi-property component
  50530. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  50531. newAttrValue = singlePropUpdate;
  50532. newAttrValue[arg1] = arg2;
  50533. clobber = false;
  50534. } else {
  50535. // Update with a value, object, or CSS-style property string, with the possiblity
  50536. // of clobbering previous values.
  50537. newAttrValue = arg1;
  50538. clobber = (arg2 === true);
  50539. }
  50540. // Update component
  50541. this.updateComponent(attrName, newAttrValue, clobber);
  50542. // In debug mode, write component data up to the DOM.
  50543. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  50544. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  50545. };
  50546. })(),
  50547. writable: window.debug
  50548. },
  50549. /**
  50550. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  50551. *
  50552. * @param {bool} recursive - Also flushToDOM on the children.
  50553. **/
  50554. flushToDOM: {
  50555. value: function (recursive) {
  50556. var components = this.components;
  50557. var child;
  50558. var children = this.children;
  50559. var i;
  50560. var key;
  50561. // Flush entity's components to DOM.
  50562. for (key in components) {
  50563. components[key].flushToDOM();
  50564. }
  50565. // Recurse.
  50566. if (!recursive) { return; }
  50567. for (i = 0; i < children.length; ++i) {
  50568. child = children[i];
  50569. if (!child.flushToDOM) { continue; }
  50570. child.flushToDOM(recursive);
  50571. }
  50572. }
  50573. },
  50574. /**
  50575. * If `attr` is a component, returns ALL component data including applied mixins and
  50576. * defaults.
  50577. *
  50578. * If `attr` is not a component, fall back to HTML getAttribute.
  50579. *
  50580. * @param {string} attr
  50581. * @returns {object|string} Object if component, else string.
  50582. */
  50583. getAttribute: {
  50584. value: function (attr) {
  50585. // If component, return component data.
  50586. var component;
  50587. if (attr === 'position') { return this.object3D.position; }
  50588. if (attr === 'rotation') { return getRotation(this); }
  50589. if (attr === 'scale') { return this.object3D.scale; }
  50590. if (attr === 'visible') { return this.object3D.visible; }
  50591. component = this.components[attr];
  50592. if (component) { return component.data; }
  50593. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50594. },
  50595. writable: window.debug
  50596. },
  50597. /**
  50598. * If `attr` is a component, returns JUST the component data defined on the entity.
  50599. * Like a partial version of `getComputedAttribute` as returned component data
  50600. * does not include applied mixins or defaults.
  50601. *
  50602. * If `attr` is not a component, fall back to HTML getAttribute.
  50603. *
  50604. * @param {string} attr
  50605. * @returns {object|string} Object if component, else string.
  50606. */
  50607. getDOMAttribute: {
  50608. value: function (attr) {
  50609. // If cached value exists, return partial component data.
  50610. var component = this.components[attr];
  50611. if (component) { return component.attrValue; }
  50612. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50613. },
  50614. writable: window.debug
  50615. },
  50616. addState: {
  50617. value: function (state) {
  50618. if (this.is(state)) { return; }
  50619. this.states.push(state);
  50620. this.emit('stateadded', state);
  50621. }
  50622. },
  50623. removeState: {
  50624. value: function (state) {
  50625. var stateIndex = this.states.indexOf(state);
  50626. if (stateIndex === -1) { return; }
  50627. this.states.splice(stateIndex, 1);
  50628. this.emit('stateremoved', state);
  50629. }
  50630. },
  50631. /**
  50632. * Checks if the element is in a given state. e.g. el.is('alive');
  50633. * @type {string} state - Name of the state we want to check
  50634. */
  50635. is: {
  50636. value: function (state) {
  50637. return this.states.indexOf(state) !== -1;
  50638. }
  50639. },
  50640. /**
  50641. * Open Inspector to this entity.
  50642. */
  50643. inspect: {
  50644. value: function () {
  50645. this.sceneEl.components.inspector.openInspector(this);
  50646. }
  50647. },
  50648. /**
  50649. * Clean up memory and return memory to object pools.
  50650. */
  50651. destroy: {
  50652. value: function () {
  50653. var key;
  50654. if (this.parentNode) {
  50655. warn('Entity can only be destroyed if detached from scenegraph.');
  50656. return;
  50657. }
  50658. for (key in this.components) {
  50659. this.components[key].destroy();
  50660. }
  50661. }
  50662. }
  50663. });
  50664. /**
  50665. * Check if a component is *defined* for an entity, including defaults and mixins.
  50666. * Does not check whether the component has been *initialized* for an entity.
  50667. *
  50668. * @param {string} el - Entity.
  50669. * @param {string} name - Component name.
  50670. * @returns {boolean}
  50671. */
  50672. function checkComponentDefined (el, name) {
  50673. // Check if element contains the component.
  50674. if (el.components[name] && el.components[name].attrValue) { return true; }
  50675. return isComponentMixedIn(name, el.mixinEls);
  50676. }
  50677. /**
  50678. * Check if any mixins contains a component.
  50679. *
  50680. * @param {string} name - Component name.
  50681. * @param {array} mixinEls - Array of <a-mixin>s.
  50682. */
  50683. function isComponentMixedIn (name, mixinEls) {
  50684. var i;
  50685. var inMixin = false;
  50686. for (i = 0; i < mixinEls.length; ++i) {
  50687. inMixin = mixinEls[i].hasAttribute(name);
  50688. if (inMixin) { break; }
  50689. }
  50690. return inMixin;
  50691. }
  50692. /**
  50693. * Given entity defined value, merge in extra data if necessary.
  50694. * Handle both single and multi-property components.
  50695. *
  50696. * @param {string} attrValue - Entity data.
  50697. * @param extraData - Entity data from another source to merge in.
  50698. */
  50699. function mergeComponentData (attrValue, extraData) {
  50700. // Extra data not defined, just return attrValue.
  50701. if (!extraData) { return attrValue; }
  50702. // Merge multi-property data.
  50703. if (extraData.constructor === Object) {
  50704. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  50705. }
  50706. // Return data, precendence to the defined value.
  50707. return attrValue || extraData;
  50708. }
  50709. function isComponent (componentName) {
  50710. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  50711. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  50712. }
  50713. if (!COMPONENTS[componentName]) { return false; }
  50714. return true;
  50715. }
  50716. function getRotation (entityEl) {
  50717. var radToDeg = THREE.Math.radToDeg;
  50718. var rotation = entityEl.object3D.rotation;
  50719. var rotationObj = entityEl.rotationObj;
  50720. rotationObj.x = radToDeg(rotation.x);
  50721. rotationObj.y = radToDeg(rotation.y);
  50722. rotationObj.z = radToDeg(rotation.z);
  50723. return rotationObj;
  50724. }
  50725. AEntity = registerElement('a-entity', {prototype: proto});
  50726. module.exports = AEntity;
  50727. },{"../lib/three":172,"../utils/":197,"./a-node":122,"./a-register-element":123,"./component":124}],121:[function(_dereq_,module,exports){
  50728. var ANode = _dereq_('./a-node');
  50729. var registerElement = _dereq_('./a-register-element').registerElement;
  50730. var components = _dereq_('./component').components;
  50731. var utils = _dereq_('../utils');
  50732. var MULTIPLE_COMPONENT_DELIMITER = '__';
  50733. /**
  50734. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  50735. * are component names and the values are already parsed by the component.
  50736. */
  50737. module.exports = registerElement('a-mixin', {
  50738. prototype: Object.create(ANode.prototype, {
  50739. createdCallback: {
  50740. value: function () {
  50741. this.componentCache = {};
  50742. this.id = this.getAttribute('id');
  50743. this.isMixin = true;
  50744. }
  50745. },
  50746. attributeChangedCallback: {
  50747. value: function (attr, oldVal, newVal) {
  50748. this.cacheAttribute(attr, newVal);
  50749. this.updateEntities();
  50750. }
  50751. },
  50752. attachedCallback: {
  50753. value: function () {
  50754. this.sceneEl = this.closestScene();
  50755. this.cacheAttributes();
  50756. this.updateEntities();
  50757. this.load();
  50758. }
  50759. },
  50760. /**
  50761. * setAttribute that parses and caches component values.
  50762. */
  50763. setAttribute: {
  50764. value: function (attr, value) {
  50765. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  50766. this.cacheAttribute(attr, value);
  50767. }
  50768. },
  50769. /**
  50770. * If `attr` is a component, then parse the value using the schema and store it.
  50771. */
  50772. cacheAttribute: {
  50773. value: function (attr, value) {
  50774. var component;
  50775. var componentName;
  50776. // Get component data.
  50777. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  50778. component = components[componentName];
  50779. if (!component) { return; }
  50780. if (value === undefined) {
  50781. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  50782. }
  50783. this.componentCache[attr] = component.parseAttrValueForCache(value);
  50784. }
  50785. },
  50786. /**
  50787. * If `attr` is a component, then grab pre-parsed value from the cache.
  50788. * Else do a normal getAttribute.
  50789. */
  50790. getAttribute: {
  50791. value: function (attr) {
  50792. return this.componentCache[attr] ||
  50793. window.HTMLElement.prototype.getAttribute.call(this, attr);
  50794. }
  50795. },
  50796. /**
  50797. * Parse and cache every component defined on the mixin.
  50798. */
  50799. cacheAttributes: {
  50800. value: function () {
  50801. var attributes = this.attributes;
  50802. var attrName;
  50803. var i;
  50804. for (i = 0; i < attributes.length; i++) {
  50805. attrName = attributes[i].name;
  50806. this.cacheAttribute(attrName);
  50807. }
  50808. }
  50809. },
  50810. /**
  50811. * For entities that already have been loaded by the time the mixin was attached, tell
  50812. * those entities to register the mixin and refresh their component data.
  50813. */
  50814. updateEntities: {
  50815. value: function () {
  50816. var entity;
  50817. var entities;
  50818. var i;
  50819. if (!this.sceneEl) { return; }
  50820. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  50821. for (i = 0; i < entities.length; i++) {
  50822. entity = entities[i];
  50823. if (!entity.hasLoaded || entity.isMixin) { continue; }
  50824. entity.mixinUpdate(this.id);
  50825. }
  50826. }
  50827. }
  50828. })
  50829. });
  50830. },{"../utils":197,"./a-node":122,"./a-register-element":123,"./component":124}],122:[function(_dereq_,module,exports){
  50831. /* global CustomEvent */
  50832. var registerElement = _dereq_('./a-register-element').registerElement;
  50833. var isNode = _dereq_('./a-register-element').isNode;
  50834. var utils = _dereq_('../utils/');
  50835. var warn = utils.debug('core:a-node:warn');
  50836. var error = utils.debug('core:a-node:error');
  50837. /**
  50838. * Base class for A-Frame that manages loading of objects.
  50839. *
  50840. * Nodes can be modified using mixins.
  50841. * Nodes emit a `loaded` event when they and their children have initialized.
  50842. */
  50843. module.exports = registerElement('a-node', {
  50844. prototype: Object.create(window.HTMLElement.prototype, {
  50845. createdCallback: {
  50846. value: function () {
  50847. this.computedMixinStr = '';
  50848. this.hasLoaded = false;
  50849. this.isNode = true;
  50850. this.mixinEls = [];
  50851. },
  50852. writable: window.debug
  50853. },
  50854. attachedCallback: {
  50855. value: function () {
  50856. var mixins;
  50857. this.sceneEl = this.closestScene();
  50858. if (!this.sceneEl) {
  50859. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  50860. 'scene. Append this element to `<a-scene>` instead.');
  50861. }
  50862. this.hasLoaded = false;
  50863. this.emit('nodeready', undefined, false);
  50864. if (!this.isMixin) {
  50865. mixins = this.getAttribute('mixin');
  50866. if (mixins) { this.updateMixins(mixins); }
  50867. }
  50868. },
  50869. writable: window.debug
  50870. },
  50871. /**
  50872. * Handle mixin.
  50873. */
  50874. attributeChangedCallback: {
  50875. value: function (attr, oldVal, newVal) {
  50876. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  50877. if (newVal === this.computedMixinStr) { return; }
  50878. if (attr === 'mixin' && !this.isMixin) {
  50879. this.updateMixins(newVal, oldVal);
  50880. }
  50881. }
  50882. },
  50883. /**
  50884. * Returns the first scene by traversing up the tree starting from and
  50885. * including receiver element.
  50886. */
  50887. closestScene: {
  50888. value: function closest () {
  50889. var element = this;
  50890. while (element) {
  50891. if (element.isScene) { break; }
  50892. element = element.parentElement;
  50893. }
  50894. return element;
  50895. }
  50896. },
  50897. /**
  50898. * Returns first element matching a selector by traversing up the tree starting
  50899. * from and including receiver element.
  50900. *
  50901. * @param {string} selector - Selector of element to find.
  50902. */
  50903. closest: {
  50904. value: function closest (selector) {
  50905. var matches = this.matches || this.mozMatchesSelector ||
  50906. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  50907. var element = this;
  50908. while (element) {
  50909. if (matches.call(element, selector)) { break; }
  50910. element = element.parentElement;
  50911. }
  50912. return element;
  50913. }
  50914. },
  50915. detachedCallback: {
  50916. value: function () {
  50917. this.hasLoaded = false;
  50918. }
  50919. },
  50920. /**
  50921. * Wait for children to load, if any.
  50922. * Then emit `loaded` event and set `hasLoaded`.
  50923. */
  50924. load: {
  50925. value: function (cb, childFilter) {
  50926. var children;
  50927. var childrenLoaded;
  50928. var self = this;
  50929. if (this.hasLoaded) { return; }
  50930. // Default to waiting for all nodes.
  50931. childFilter = childFilter || isNode;
  50932. // Wait for children to load (if any), then load.
  50933. children = this.getChildren();
  50934. childrenLoaded = children.filter(childFilter).map(function (child) {
  50935. return new Promise(function waitForLoaded (resolve) {
  50936. if (child.hasLoaded) { return resolve(); }
  50937. child.addEventListener('loaded', resolve);
  50938. });
  50939. });
  50940. Promise.all(childrenLoaded).then(function emitLoaded () {
  50941. self.hasLoaded = true;
  50942. if (cb) { cb(); }
  50943. self.emit('loaded', undefined, false);
  50944. }).catch(function (err) {
  50945. error('Failure loading node: ', err);
  50946. });
  50947. },
  50948. writable: true
  50949. },
  50950. getChildren: {
  50951. value: function () {
  50952. return Array.prototype.slice.call(this.children, 0);
  50953. }
  50954. },
  50955. /**
  50956. * Unregister old mixins and listeners.
  50957. * Register new mixins and listeners.
  50958. * Registering means to update `this.mixinEls` with listeners.
  50959. */
  50960. updateMixins: {
  50961. value: (function () {
  50962. var newMixinIdArray = [];
  50963. var oldMixinIdArray = [];
  50964. var mixinIds = {};
  50965. return function (newMixins, oldMixins) {
  50966. var i;
  50967. var newMixinIds;
  50968. var oldMixinIds;
  50969. newMixinIdArray.length = 0;
  50970. oldMixinIdArray.length = 0;
  50971. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  50972. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  50973. mixinIds.newMixinIds = newMixinIds;
  50974. mixinIds.oldMixinIds = oldMixinIds;
  50975. // Unregister old mixins.
  50976. for (i = 0; i < oldMixinIds.length; i++) {
  50977. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  50978. this.unregisterMixin(oldMixinIds[i]);
  50979. }
  50980. }
  50981. // Register new mixins.
  50982. this.computedMixinStr = '';
  50983. this.mixinEls.length = 0;
  50984. for (i = 0; i < newMixinIds.length; i++) {
  50985. this.registerMixin(document.getElementById(newMixinIds[i]));
  50986. }
  50987. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  50988. // update.
  50989. if (this.computedMixinStr) {
  50990. this.computedMixinStr = this.computedMixinStr.trim();
  50991. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  50992. this.computedMixinStr);
  50993. }
  50994. return mixinIds;
  50995. };
  50996. })()
  50997. },
  50998. /**
  50999. * From mixin ID, add mixin element to `mixinEls`.
  51000. *
  51001. * @param {Element} mixinEl
  51002. */
  51003. registerMixin: {
  51004. value: function (mixinEl) {
  51005. var compositedMixinIds;
  51006. var i;
  51007. var mixin;
  51008. if (!mixinEl) { return; }
  51009. // Register composited mixins (if mixin has mixins).
  51010. mixin = mixinEl.getAttribute('mixin');
  51011. if (mixin) {
  51012. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  51013. for (i = 0; i < compositedMixinIds.length; i++) {
  51014. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  51015. }
  51016. }
  51017. // Register mixin.
  51018. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  51019. this.mixinEls.push(mixinEl);
  51020. }
  51021. },
  51022. setAttribute: {
  51023. value: function (attr, newValue) {
  51024. if (attr === 'mixin') { this.updateMixins(newValue); }
  51025. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  51026. }
  51027. },
  51028. unregisterMixin: {
  51029. value: function (mixinId) {
  51030. var i;
  51031. var mixinEls = this.mixinEls;
  51032. var mixinEl;
  51033. for (i = 0; i < mixinEls.length; ++i) {
  51034. mixinEl = mixinEls[i];
  51035. if (mixinId === mixinEl.id) {
  51036. mixinEls.splice(i, 1);
  51037. break;
  51038. }
  51039. }
  51040. }
  51041. },
  51042. /**
  51043. * Emit a DOM event.
  51044. *
  51045. * @param {string} name - Name of event.
  51046. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  51047. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  51048. * @param {object} [extraData] - Extra data to pass to the event, if any.
  51049. */
  51050. emit: {
  51051. value: (function () {
  51052. var data = {};
  51053. return function (name, detail, bubbles, extraData) {
  51054. if (bubbles === undefined) { bubbles = true; }
  51055. data.bubbles = !!bubbles;
  51056. data.detail = detail;
  51057. // If extra data is present, we need to create a new object.
  51058. if (extraData) { data = utils.extend({}, extraData, data); }
  51059. this.dispatchEvent(new CustomEvent(name, data));
  51060. };
  51061. })(),
  51062. writable: window.debug
  51063. }
  51064. })
  51065. });
  51066. },{"../utils/":197,"./a-register-element":123}],123:[function(_dereq_,module,exports){
  51067. /*
  51068. ------------------------------------------------------------
  51069. ------------- WARNING WARNING WARNING WARNING --------------
  51070. ------------------------------------------------------------
  51071. This module wraps registerElement to deal with components that inherit from
  51072. `ANode` and `AEntity`. It's a pass through in any other case.
  51073. It wraps some of the prototype methods of the created element to make sure
  51074. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  51075. are also invoked. The method in the base prototype is always called before the one
  51076. in the derived prototype.
  51077. */
  51078. // Polyfill `document.registerElement`.
  51079. _dereq_('document-register-element');
  51080. var ANode; // Must declare before AEntity. Initialized at the bottom.
  51081. var AEntity;
  51082. var knownTags = module.exports.knownTags = {};
  51083. function addTagName (tagName) {
  51084. knownTags[tagName.toLowerCase()] = true;
  51085. }
  51086. /**
  51087. * Return whether the element type is one of our known registered ones.
  51088. *
  51089. * @param {string} node - The name of the tag to register.
  51090. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  51091. */
  51092. module.exports.isNode = function (node) {
  51093. return node.tagName.toLowerCase() in knownTags || node.isNode;
  51094. };
  51095. /**
  51096. * @param {string} tagName - The name of the tag to register.
  51097. * @param {object} obj - The prototype of the new element.
  51098. * @returns {object} The prototype of the new element.
  51099. */
  51100. module.exports.registerElement = function (tagName, obj) {
  51101. var proto = Object.getPrototypeOf(obj.prototype);
  51102. var newObj = obj;
  51103. var isANode = ANode && proto === ANode.prototype;
  51104. var isAEntity = AEntity && proto === AEntity.prototype;
  51105. if (isANode || isAEntity) { addTagName(tagName); }
  51106. // Wrap if element inherits from `ANode`.
  51107. if (isANode) {
  51108. newObj = wrapANodeMethods(obj.prototype);
  51109. newObj = {prototype: Object.create(proto, newObj)};
  51110. }
  51111. // Wrap if element inherits from `AEntity`.
  51112. if (isAEntity) {
  51113. newObj = wrapAEntityMethods(obj.prototype);
  51114. newObj = {prototype: Object.create(proto, newObj)};
  51115. }
  51116. // Give all functions their proper name.
  51117. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  51118. var propVal = newObj.prototype[propName];
  51119. if (typeof propVal === 'function') {
  51120. propVal.displayName = propName;
  51121. }
  51122. });
  51123. return document.registerElement(tagName, newObj);
  51124. };
  51125. /**
  51126. * Wrap some obj methods to call those on `ANode` base prototype.
  51127. *
  51128. * @param {object} obj - Object that contains the methods that will be wrapped.
  51129. * @return {object} An object with the same properties as the input parameter but
  51130. * with some of methods wrapped.
  51131. */
  51132. function wrapANodeMethods (obj) {
  51133. var newObj = {};
  51134. var ANodeMethods = [
  51135. 'attachedCallback',
  51136. 'attributeChangedCallback',
  51137. 'createdCallback',
  51138. 'detachedCallback'
  51139. ];
  51140. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  51141. copyProperties(obj, newObj);
  51142. return newObj;
  51143. }
  51144. /**
  51145. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  51146. *
  51147. * @param {object} obj - The objects that contains the methods that will be wrapped.
  51148. * @return {object} - An object with the same properties as the input parameter but
  51149. * with some of methods wrapped.
  51150. */
  51151. function wrapAEntityMethods (obj) {
  51152. var newObj = {};
  51153. var ANodeMethods = [
  51154. 'attachedCallback',
  51155. 'attributeChangedCallback',
  51156. 'createdCallback',
  51157. 'detachedCallback'
  51158. ];
  51159. var AEntityMethods = [
  51160. 'attachedCallback',
  51161. 'attributeChangedCallback',
  51162. 'createdCallback',
  51163. 'detachedCallback'
  51164. ];
  51165. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  51166. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  51167. // Copies the remaining properties into the new object.
  51168. copyProperties(obj, newObj);
  51169. return newObj;
  51170. }
  51171. /**
  51172. * Wrap a list a methods to ensure that those in the base prototype are called
  51173. * before the derived one.
  51174. *
  51175. * @param {object} targetObj - Object that will contain the wrapped methods.
  51176. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  51177. * @param {object} derivedObject - Object that inherits from the baseObj.
  51178. * @param {object} baseObj - Object that derivedObj inherits from.
  51179. */
  51180. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  51181. methodList.forEach(function (methodName) {
  51182. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  51183. });
  51184. }
  51185. module.exports.wrapMethods = wrapMethods;
  51186. /**
  51187. * Wrap one method to ensure that the one in the base prototype is called before
  51188. * the one in the derived one.
  51189. *
  51190. * @param {object} obj - Object that will contain the wrapped method.
  51191. * @param {string} methodName - The name of the method that will be wrapped.
  51192. * @param {object} derivedObject - Object that inherits from the baseObj.
  51193. * @param {object} baseObj - Object that derivedObj inherits from.
  51194. */
  51195. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  51196. var derivedMethod = derivedObj[methodName];
  51197. var baseMethod = baseObj[methodName];
  51198. // Derived prototype does not define method, no need to wrap.
  51199. if (!derivedMethod || !baseMethod) { return; }
  51200. // Derived prototype doesn't override the one in the base one, no need to wrap.
  51201. if (derivedMethod === baseMethod) { return; }
  51202. // Wrap to ensure the base method is called before the one in the derived prototype.
  51203. obj[methodName] = {
  51204. value: function wrappedMethod () {
  51205. baseMethod.apply(this, arguments);
  51206. return derivedMethod.apply(this, arguments);
  51207. },
  51208. writable: window.debug
  51209. };
  51210. }
  51211. /**
  51212. * It copies the properties from source to destination object if they don't
  51213. * exist already.
  51214. *
  51215. * @param {object} source - The object where properties are copied from.
  51216. * @param {type} destination - The object where properties are copied to.
  51217. */
  51218. function copyProperties (source, destination) {
  51219. var props = Object.getOwnPropertyNames(source);
  51220. props.forEach(function (prop) {
  51221. var desc;
  51222. if (!destination[prop]) {
  51223. desc = Object.getOwnPropertyDescriptor(source, prop);
  51224. destination[prop] = {value: source[prop], writable: desc.writable};
  51225. }
  51226. });
  51227. }
  51228. ANode = _dereq_('./a-node');
  51229. AEntity = _dereq_('./a-entity');
  51230. },{"./a-entity":120,"./a-node":122,"document-register-element":12}],124:[function(_dereq_,module,exports){
  51231. /* global Node */
  51232. var schema = _dereq_('./schema');
  51233. var scenes = _dereq_('./scene/scenes');
  51234. var systems = _dereq_('./system');
  51235. var utils = _dereq_('../utils/');
  51236. var components = module.exports.components = {}; // Keep track of registered components.
  51237. var parseProperties = schema.parseProperties;
  51238. var parseProperty = schema.parseProperty;
  51239. var processSchema = schema.process;
  51240. var isSingleProp = schema.isSingleProperty;
  51241. var stringifyProperties = schema.stringifyProperties;
  51242. var stringifyProperty = schema.stringifyProperty;
  51243. var styleParser = utils.styleParser;
  51244. var warn = utils.debug('core:component:warn');
  51245. var aframeScript = document.currentScript;
  51246. var upperCaseRegExp = new RegExp('[A-Z]+');
  51247. // Object pools by component, created upon registration.
  51248. var objectPools = {};
  51249. /**
  51250. * Component class definition.
  51251. *
  51252. * Components configure appearance, modify behavior, or add functionality to
  51253. * entities. The behavior and appearance of an entity can be changed at runtime
  51254. * by adding, removing, or updating components. Entities do not share instances
  51255. * of components.
  51256. *
  51257. * @member {object} el - Reference to the entity element.
  51258. * @member {string} attrValue - Value of the corresponding HTML attribute.
  51259. * @member {object} data - Component data populated by parsing the
  51260. * mapped attribute of the component plus applying defaults and mixins.
  51261. */
  51262. var Component = module.exports.Component = function (el, attrValue, id) {
  51263. var self = this;
  51264. this.el = el;
  51265. this.id = id;
  51266. this.attrName = this.name + (id ? '__' + id : '');
  51267. this.evtDetail = {id: this.id, name: this.name};
  51268. this.initialized = false;
  51269. this.isSingleProperty = isSingleProp(this.schema);
  51270. this.isSinglePropertyObject = this.isSingleProperty &&
  51271. isObject(parseProperty(undefined, this.schema)) &&
  51272. !(this.schema.default instanceof window.HTMLElement);
  51273. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  51274. this.el.components[this.attrName] = this;
  51275. this.objectPool = objectPools[this.name];
  51276. const events = this.events;
  51277. this.events = {};
  51278. eventsBind(this, events);
  51279. // Store component data from previous update call.
  51280. this.attrValue = undefined;
  51281. if (this.isObjectBased) {
  51282. this.nextData = this.objectPool.use();
  51283. // Drop any properties added by dynamic schemas in previous use
  51284. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  51285. this.oldData = this.objectPool.use();
  51286. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  51287. this.previousOldData = this.objectPool.use();
  51288. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  51289. this.parsingAttrValue = this.objectPool.use();
  51290. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  51291. } else {
  51292. this.nextData = undefined;
  51293. this.oldData = undefined;
  51294. this.previousOldData = undefined;
  51295. this.parsingAttrValue = undefined;
  51296. }
  51297. // Last value passed to updateProperties.
  51298. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  51299. el.emit('componentchanged', self.evtDetail, false);
  51300. }, 200);
  51301. this.updateProperties(attrValue);
  51302. };
  51303. Component.prototype = {
  51304. /**
  51305. * Contains the type schema and defaults for the data values.
  51306. * Data is coerced into the types of the values of the defaults.
  51307. */
  51308. schema: {},
  51309. /**
  51310. * Init handler. Similar to attachedCallback.
  51311. * Called during component initialization and is only run once.
  51312. * Components can use this to set initial state.
  51313. */
  51314. init: function () { /* no-op */ },
  51315. /**
  51316. * Map of event names to binded event handlers that will be lifecycle-handled.
  51317. * Will be detached on pause / remove.
  51318. * Will be attached on play.
  51319. */
  51320. events: {},
  51321. /**
  51322. * Update handler. Similar to attributeChangedCallback.
  51323. * Called whenever component's data changes.
  51324. * Also called on component initialization when the component receives initial data.
  51325. *
  51326. * @param {object} prevData - Previous attributes of the component.
  51327. */
  51328. update: function (prevData) { /* no-op */ },
  51329. updateSchema: undefined,
  51330. /**
  51331. * Tick handler.
  51332. * Called on each tick of the scene render loop.
  51333. * Affected by play and pause.
  51334. *
  51335. * @param {number} time - Scene tick time.
  51336. * @param {number} timeDelta - Difference in current render time and previous render time.
  51337. */
  51338. tick: undefined,
  51339. /**
  51340. * Tock handler.
  51341. * Called on each tock of the scene render loop.
  51342. * Affected by play and pause.
  51343. *
  51344. * @param {number} time - Scene tick time.
  51345. * @param {number} timeDelta - Difference in current render time and previous render time.
  51346. * @param {object} camera - Camera used to render the last frame.
  51347. */
  51348. tock: undefined,
  51349. /**
  51350. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51351. */
  51352. play: function () { /* no-op */ },
  51353. /**
  51354. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51355. */
  51356. pause: function () { /* no-op */ },
  51357. /**
  51358. * Remove handler. Similar to detachedCallback.
  51359. * Called whenever component is removed from the entity (i.e., removeAttribute).
  51360. * Components can use this to reset behavior on the entity.
  51361. */
  51362. remove: function () { /* no-op */ },
  51363. /**
  51364. * Parses each property based on property type.
  51365. * If component is single-property, then parses the single property value.
  51366. *
  51367. * @param {string} value - HTML attribute value.
  51368. * @param {boolean} silent - Suppress warning messages.
  51369. * @returns {object} Component data.
  51370. */
  51371. parse: function (value, silent) {
  51372. var schema = this.schema;
  51373. if (this.isSingleProperty) { return parseProperty(value, schema); }
  51374. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  51375. },
  51376. /**
  51377. * Stringify properties if necessary.
  51378. *
  51379. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  51380. * value (e.g., selector, vec3 property types).
  51381. *
  51382. * @param {object} data - Complete component data.
  51383. * @returns {string}
  51384. */
  51385. stringify: function (data) {
  51386. var schema = this.schema;
  51387. if (typeof data === 'string') { return data; }
  51388. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  51389. data = stringifyProperties(data, schema);
  51390. return styleParser.stringify(data);
  51391. },
  51392. /**
  51393. * Update the cache of the pre-parsed attribute value.
  51394. *
  51395. * @param {string} value - New data.
  51396. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  51397. */
  51398. updateCachedAttrValue: function (value, clobber) {
  51399. var newAttrValue;
  51400. var tempObject;
  51401. var property;
  51402. if (value === undefined) { return; }
  51403. // If null value is the new attribute value, make the attribute value falsy.
  51404. if (value === null) {
  51405. if (this.isObjectBased && this.attrValue) {
  51406. this.objectPool.recycle(this.attrValue);
  51407. }
  51408. this.attrValue = undefined;
  51409. return;
  51410. }
  51411. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  51412. // If value is an object, copy it to our pooled newAttrValue object to use to update
  51413. // the attrValue.
  51414. tempObject = this.objectPool.use();
  51415. newAttrValue = utils.extend(tempObject, value);
  51416. } else {
  51417. newAttrValue = this.parseAttrValueForCache(value);
  51418. }
  51419. // Merge new data with previous `attrValue` if updating and not clobbering.
  51420. if (this.isObjectBased && !clobber && this.attrValue) {
  51421. for (property in this.attrValue) {
  51422. if (newAttrValue[property] === undefined) {
  51423. newAttrValue[property] = this.attrValue[property];
  51424. }
  51425. }
  51426. }
  51427. // Update attrValue.
  51428. if (this.isObjectBased && !this.attrValue) {
  51429. this.attrValue = this.objectPool.use();
  51430. }
  51431. utils.objectPool.clearObject(this.attrValue);
  51432. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  51433. utils.objectPool.clearObject(tempObject);
  51434. },
  51435. /**
  51436. * Given an HTML attribute value parses the string based on the component schema.
  51437. * To avoid double parsings of strings into strings we store the original instead
  51438. * of the parsed one
  51439. *
  51440. * @param {string} value - HTML attribute value
  51441. */
  51442. parseAttrValueForCache: function (value) {
  51443. var parsedValue;
  51444. if (typeof value !== 'string') { return value; }
  51445. if (this.isSingleProperty) {
  51446. parsedValue = this.schema.parse(value);
  51447. /**
  51448. * To avoid bogus double parsings. Cached values will be parsed when building
  51449. * component data. For instance when parsing a src id to its url, we want to cache
  51450. * original string and not the parsed one (#monster -> models/monster.dae)
  51451. * so when building data we parse the expected value.
  51452. */
  51453. if (typeof parsedValue === 'string') { parsedValue = value; }
  51454. } else {
  51455. // Parse using the style parser to avoid double parsing of individual properties.
  51456. utils.objectPool.clearObject(this.parsingAttrValue);
  51457. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  51458. }
  51459. return parsedValue;
  51460. },
  51461. /**
  51462. * Write cached attribute data to the entity DOM element.
  51463. *
  51464. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  51465. * default components.
  51466. */
  51467. flushToDOM: function (isDefault) {
  51468. var attrValue = isDefault ? this.data : this.attrValue;
  51469. if (attrValue === null || attrValue === undefined) { return; }
  51470. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  51471. this.stringify(attrValue));
  51472. },
  51473. /**
  51474. * Apply new component data if data has changed (from setAttribute).
  51475. *
  51476. * @param {string} attrValue - HTML attribute value.
  51477. * If undefined, use the cached attribute value and continue updating properties.
  51478. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  51479. */
  51480. updateProperties: function (attrValue, clobber) {
  51481. var el = this.el;
  51482. // Just cache the attribute if the entity has not loaded
  51483. // Components are not initialized until the entity has loaded
  51484. if (!el.hasLoaded) {
  51485. this.updateCachedAttrValue(attrValue);
  51486. return;
  51487. }
  51488. // Parse the attribute value.
  51489. // Cache current attrValue for future updates. Updates `this.attrValue`.
  51490. // `null` means no value on purpose, do not set a default value, let mixins take over.
  51491. if (attrValue !== null) {
  51492. attrValue = this.parseAttrValueForCache(attrValue);
  51493. }
  51494. // Cache current attrValue for future updates.
  51495. this.updateCachedAttrValue(attrValue, clobber);
  51496. if (this.initialized) {
  51497. this.updateComponent(attrValue, clobber);
  51498. this.callUpdateHandler();
  51499. } else {
  51500. this.initComponent();
  51501. }
  51502. },
  51503. initComponent: function () {
  51504. var el = this.el;
  51505. var initialOldData;
  51506. // Build data.
  51507. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  51508. this.data = this.buildData(this.attrValue);
  51509. // Component is being already initialized.
  51510. if (el.initializingComponents[this.name]) { return; }
  51511. // Prevent infinite loop in case of init method setting same component on the entity.
  51512. el.initializingComponents[this.name] = true;
  51513. // Initialize component.
  51514. this.init();
  51515. this.initialized = true;
  51516. delete el.initializingComponents[this.name];
  51517. // Store current data as previous data for future updates.
  51518. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  51519. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  51520. // Pass undefined to rest of types.
  51521. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  51522. this.update(initialOldData);
  51523. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  51524. // Play the component if the entity is playing.
  51525. if (el.isPlaying) { this.play(); }
  51526. el.emit('componentinitialized', this.evtDetail, false);
  51527. },
  51528. /**
  51529. * @param attrValue - Passed argument from setAttribute.
  51530. */
  51531. updateComponent: function (attrValue, clobber) {
  51532. var key;
  51533. var mayNeedSchemaUpdate;
  51534. if (clobber) {
  51535. // Clobber. Rebuild.
  51536. if (this.updateSchema) {
  51537. this.updateSchema(this.buildData(this.attrValue, true, true));
  51538. }
  51539. this.data = this.buildData(this.attrValue, true, false);
  51540. return;
  51541. }
  51542. // Apply new value to this.data in place since direct update.
  51543. if (this.isSingleProperty) {
  51544. if (this.isObjectBased) {
  51545. parseProperty(attrValue, this.schema);
  51546. }
  51547. // Single-property (already parsed).
  51548. this.data = attrValue;
  51549. return;
  51550. }
  51551. parseProperties(attrValue, this.schema, true, this.name);
  51552. // Check if we need to update schema.
  51553. if (this.schemaChangeKeys.length) {
  51554. for (key in attrValue) {
  51555. if (this.schema[key].schemaChange) {
  51556. mayNeedSchemaUpdate = true;
  51557. break;
  51558. }
  51559. }
  51560. }
  51561. if (mayNeedSchemaUpdate) {
  51562. // Rebuild data if need schema update.
  51563. if (this.updateSchema) {
  51564. this.updateSchema(this.buildData(this.attrValue, true, true));
  51565. }
  51566. this.data = this.buildData(this.attrValue, true, false);
  51567. return;
  51568. }
  51569. // Normal update.
  51570. for (key in attrValue) {
  51571. if (attrValue[key] === undefined) { continue; }
  51572. this.data[key] = attrValue[key];
  51573. }
  51574. },
  51575. /**
  51576. * Check if component should fire update and fire update lifecycle handler.
  51577. */
  51578. callUpdateHandler: function () {
  51579. var hasComponentChanged;
  51580. // Store the previous old data before we calculate the new oldData.
  51581. if (this.previousOldData instanceof Object) {
  51582. utils.objectPool.clearObject(this.previousOldData);
  51583. }
  51584. if (this.isObjectBased) {
  51585. copyData(this.previousOldData, this.oldData);
  51586. } else {
  51587. this.previousOldData = this.oldData;
  51588. }
  51589. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  51590. // Don't update if properties haven't changed.
  51591. // Always update rotation, position, scale.
  51592. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  51593. // Store current data as previous data for future updates.
  51594. // Reuse `this.oldData` object to try not to allocate another one.
  51595. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  51596. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  51597. // Update component with the previous old data.
  51598. this.update(this.previousOldData);
  51599. this.throttledEmitComponentChanged();
  51600. },
  51601. handleMixinUpdate: function () {
  51602. this.data = this.buildData(this.attrValue);
  51603. this.callUpdateHandler();
  51604. },
  51605. /**
  51606. * Reset value of a property to the property's default value.
  51607. * If single-prop component, reset value to component's default value.
  51608. *
  51609. * @param {string} propertyName - Name of property to reset.
  51610. */
  51611. resetProperty: function (propertyName) {
  51612. if (this.isObjectBased) {
  51613. if (!(propertyName in this.attrValue)) { return; }
  51614. delete this.attrValue[propertyName];
  51615. this.data[propertyName] = this.schema[propertyName].default;
  51616. } else {
  51617. this.attrValue = this.schema.default;
  51618. this.data = this.schema.default;
  51619. }
  51620. this.updateProperties(this.attrValue);
  51621. },
  51622. /**
  51623. * Extend schema of component given a partial schema.
  51624. *
  51625. * Some components might want to mutate their schema based on certain properties.
  51626. * e.g., Material component changes its schema based on `shader` to account for different
  51627. * uniforms
  51628. *
  51629. * @param {object} schemaAddon - Schema chunk that extend base schema.
  51630. */
  51631. extendSchema: function (schemaAddon) {
  51632. var extendedSchema;
  51633. // Clone base schema.
  51634. extendedSchema = utils.extend({}, components[this.name].schema);
  51635. // Extend base schema with new schema chunk.
  51636. utils.extend(extendedSchema, schemaAddon);
  51637. this.schema = processSchema(extendedSchema);
  51638. this.el.emit('schemachanged', this.evtDetail);
  51639. },
  51640. /**
  51641. * Build component data from the current state of the entity.data.
  51642. *
  51643. * Precedence:
  51644. * 1. Defaults data
  51645. * 2. Mixin data.
  51646. * 3. Attribute data.
  51647. *
  51648. * Finally coerce the data to the types of the defaults.
  51649. *
  51650. * @param {object} newData - Element new data.
  51651. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  51652. * @param {boolean} silent - Suppress warning messages.
  51653. * @return {object} The component data
  51654. */
  51655. buildData: function (newData, clobber, silent) {
  51656. var componentDefined;
  51657. var data;
  51658. var defaultValue;
  51659. var key;
  51660. var mixinData;
  51661. var nextData = this.nextData;
  51662. var schema = this.schema;
  51663. var i;
  51664. var mixinEls = this.el.mixinEls;
  51665. var previousData;
  51666. // Whether component has a defined value. For arrays, treat empty as not defined.
  51667. componentDefined = newData && newData.constructor === Array
  51668. ? newData.length
  51669. : newData !== undefined && newData !== null;
  51670. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  51671. // 1. Gather default values (lowest precendence).
  51672. if (this.isSingleProperty) {
  51673. if (this.isObjectBased) {
  51674. // If object-based single-prop, then copy over the data to our pooled object.
  51675. data = copyData(nextData, schema.default);
  51676. } else {
  51677. // If is plain single-prop, copy by value the default.
  51678. data = isObjectOrArray(schema.default)
  51679. ? utils.clone(schema.default)
  51680. : schema.default;
  51681. }
  51682. } else {
  51683. // Preserve previously set properties if clobber not enabled.
  51684. previousData = !clobber && this.attrValue;
  51685. // Clone default value if object so components don't share object
  51686. data = previousData instanceof Object
  51687. ? copyData(nextData, previousData)
  51688. : nextData;
  51689. // Apply defaults.
  51690. for (key in schema) {
  51691. defaultValue = schema[key].default;
  51692. if (data[key] !== undefined) { continue; }
  51693. // Clone default value if object so components don't share object
  51694. data[key] = isObjectOrArray(defaultValue)
  51695. ? utils.clone(defaultValue)
  51696. : defaultValue;
  51697. }
  51698. }
  51699. // 2. Gather mixin values.
  51700. for (i = 0; i < mixinEls.length; i++) {
  51701. mixinData = mixinEls[i].getAttribute(this.attrName);
  51702. if (!mixinData) { continue; }
  51703. data = extendProperties(data, mixinData, this.isObjectBased);
  51704. }
  51705. // 3. Gather attribute values (highest precendence).
  51706. if (componentDefined) {
  51707. if (this.isSingleProperty) {
  51708. // If object-based, copy the value to not modify the original.
  51709. if (isObject(newData)) {
  51710. copyData(this.parsingAttrValue, newData);
  51711. return parseProperty(this.parsingAttrValue, schema);
  51712. }
  51713. return parseProperty(newData, schema);
  51714. }
  51715. data = extendProperties(data, newData, this.isObjectBased);
  51716. } else {
  51717. // Parse and coerce using the schema.
  51718. if (this.isSingleProperty) { return parseProperty(data, schema); }
  51719. }
  51720. return parseProperties(data, schema, undefined, this.name, silent);
  51721. },
  51722. /**
  51723. * Attach events from component-defined events map.
  51724. */
  51725. eventsAttach: function () {
  51726. var eventName;
  51727. // Safety detach to prevent double-registration.
  51728. this.eventsDetach();
  51729. for (eventName in this.events) {
  51730. this.el.addEventListener(eventName, this.events[eventName]);
  51731. }
  51732. },
  51733. /**
  51734. * Detach events from component-defined events map.
  51735. */
  51736. eventsDetach: function () {
  51737. var eventName;
  51738. for (eventName in this.events) {
  51739. this.el.removeEventListener(eventName, this.events[eventName]);
  51740. }
  51741. },
  51742. /**
  51743. * Release and free memory.
  51744. */
  51745. destroy: function () {
  51746. this.objectPool.recycle(this.attrValue);
  51747. this.objectPool.recycle(this.oldData);
  51748. this.objectPool.recycle(this.parsingAttrValue);
  51749. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  51750. }
  51751. };
  51752. function eventsBind (component, events) {
  51753. var eventName;
  51754. for (eventName in events) {
  51755. component.events[eventName] = events[eventName].bind(component);
  51756. }
  51757. }
  51758. // For testing.
  51759. if (window.debug) {
  51760. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  51761. }
  51762. /**
  51763. * Register a component to A-Frame.
  51764. *
  51765. * @param {string} name - Component name.
  51766. * @param {object} definition - Component schema and lifecycle method handlers.
  51767. * @returns {object} Component.
  51768. */
  51769. module.exports.registerComponent = function (name, definition) {
  51770. var NewComponent;
  51771. var propertyName;
  51772. var proto = {};
  51773. var schema;
  51774. var schemaIsSingleProp;
  51775. // Warning if component is statically registered after the scene.
  51776. if (document.currentScript && document.currentScript !== aframeScript) {
  51777. scenes.forEach(function checkPosition (sceneEl) {
  51778. // Okay to register component after the scene at runtime.
  51779. if (sceneEl.hasLoaded) { return; }
  51780. // Check that component is declared before the scene.
  51781. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  51782. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  51783. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  51784. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  51785. 'such that the component is available to entities during scene initialization.');
  51786. // For testing.
  51787. if (window.debug) { registrationOrderWarnings[name] = true; }
  51788. });
  51789. }
  51790. if (upperCaseRegExp.test(name) === true) {
  51791. warn('The component name `' + name + '` contains uppercase characters, but ' +
  51792. 'HTML will ignore the capitalization of attribute names. ' +
  51793. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  51794. }
  51795. if (name.indexOf('__') !== -1) {
  51796. throw new Error('The component name `' + name + '` is not allowed. ' +
  51797. 'The sequence __ (double underscore) is reserved to specify an id' +
  51798. ' for multiple components of the same type');
  51799. }
  51800. // Format definition object to prototype object.
  51801. Object.keys(definition).forEach(function (key) {
  51802. proto[key] = {
  51803. value: definition[key],
  51804. writable: true
  51805. };
  51806. });
  51807. if (components[name]) {
  51808. throw new Error('The component `' + name + '` has been already registered. ' +
  51809. 'Check that you are not loading two versions of the same component ' +
  51810. 'or two different components of the same name.');
  51811. }
  51812. NewComponent = function (el, attr, id) {
  51813. Component.call(this, el, attr, id);
  51814. };
  51815. NewComponent.prototype = Object.create(Component.prototype, proto);
  51816. NewComponent.prototype.name = name;
  51817. NewComponent.prototype.isPositionRotationScale =
  51818. name === 'position' || name === 'rotation' || name === 'scale';
  51819. NewComponent.prototype.constructor = NewComponent;
  51820. NewComponent.prototype.system = systems && systems.systems[name];
  51821. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  51822. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  51823. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  51824. NewComponent.prototype.name));
  51825. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  51826. // Keep track of keys that may potentially change the schema.
  51827. if (!schemaIsSingleProp) {
  51828. NewComponent.prototype.schemaChangeKeys = [];
  51829. for (propertyName in schema) {
  51830. if (schema[propertyName].schemaChange) {
  51831. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  51832. }
  51833. }
  51834. }
  51835. // Create object pool for class of components.
  51836. objectPools[name] = utils.objectPool.createPool();
  51837. components[name] = {
  51838. Component: NewComponent,
  51839. dependencies: NewComponent.prototype.dependencies,
  51840. isSingleProp: schemaIsSingleProp,
  51841. multiple: NewComponent.prototype.multiple,
  51842. name: name,
  51843. parse: NewComponent.prototype.parse,
  51844. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  51845. schema: schema,
  51846. stringify: NewComponent.prototype.stringify,
  51847. type: NewComponent.prototype.type
  51848. };
  51849. return NewComponent;
  51850. };
  51851. /**
  51852. * Clone component data.
  51853. * Clone only the properties that are plain objects while keeping a reference for the rest.
  51854. *
  51855. * @param data - Component data to clone.
  51856. * @returns Cloned data.
  51857. */
  51858. function copyData (dest, sourceData) {
  51859. var parsedProperty;
  51860. var key;
  51861. for (key in sourceData) {
  51862. if (sourceData[key] === undefined) { continue; }
  51863. parsedProperty = sourceData[key];
  51864. dest[key] = isObjectOrArray(parsedProperty)
  51865. ? utils.clone(parsedProperty)
  51866. : parsedProperty;
  51867. }
  51868. return dest;
  51869. }
  51870. /**
  51871. * Object extending with checking for single-property schema.
  51872. *
  51873. * @param dest - Destination object or value.
  51874. * @param source - Source object or value
  51875. * @param {boolean} isObjectBased - Whether values are objects.
  51876. * @returns Overridden object or value.
  51877. */
  51878. function extendProperties (dest, source, isObjectBased) {
  51879. var key;
  51880. if (isObjectBased && source.constructor === Object) {
  51881. for (key in source) {
  51882. if (source[key] === undefined) { continue; }
  51883. if (source[key] && source[key].constructor === Object) {
  51884. dest[key] = utils.clone(source[key]);
  51885. } else {
  51886. dest[key] = source[key];
  51887. }
  51888. }
  51889. return dest;
  51890. }
  51891. return source;
  51892. }
  51893. /**
  51894. * Checks if a component has defined a method that needs to run every frame.
  51895. */
  51896. function hasBehavior (component) {
  51897. return component.tick || component.tock;
  51898. }
  51899. /**
  51900. * Wrapper for defined pause method.
  51901. * Pause component by removing tick behavior and calling user's pause method.
  51902. *
  51903. * @param pauseMethod {function}
  51904. */
  51905. function wrapPause (pauseMethod) {
  51906. return function pause () {
  51907. var sceneEl = this.el.sceneEl;
  51908. if (!this.isPlaying) { return; }
  51909. pauseMethod.call(this);
  51910. this.isPlaying = false;
  51911. this.eventsDetach();
  51912. // Remove tick behavior.
  51913. if (!hasBehavior(this)) { return; }
  51914. sceneEl.removeBehavior(this);
  51915. };
  51916. }
  51917. /**
  51918. * Wrapper for defined play method.
  51919. * Play component by adding tick behavior and calling user's play method.
  51920. *
  51921. * @param playMethod {function}
  51922. */
  51923. function wrapPlay (playMethod) {
  51924. return function play () {
  51925. var sceneEl = this.el.sceneEl;
  51926. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  51927. if (!this.initialized || !shouldPlay) { return; }
  51928. playMethod.call(this);
  51929. this.isPlaying = true;
  51930. this.eventsAttach();
  51931. // Add tick behavior.
  51932. if (!hasBehavior(this)) { return; }
  51933. sceneEl.addBehavior(this);
  51934. };
  51935. }
  51936. function isObject (value) {
  51937. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  51938. }
  51939. function isObjectOrArray (value) {
  51940. return value && (value.constructor === Object || value.constructor === Array) &&
  51941. !(value instanceof window.HTMLElement);
  51942. }
  51943. },{"../utils/":197,"./scene/scenes":131,"./schema":133,"./system":135}],125:[function(_dereq_,module,exports){
  51944. var schema = _dereq_('./schema');
  51945. var processSchema = schema.process;
  51946. var geometries = module.exports.geometries = {}; // Registered geometries.
  51947. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  51948. var THREE = _dereq_('../lib/three');
  51949. /**
  51950. * Geometry class definition.
  51951. *
  51952. * Geometries extend the geometry component API to create and register geometry types.
  51953. */
  51954. var Geometry = module.exports.Geometry = function () {};
  51955. Geometry.prototype = {
  51956. /**
  51957. * Contains the type schema and defaults for the data values.
  51958. * Data is coerced into the types of the values of the defaults.
  51959. */
  51960. schema: {},
  51961. /**
  51962. * Init handler. Similar to attachedCallback.
  51963. * Called during shader initialization and is only run once.
  51964. */
  51965. init: function (data) {
  51966. this.geometry = new THREE.Geometry();
  51967. return this.geometry;
  51968. },
  51969. /**
  51970. * Update handler. Similar to attributeChangedCallback.
  51971. * Called whenever the associated geometry data changes.
  51972. *
  51973. * @param {object} data - New geometry data.
  51974. */
  51975. update: function (data) { /* no-op */ }
  51976. };
  51977. /**
  51978. * Registers a geometry to A-Frame.
  51979. *
  51980. * @param {string} name - Geometry name.
  51981. * @param {object} definition - Geometry property and methods.
  51982. * @returns {object} Geometry.
  51983. */
  51984. module.exports.registerGeometry = function (name, definition) {
  51985. var NewGeometry;
  51986. var proto = {};
  51987. // Format definition object to prototype object.
  51988. Object.keys(definition).forEach(function expandDefinition (key) {
  51989. proto[key] = {
  51990. value: definition[key],
  51991. writable: true
  51992. };
  51993. });
  51994. if (geometries[name]) {
  51995. throw new Error('The geometry `' + name + '` has been already registered');
  51996. }
  51997. NewGeometry = function () { Geometry.call(this); };
  51998. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  51999. NewGeometry.prototype.name = name;
  52000. NewGeometry.prototype.constructor = NewGeometry;
  52001. geometries[name] = {
  52002. Geometry: NewGeometry,
  52003. schema: processSchema(NewGeometry.prototype.schema)
  52004. };
  52005. geometryNames.push(name);
  52006. return NewGeometry;
  52007. };
  52008. },{"../lib/three":172,"./schema":133}],126:[function(_dereq_,module,exports){
  52009. var coordinates = _dereq_('../utils/coordinates');
  52010. var debug = _dereq_('debug');
  52011. var error = debug('core:propertyTypes:warn');
  52012. var warn = debug('core:propertyTypes:warn');
  52013. var propertyTypes = module.exports.propertyTypes = {};
  52014. var nonCharRegex = /[,> .[\]:]/;
  52015. var urlRegex = /\url\((.+)\)/;
  52016. // Built-in property types.
  52017. registerPropertyType('audio', '', assetParse);
  52018. registerPropertyType('array', [], arrayParse, arrayStringify);
  52019. registerPropertyType('asset', '', assetParse);
  52020. registerPropertyType('boolean', false, boolParse);
  52021. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  52022. registerPropertyType('int', 0, intParse);
  52023. registerPropertyType('number', 0, numberParse);
  52024. registerPropertyType('map', '', assetParse);
  52025. registerPropertyType('model', '', assetParse);
  52026. registerPropertyType('selector', null, selectorParse, selectorStringify);
  52027. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  52028. registerPropertyType('src', '', srcParse);
  52029. registerPropertyType('string', '', defaultParse, defaultStringify);
  52030. registerPropertyType('time', 0, intParse);
  52031. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  52032. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  52033. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  52034. /**
  52035. * Register a parser for re-use such that when someone uses `type` in the schema,
  52036. * `schema.process` will set the property `parse` and `stringify`.
  52037. *
  52038. * @param {string} type - Type name.
  52039. * @param [defaultValue=null] -
  52040. * Default value to use if component does not define default value.
  52041. * @param {function} [parse=defaultParse] - Parse string function.
  52042. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  52043. */
  52044. function registerPropertyType (type, defaultValue, parse, stringify) {
  52045. if ('type' in propertyTypes) {
  52046. error('Property type ' + type + ' is already registered.');
  52047. return;
  52048. }
  52049. propertyTypes[type] = {
  52050. default: defaultValue,
  52051. parse: parse || defaultParse,
  52052. stringify: stringify || defaultStringify
  52053. };
  52054. }
  52055. module.exports.registerPropertyType = registerPropertyType;
  52056. function arrayParse (value) {
  52057. if (Array.isArray(value)) { return value; }
  52058. if (!value || typeof value !== 'string') { return []; }
  52059. return value.split(',').map(trim);
  52060. function trim (str) { return str.trim(); }
  52061. }
  52062. function arrayStringify (value) {
  52063. return value.join(', ');
  52064. }
  52065. /**
  52066. * For general assets.
  52067. *
  52068. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  52069. * just string.
  52070. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  52071. * just string.
  52072. */
  52073. function assetParse (value) {
  52074. var el;
  52075. var parsedUrl;
  52076. // If an element was provided (e.g. canvas or video), just return it.
  52077. if (typeof value !== 'string') { return value; }
  52078. // Wrapped `url()` in case of data URI.
  52079. parsedUrl = value.match(urlRegex);
  52080. if (parsedUrl) { return parsedUrl[1]; }
  52081. // ID.
  52082. if (value.charAt(0) === '#') {
  52083. el = document.getElementById(value.substring(1));
  52084. if (el) {
  52085. // Pass through media elements. If we have the elements, we don't have to call
  52086. // three.js loaders which would re-request the assets.
  52087. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  52088. return el;
  52089. }
  52090. return el.getAttribute('src');
  52091. }
  52092. warn('"' + value + '" asset not found.');
  52093. return;
  52094. }
  52095. // Non-wrapped url().
  52096. return value;
  52097. }
  52098. function defaultParse (value) {
  52099. return value;
  52100. }
  52101. function defaultStringify (value) {
  52102. if (value === null) { return 'null'; }
  52103. return value.toString();
  52104. }
  52105. function boolParse (value) {
  52106. return value !== 'false' && value !== false;
  52107. }
  52108. function intParse (value) {
  52109. return parseInt(value, 10);
  52110. }
  52111. function numberParse (value) {
  52112. return parseFloat(value, 10);
  52113. }
  52114. function selectorParse (value) {
  52115. if (!value) { return null; }
  52116. if (typeof value !== 'string') { return value; }
  52117. if (value[0] === '#' && !nonCharRegex.test(value)) {
  52118. // When selecting element by ID only, use getElementById for better performance.
  52119. // Don't match like #myId .child.
  52120. return document.getElementById(value.substring(1));
  52121. }
  52122. return document.querySelector(value);
  52123. }
  52124. function selectorAllParse (value) {
  52125. if (!value) { return null; }
  52126. if (typeof value !== 'string') { return value; }
  52127. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  52128. }
  52129. function selectorStringify (value) {
  52130. if (value.getAttribute) {
  52131. return '#' + value.getAttribute('id');
  52132. }
  52133. return defaultStringify(value);
  52134. }
  52135. function selectorAllStringify (value) {
  52136. if (value instanceof Array) {
  52137. return value.map(function (element) {
  52138. return '#' + element.getAttribute('id');
  52139. }).join(', ');
  52140. }
  52141. return defaultStringify(value);
  52142. }
  52143. function srcParse (value) {
  52144. warn('`src` property type is deprecated. Use `asset` instead.');
  52145. return assetParse(value);
  52146. }
  52147. function vecParse (value) {
  52148. return coordinates.parse(value, this.default);
  52149. }
  52150. /**
  52151. * Validate the default values in a schema to match their type.
  52152. *
  52153. * @param {string} type - Property type name.
  52154. * @param defaultVal - Property type default value.
  52155. * @returns {boolean} Whether default value is accurate given the type.
  52156. */
  52157. function isValidDefaultValue (type, defaultVal) {
  52158. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  52159. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  52160. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  52161. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  52162. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  52163. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  52164. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  52165. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  52166. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  52167. if (type === 'selector' && typeof defaultVal !== 'string' &&
  52168. defaultVal !== null) { return false; }
  52169. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  52170. defaultVal !== null) { return false; }
  52171. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  52172. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  52173. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  52174. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  52175. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  52176. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  52177. return true;
  52178. }
  52179. module.exports.isValidDefaultValue = isValidDefaultValue;
  52180. /**
  52181. * Checks if default coordinates are valid.
  52182. *
  52183. * @param possibleCoordinates
  52184. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  52185. * @returns {boolean} Whether coordinates are parsed correctly.
  52186. */
  52187. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  52188. if (possibleCoordinates === null) { return true; }
  52189. if (typeof possibleCoordinates !== 'object') { return false; }
  52190. if (Object.keys(possibleCoordinates).length !== dimensions) {
  52191. return false;
  52192. } else {
  52193. var x = possibleCoordinates.x;
  52194. var y = possibleCoordinates.y;
  52195. var z = possibleCoordinates.z;
  52196. var w = possibleCoordinates.w;
  52197. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  52198. if (dimensions > 2 && typeof z !== 'number') { return false; }
  52199. if (dimensions > 3 && typeof w !== 'number') { return false; }
  52200. }
  52201. return true;
  52202. }
  52203. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  52204. },{"../utils/coordinates":192,"debug":8}],127:[function(_dereq_,module,exports){
  52205. /* global Promise, screen, CustomEvent */
  52206. var initMetaTags = _dereq_('./metaTags').inject;
  52207. var initWakelock = _dereq_('./wakelock');
  52208. var loadingScreen = _dereq_('./loadingScreen');
  52209. var re = _dereq_('../a-register-element');
  52210. var scenes = _dereq_('./scenes');
  52211. var systems = _dereq_('../system').systems;
  52212. var THREE = _dereq_('../../lib/three');
  52213. var utils = _dereq_('../../utils/');
  52214. // Require after.
  52215. var AEntity = _dereq_('../a-entity');
  52216. var ANode = _dereq_('../a-node');
  52217. var initPostMessageAPI = _dereq_('./postMessage');
  52218. var bind = utils.bind;
  52219. var isIOS = utils.device.isIOS();
  52220. var isMobile = utils.device.isMobile();
  52221. var isWebXRAvailable = utils.device.isWebXRAvailable;
  52222. var registerElement = re.registerElement;
  52223. var warn = utils.debug('core:a-scene:warn');
  52224. /**
  52225. * Scene element, holds all entities.
  52226. *
  52227. * @member {array} behaviors - Component instances that have registered themselves to be
  52228. updated on every tick.
  52229. * @member {object} camera - three.js Camera object.
  52230. * @member {object} canvas
  52231. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  52232. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  52233. * @member {object} object3D - Root three.js Scene object.
  52234. * @member {object} renderer
  52235. * @member {bool} renderStarted
  52236. * @member {object} systems - Registered instantiated systems.
  52237. * @member {number} time
  52238. */
  52239. module.exports.AScene = registerElement('a-scene', {
  52240. prototype: Object.create(AEntity.prototype, {
  52241. createdCallback: {
  52242. value: function () {
  52243. this.clock = new THREE.Clock();
  52244. this.isIOS = isIOS;
  52245. this.isMobile = isMobile;
  52246. this.hasWebXR = isWebXRAvailable;
  52247. this.isScene = true;
  52248. this.object3D = new THREE.Scene();
  52249. var self = this;
  52250. this.object3D.onAfterRender = function (renderer, scene, camera) {
  52251. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  52252. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  52253. };
  52254. this.render = bind(this.render, this);
  52255. this.systems = {};
  52256. this.systemNames = [];
  52257. this.time = this.delta = 0;
  52258. this.behaviors = {tick: [], tock: []};
  52259. this.hasLoaded = false;
  52260. this.isPlaying = false;
  52261. this.originalHTML = this.innerHTML;
  52262. // Default components.
  52263. this.setAttribute('inspector', '');
  52264. this.setAttribute('keyboard-shortcuts', '');
  52265. this.setAttribute('screenshot', '');
  52266. this.setAttribute('vr-mode-ui', '');
  52267. }
  52268. },
  52269. addFullScreenStyles: {
  52270. value: function () {
  52271. document.documentElement.classList.add('a-fullscreen');
  52272. }
  52273. },
  52274. removeFullScreenStyles: {
  52275. value: function () {
  52276. document.documentElement.classList.remove('a-fullscreen');
  52277. }
  52278. },
  52279. attachedCallback: {
  52280. value: function () {
  52281. var self = this;
  52282. var embedded = this.hasAttribute('embedded');
  52283. // Renderer initialization
  52284. setupCanvas(this);
  52285. this.setupRenderer();
  52286. this.resize();
  52287. if (!embedded) { this.addFullScreenStyles(); }
  52288. initPostMessageAPI(this);
  52289. initMetaTags(this);
  52290. initWakelock(this);
  52291. // Handler to exit VR (e.g., Oculus Browser back button).
  52292. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  52293. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  52294. // Bind functions.
  52295. this.enterVRBound = function () { self.enterVR(); };
  52296. this.exitVRBound = function () { self.exitVR(); };
  52297. this.exitVRTrueBound = function () { self.exitVR(true); };
  52298. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  52299. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  52300. if (!isWebXRAvailable) {
  52301. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  52302. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  52303. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  52304. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  52305. // Register for mouse restricted events while in VR
  52306. // (e.g. mouse no longer available on desktop 2D view)
  52307. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  52308. // Register for mouse unrestricted events while in VR
  52309. // (e.g. mouse once again available on desktop 2D view)
  52310. window.addEventListener('vrdisplaypointerunrestricted',
  52311. this.pointerUnrestrictedBound);
  52312. }
  52313. // Camera set up by camera system.
  52314. this.addEventListener('cameraready', function () {
  52315. self.attachedCallbackPostCamera();
  52316. });
  52317. this.initSystems();
  52318. }
  52319. },
  52320. attachedCallbackPostCamera: {
  52321. value: function () {
  52322. var resize;
  52323. var self = this;
  52324. resize = bind(this.resize, this);
  52325. window.addEventListener('load', resize);
  52326. window.addEventListener('resize', function () {
  52327. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  52328. // where the window does not contain the correct viewport size
  52329. // after an orientation change. The window size is correct if the operation
  52330. // is postponed a few milliseconds.
  52331. // self.resize can be called directly once the bug above is fixed.
  52332. if (self.isIOS) {
  52333. setTimeout(resize, 100);
  52334. } else {
  52335. resize();
  52336. }
  52337. });
  52338. this.play();
  52339. // Add to scene index.
  52340. scenes.push(this);
  52341. },
  52342. writable: window.debug
  52343. },
  52344. /**
  52345. * Initialize all systems.
  52346. */
  52347. initSystems: {
  52348. value: function () {
  52349. var name;
  52350. // Initialize camera system first.
  52351. this.initSystem('camera');
  52352. for (name in systems) {
  52353. if (name === 'camera') { continue; }
  52354. this.initSystem(name);
  52355. }
  52356. }
  52357. },
  52358. /**
  52359. * Initialize a system.
  52360. */
  52361. initSystem: {
  52362. value: function (name) {
  52363. if (this.systems[name]) { return; }
  52364. this.systems[name] = new systems[name](this);
  52365. this.systemNames.push(name);
  52366. }
  52367. },
  52368. /**
  52369. * Shut down scene on detach.
  52370. */
  52371. detachedCallback: {
  52372. value: function () {
  52373. // Remove from scene index.
  52374. var sceneIndex = scenes.indexOf(this);
  52375. scenes.splice(sceneIndex, 1);
  52376. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  52377. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  52378. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  52379. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  52380. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  52381. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  52382. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  52383. }
  52384. },
  52385. /**
  52386. * Add ticks and tocks.
  52387. *
  52388. * @param {object} behavior - A component.
  52389. */
  52390. addBehavior: {
  52391. value: function (behavior) {
  52392. var behaviorArr;
  52393. var behaviors = this.behaviors;
  52394. var behaviorType;
  52395. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  52396. for (behaviorType in behaviors) {
  52397. if (!behavior[behaviorType]) { continue; }
  52398. behaviorArr = this.behaviors[behaviorType];
  52399. if (behaviorArr.indexOf(behavior) === -1) {
  52400. behaviorArr.push(behavior);
  52401. }
  52402. }
  52403. }
  52404. },
  52405. /**
  52406. * For tests.
  52407. */
  52408. getPointerLockElement: {
  52409. value: function () {
  52410. return document.pointerLockElement;
  52411. },
  52412. writable: window.debug
  52413. },
  52414. /**
  52415. * For tests.
  52416. */
  52417. checkHeadsetConnected: {
  52418. value: utils.device.checkHeadsetConnected,
  52419. writable: window.debug
  52420. },
  52421. /**
  52422. * Call `requestPresent` if WebVR or WebVR polyfill.
  52423. * Call `requestFullscreen` on desktop.
  52424. * Handle events, states, fullscreen styles.
  52425. *
  52426. * @returns {Promise}
  52427. */
  52428. enterVR: {
  52429. value: function () {
  52430. var self = this;
  52431. var vrDisplay;
  52432. var vrManager = self.renderer.vr;
  52433. // Don't enter VR if already in VR.
  52434. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  52435. // Has VR.
  52436. if (this.checkHeadsetConnected() || this.isMobile) {
  52437. vrDisplay = utils.device.getVRDisplay();
  52438. vrManager.enabled = true;
  52439. vrManager.setDevice(vrDisplay);
  52440. if (this.hasWebXR) {
  52441. // XR API.
  52442. if (this.xrSession) {
  52443. this.xrSession.removeEventListener('end', this.exitVRBound);
  52444. }
  52445. navigator.xr.requestSession('immersive-vr').then(function requestSuccess (xrSession) {
  52446. self.xrSession = xrSession;
  52447. vrManager.setSession(xrSession);
  52448. xrSession.addEventListener('end', self.exitVRBound);
  52449. enterVRSuccess();
  52450. });
  52451. } else {
  52452. vrDisplay = utils.device.getVRDisplay();
  52453. vrManager.setDevice(vrDisplay);
  52454. if (vrDisplay.isPresenting &&
  52455. !window.hasNativeWebVRImplementation) {
  52456. enterVRSuccess();
  52457. return Promise.resolve();
  52458. }
  52459. var rendererSystem = this.getAttribute('renderer');
  52460. var presentationAttributes = {
  52461. highRefreshRate: rendererSystem.highRefreshRate,
  52462. foveationLevel: rendererSystem.foveationLevel
  52463. };
  52464. return vrDisplay.requestPresent([{
  52465. source: this.canvas,
  52466. attributes: presentationAttributes
  52467. }]).then(enterVRSuccess, enterVRFailure);
  52468. }
  52469. return Promise.resolve();
  52470. }
  52471. // No VR.
  52472. enterVRSuccess();
  52473. return Promise.resolve();
  52474. // Callback that happens on enter VR success or enter fullscreen (any API).
  52475. function enterVRSuccess () {
  52476. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  52477. // the first requestPresent could be called from ondisplayactivate and there is no way
  52478. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  52479. // for the actual requestPresent. Need to make sure there are no issues with firing the
  52480. // vrdisplaypresentchange multiple times.
  52481. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  52482. if (!isWebXRAvailable) { window.dispatchEvent(event); }
  52483. self.addState('vr-mode');
  52484. self.emit('enter-vr', {target: self});
  52485. // Lock to landscape orientation on mobile.
  52486. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  52487. screen.orientation.lock('landscape');
  52488. }
  52489. self.addFullScreenStyles();
  52490. // On mobile, the polyfill handles fullscreen.
  52491. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  52492. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  52493. // connected.
  52494. if (!self.isMobile && !self.checkHeadsetConnected()) {
  52495. requestFullscreen(self.canvas);
  52496. }
  52497. self.renderer.setAnimationLoop(self.render);
  52498. self.resize();
  52499. }
  52500. function enterVRFailure (err) {
  52501. if (err && err.message) {
  52502. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  52503. } else {
  52504. throw new Error('Failed to enter VR mode (`requestPresent`).');
  52505. }
  52506. }
  52507. },
  52508. writable: true
  52509. },
  52510. /**
  52511. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  52512. * Handle events, states, fullscreen styles.
  52513. *
  52514. * @returns {Promise}
  52515. */
  52516. exitVR: {
  52517. value: function () {
  52518. var self = this;
  52519. var vrDisplay;
  52520. var vrManager = this.renderer.vr;
  52521. // Don't exit VR if not in VR.
  52522. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  52523. // Handle exiting VR if not yet already and in a headset or polyfill.
  52524. if (this.checkHeadsetConnected() || this.isMobile) {
  52525. vrManager.enabled = false;
  52526. vrDisplay = utils.device.getVRDisplay();
  52527. if (this.hasWebXR) {
  52528. this.xrSession.removeEventListener('end', this.exitVRBound);
  52529. this.xrSession.end();
  52530. vrManager.setSession(null);
  52531. } else {
  52532. if (vrDisplay.isPresenting) {
  52533. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  52534. }
  52535. }
  52536. } else {
  52537. exitFullscreen();
  52538. }
  52539. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  52540. exitVRSuccess();
  52541. return Promise.resolve();
  52542. function exitVRSuccess () {
  52543. self.removeState('vr-mode');
  52544. // Lock to landscape orientation on mobile.
  52545. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  52546. screen.orientation.unlock();
  52547. }
  52548. // Exiting VR in embedded mode, no longer need fullscreen styles.
  52549. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  52550. self.resize();
  52551. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  52552. self.renderer.setPixelRatio(window.devicePixelRatio);
  52553. self.emit('exit-vr', {target: self});
  52554. }
  52555. function exitVRFailure (err) {
  52556. if (err && err.message) {
  52557. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  52558. } else {
  52559. throw new Error('Failed to exit VR mode (`exitPresent`).');
  52560. }
  52561. }
  52562. },
  52563. writable: true
  52564. },
  52565. pointerRestricted: {
  52566. value: function () {
  52567. if (this.canvas) {
  52568. var pointerLockElement = this.getPointerLockElement();
  52569. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  52570. // Recreate pointer lock on the canvas, if taken on another element.
  52571. document.exitPointerLock();
  52572. }
  52573. if (this.canvas.requestPointerLock) {
  52574. this.canvas.requestPointerLock();
  52575. }
  52576. }
  52577. }
  52578. },
  52579. pointerUnrestricted: {
  52580. value: function () {
  52581. var pointerLockElement = this.getPointerLockElement();
  52582. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  52583. document.exitPointerLock();
  52584. }
  52585. }
  52586. },
  52587. /**
  52588. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  52589. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  52590. */
  52591. onVRPresentChange: {
  52592. value: function (evt) {
  52593. // Polyfill places display inside the detail property
  52594. var display = evt.display || evt.detail.display;
  52595. // Entering VR.
  52596. if (display.isPresenting) {
  52597. this.enterVR();
  52598. return;
  52599. }
  52600. // Exiting VR.
  52601. this.exitVR();
  52602. }
  52603. },
  52604. /**
  52605. * Wraps Entity.getAttribute to take into account for systems.
  52606. * If system exists, then return system data rather than possible component data.
  52607. */
  52608. getAttribute: {
  52609. value: function (attr) {
  52610. var system = this.systems[attr];
  52611. if (system) { return system.data; }
  52612. return AEntity.prototype.getAttribute.call(this, attr);
  52613. }
  52614. },
  52615. /**
  52616. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  52617. * what `getAttribute` is now. Now legacy code.
  52618. */
  52619. getComputedAttribute: {
  52620. value: function (attr) {
  52621. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  52622. this.getAttribute(attr);
  52623. }
  52624. },
  52625. /**
  52626. * Wraps Entity.getDOMAttribute to take into account for systems.
  52627. * If system exists, then return system data rather than possible component data.
  52628. */
  52629. getDOMAttribute: {
  52630. value: function (attr) {
  52631. var system = this.systems[attr];
  52632. if (system) { return system.data; }
  52633. return AEntity.prototype.getDOMAttribute.call(this, attr);
  52634. }
  52635. },
  52636. /**
  52637. * Wrap Entity.setAttribute to take into account for systems.
  52638. * If system exists, then skip component initialization checks and do a normal
  52639. * setAttribute.
  52640. */
  52641. setAttribute: {
  52642. value: function (attr, value, componentPropValue) {
  52643. var system = this.systems[attr];
  52644. if (system) {
  52645. ANode.prototype.setAttribute.call(this, attr, value);
  52646. system.updateProperties(value);
  52647. return;
  52648. }
  52649. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  52650. }
  52651. },
  52652. /**
  52653. * @param {object} behavior - A component.
  52654. */
  52655. removeBehavior: {
  52656. value: function (behavior) {
  52657. var behaviorArr;
  52658. var behaviorType;
  52659. var behaviors = this.behaviors;
  52660. var index;
  52661. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  52662. // array.
  52663. for (behaviorType in behaviors) {
  52664. if (!behavior[behaviorType]) { continue; }
  52665. behaviorArr = this.behaviors[behaviorType];
  52666. index = behaviorArr.indexOf(behavior);
  52667. if (index !== -1) { behaviorArr.splice(index, 1); }
  52668. }
  52669. }
  52670. },
  52671. resize: {
  52672. value: function () {
  52673. var camera = this.camera;
  52674. var canvas = this.canvas;
  52675. var embedded;
  52676. var isVRPresenting;
  52677. var size;
  52678. var isPresenting = this.renderer.vr.isPresenting();
  52679. isVRPresenting = this.renderer.vr.enabled && isPresenting;
  52680. // Do not update renderer, if a camera or a canvas have not been injected.
  52681. // In VR mode, three handles canvas resize based on the dimensions returned by
  52682. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  52683. // the window size, therefore should not be overwritten with the window's width and
  52684. // height, // except when in fullscreen mode.
  52685. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  52686. return;
  52687. }
  52688. // Update camera.
  52689. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  52690. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  52691. camera.aspect = size.width / size.height;
  52692. camera.updateProjectionMatrix();
  52693. // Notify renderer of size change.
  52694. this.renderer.setSize(size.width, size.height, false);
  52695. this.emit('rendererresize', null, false);
  52696. },
  52697. writable: true
  52698. },
  52699. setupRenderer: {
  52700. value: function () {
  52701. var self = this;
  52702. var renderer;
  52703. var rendererAttr;
  52704. var rendererAttrString;
  52705. var rendererConfig;
  52706. rendererConfig = {
  52707. alpha: true,
  52708. antialias: !isMobile,
  52709. canvas: this.canvas,
  52710. logarithmicDepthBuffer: false
  52711. };
  52712. this.maxCanvasSize = {height: 1920, width: 1920};
  52713. if (this.hasAttribute('renderer')) {
  52714. rendererAttrString = this.getAttribute('renderer');
  52715. rendererAttr = utils.styleParser.parse(rendererAttrString);
  52716. if (rendererAttr.precision) {
  52717. rendererConfig.precision = rendererAttr.precision + 'p';
  52718. }
  52719. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  52720. rendererConfig.antialias = rendererAttr.antialias === 'true';
  52721. }
  52722. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  52723. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  52724. }
  52725. if (rendererAttr.alpha) {
  52726. rendererConfig.alpha = rendererAttr.alpha === 'true';
  52727. }
  52728. this.maxCanvasSize = {
  52729. width: rendererAttr.maxCanvasWidth
  52730. ? parseInt(rendererAttr.maxCanvasWidth)
  52731. : this.maxCanvasSize.width,
  52732. height: rendererAttr.maxCanvasHeight
  52733. ? parseInt(rendererAttr.maxCanvasHeight)
  52734. : this.maxCanvasSize.height
  52735. };
  52736. }
  52737. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  52738. renderer.setPixelRatio(window.devicePixelRatio);
  52739. renderer.sortObjects = false;
  52740. if (this.camera) { renderer.vr.setPoseTarget(this.camera.el.object3D); }
  52741. this.addEventListener('camera-set-active', function () {
  52742. renderer.vr.setPoseTarget(self.camera.el.object3D);
  52743. });
  52744. loadingScreen.setup(this, getCanvasSize);
  52745. },
  52746. writable: window.debug
  52747. },
  52748. /**
  52749. * Handler attached to elements to help scene know when to kick off.
  52750. * Scene waits for all entities to load.
  52751. */
  52752. play: {
  52753. value: function () {
  52754. var self = this;
  52755. var sceneEl = this;
  52756. if (this.renderStarted) {
  52757. AEntity.prototype.play.call(this);
  52758. return;
  52759. }
  52760. this.addEventListener('loaded', function () {
  52761. var renderer = this.renderer;
  52762. var vrDisplay;
  52763. var vrManager = this.renderer.vr;
  52764. AEntity.prototype.play.call(this); // .play() *before* render.
  52765. if (sceneEl.renderStarted) { return; }
  52766. sceneEl.resize();
  52767. // Kick off render loop.
  52768. if (sceneEl.renderer) {
  52769. if (window.performance) { window.performance.mark('render-started'); }
  52770. loadingScreen.remove();
  52771. vrDisplay = utils.device.getVRDisplay();
  52772. if (vrDisplay && vrDisplay.isPresenting) {
  52773. vrManager.setDevice(vrDisplay);
  52774. vrManager.enabled = true;
  52775. sceneEl.enterVR();
  52776. }
  52777. renderer.setAnimationLoop(this.render);
  52778. sceneEl.renderStarted = true;
  52779. sceneEl.emit('renderstart');
  52780. }
  52781. });
  52782. // setTimeout to wait for all nodes to attach and run their callbacks.
  52783. setTimeout(function () {
  52784. AEntity.prototype.load.call(self);
  52785. });
  52786. }
  52787. },
  52788. /**
  52789. * Wrap `updateComponent` to not initialize the component if the component has a system
  52790. * (aframevr/aframe#2365).
  52791. */
  52792. updateComponent: {
  52793. value: function (componentName) {
  52794. if (componentName in systems) { return; }
  52795. AEntity.prototype.updateComponent.apply(this, arguments);
  52796. }
  52797. },
  52798. /**
  52799. * Behavior-updater meant to be called from scene render.
  52800. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  52801. * needing to render.
  52802. */
  52803. tick: {
  52804. value: function (time, timeDelta) {
  52805. var i;
  52806. var systems = this.systems;
  52807. // Components.
  52808. for (i = 0; i < this.behaviors.tick.length; i++) {
  52809. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  52810. this.behaviors.tick[i].tick(time, timeDelta);
  52811. }
  52812. // Systems.
  52813. for (i = 0; i < this.systemNames.length; i++) {
  52814. if (!systems[this.systemNames[i]].tick) { continue; }
  52815. systems[this.systemNames[i]].tick(time, timeDelta);
  52816. }
  52817. }
  52818. },
  52819. /**
  52820. * Behavior-updater meant to be called after scene render for post processing purposes.
  52821. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  52822. * needing to render.
  52823. */
  52824. tock: {
  52825. value: function (time, timeDelta, camera) {
  52826. var i;
  52827. var systems = this.systems;
  52828. // Components.
  52829. for (i = 0; i < this.behaviors.tock.length; i++) {
  52830. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  52831. this.behaviors.tock[i].tock(time, timeDelta, camera);
  52832. }
  52833. // Systems.
  52834. for (i = 0; i < this.systemNames.length; i++) {
  52835. if (!systems[this.systemNames[i]].tock) { continue; }
  52836. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  52837. }
  52838. }
  52839. },
  52840. /**
  52841. * The render loop.
  52842. *
  52843. * Updates animations.
  52844. * Updates behaviors.
  52845. * Renders with request animation frame.
  52846. */
  52847. render: {
  52848. value: function (time, frame) {
  52849. var renderer = this.renderer;
  52850. this.frame = frame;
  52851. this.delta = this.clock.getDelta() * 1000;
  52852. this.time = this.clock.elapsedTime * 1000;
  52853. if (this.isPlaying) { this.tick(this.time, this.delta); }
  52854. renderer.render(this.object3D, this.camera);
  52855. },
  52856. writable: true
  52857. }
  52858. })
  52859. });
  52860. /**
  52861. * Return the canvas size where the scene will be rendered.
  52862. * Will be always the window size except when the scene is embedded.
  52863. * The parent size (less than max size) will be returned in that case.
  52864. *
  52865. * @param {object} canvasEl - the canvas element
  52866. * @param {boolean} embedded - Is the scene embedded?
  52867. * @param {object} max - Max size parameters
  52868. * @param {boolean} isVR - If in VR
  52869. */
  52870. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  52871. if (embedded) {
  52872. return {
  52873. height: canvasEl.parentElement.offsetHeight,
  52874. width: canvasEl.parentElement.offsetWidth
  52875. };
  52876. }
  52877. return getMaxSize(maxSize, isVR);
  52878. }
  52879. /**
  52880. * Return the canvas size. Will be the window size unless that size is greater than the
  52881. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  52882. * maintaining aspect ratio
  52883. *
  52884. * @param {object} maxSize - Max size parameters (width and height).
  52885. * @param {boolean} isVR - If in VR.
  52886. * @returns {object} Width and height.
  52887. */
  52888. function getMaxSize (maxSize, isVR) {
  52889. var aspectRatio;
  52890. var size;
  52891. var pixelRatio = window.devicePixelRatio;
  52892. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  52893. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  52894. return size;
  52895. }
  52896. if (size.width * pixelRatio < maxSize.width &&
  52897. size.height * pixelRatio < maxSize.height) {
  52898. return size;
  52899. }
  52900. aspectRatio = size.width / size.height;
  52901. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  52902. size.width = Math.round(maxSize.width / pixelRatio);
  52903. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  52904. }
  52905. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  52906. size.height = Math.round(maxSize.height / pixelRatio);
  52907. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  52908. }
  52909. return size;
  52910. }
  52911. function requestFullscreen (canvas) {
  52912. var requestFullscreen =
  52913. canvas.requestFullscreen ||
  52914. canvas.webkitRequestFullscreen ||
  52915. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  52916. canvas.msRequestFullscreen;
  52917. // Hide navigation buttons on Android.
  52918. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  52919. }
  52920. function exitFullscreen () {
  52921. var fullscreenEl =
  52922. document.fullscreenElement ||
  52923. document.webkitFullscreenElement ||
  52924. document.mozFullScreenElement;
  52925. if (!fullscreenEl) { return; }
  52926. if (document.exitFullscreen) {
  52927. document.exitFullscreen();
  52928. } else if (document.mozCancelFullScreen) {
  52929. document.mozCancelFullScreen();
  52930. } else if (document.webkitExitFullscreen) {
  52931. document.webkitExitFullscreen();
  52932. }
  52933. }
  52934. function setupCanvas (sceneEl) {
  52935. var canvasEl;
  52936. canvasEl = document.createElement('canvas');
  52937. canvasEl.classList.add('a-canvas');
  52938. // Mark canvas as provided/injected by A-Frame.
  52939. canvasEl.dataset.aframeCanvas = true;
  52940. sceneEl.appendChild(canvasEl);
  52941. document.addEventListener('fullscreenchange', onFullScreenChange);
  52942. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  52943. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  52944. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  52945. // Prevent overscroll on mobile.
  52946. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  52947. // Set canvas on scene.
  52948. sceneEl.canvas = canvasEl;
  52949. sceneEl.emit('render-target-loaded', {target: canvasEl});
  52950. // For unknown reasons a synchronous resize does not work on desktop when
  52951. // entering/exiting fullscreen.
  52952. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  52953. function onFullScreenChange () {
  52954. var fullscreenEl =
  52955. document.fullscreenElement ||
  52956. document.mozFullScreenElement ||
  52957. document.webkitFullscreenElement;
  52958. // No fullscren element === exit fullscreen
  52959. if (!fullscreenEl) { sceneEl.exitVR(); }
  52960. document.activeElement.blur();
  52961. document.body.focus();
  52962. }
  52963. }
  52964. module.exports.setupCanvas = setupCanvas; // For testing.
  52965. },{"../../lib/three":172,"../../utils/":197,"../a-entity":120,"../a-node":122,"../a-register-element":123,"../system":135,"./loadingScreen":128,"./metaTags":129,"./postMessage":130,"./scenes":131,"./wakelock":132}],128:[function(_dereq_,module,exports){
  52966. /* global THREE */
  52967. var utils = _dereq_('../../utils/');
  52968. var styleParser = utils.styleParser;
  52969. var sceneEl;
  52970. var titleEl;
  52971. var getSceneCanvasSize;
  52972. var ATTR_NAME = 'loading-screen';
  52973. var LOADER_TITLE_CLASS = 'a-loader-title';
  52974. module.exports.setup = function setup (el, getCanvasSize) {
  52975. sceneEl = el;
  52976. getSceneCanvasSize = getCanvasSize;
  52977. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  52978. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  52979. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  52980. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  52981. var loaderScene;
  52982. var sphereGeometry;
  52983. var sphereMaterial;
  52984. var sphereMesh1;
  52985. var sphereMesh2;
  52986. var sphereMesh3;
  52987. var camera;
  52988. var clock;
  52989. var time;
  52990. var render;
  52991. if (!loaderEnabled) { return; }
  52992. // Setup Scene.
  52993. loaderScene = new THREE.Scene();
  52994. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  52995. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  52996. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  52997. sphereMesh2 = sphereMesh1.clone();
  52998. sphereMesh3 = sphereMesh1.clone();
  52999. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  53000. clock = new THREE.Clock();
  53001. time = 0;
  53002. render = function () {
  53003. sceneEl.renderer.render(loaderScene, camera);
  53004. time = clock.getElapsedTime() % 4;
  53005. sphereMesh1.visible = time >= 1;
  53006. sphereMesh2.visible = time >= 2;
  53007. sphereMesh3.visible = time >= 3;
  53008. };
  53009. loaderScene.background = new THREE.Color(backgroundColor);
  53010. loaderScene.add(camera);
  53011. sphereMesh1.position.set(-1, 0, -15);
  53012. sphereMesh2.position.set(0, 0, -15);
  53013. sphereMesh3.position.set(1, 0, -15);
  53014. camera.add(sphereMesh1);
  53015. camera.add(sphereMesh2);
  53016. camera.add(sphereMesh3);
  53017. setupTitle();
  53018. // Delay 200ms to avoid loader flashes.
  53019. setTimeout(function () {
  53020. if (sceneEl.hasLoaded) { return; }
  53021. resize(camera);
  53022. titleEl.style.display = 'block';
  53023. window.addEventListener('resize', function () { resize(camera); });
  53024. sceneEl.renderer.setAnimationLoop(render);
  53025. }, 200);
  53026. };
  53027. module.exports.remove = function remove () {
  53028. window.removeEventListener('resize', resize);
  53029. if (!titleEl) { return; }
  53030. // Hide title.
  53031. titleEl.style.display = 'none';
  53032. };
  53033. function resize (camera) {
  53034. var embedded = sceneEl.hasAttribute('embedded');
  53035. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  53036. camera.aspect = size.width / size.height;
  53037. camera.updateProjectionMatrix();
  53038. // Notify renderer of size change.
  53039. sceneEl.renderer.setSize(size.width, size.height, false);
  53040. }
  53041. function setupTitle () {
  53042. titleEl = document.createElement('div');
  53043. titleEl.className = LOADER_TITLE_CLASS;
  53044. titleEl.innerHTML = document.title;
  53045. titleEl.style.display = 'none';
  53046. sceneEl.appendChild(titleEl);
  53047. }
  53048. },{"../../utils/":197}],129:[function(_dereq_,module,exports){
  53049. var constants = _dereq_('../../constants/');
  53050. var extend = _dereq_('../../utils').extend;
  53051. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  53052. 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'}),
  53053. // W3C-standardised meta tags.
  53054. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  53055. Meta({name: 'theme-color', content: 'black'})
  53056. ];
  53057. var MOBILE_IOS_HEAD_TAGS = [
  53058. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  53059. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  53060. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  53061. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  53062. ];
  53063. function Meta (attrs) {
  53064. return {
  53065. tagName: 'meta',
  53066. attributes: attrs,
  53067. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  53068. };
  53069. }
  53070. function Link (attrs) {
  53071. return {
  53072. tagName: 'link',
  53073. attributes: attrs,
  53074. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  53075. };
  53076. }
  53077. /**
  53078. * Injects the necessary metatags in the document for mobile support:
  53079. * 1. Prevent the user to zoom in the document.
  53080. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  53081. * values and the canvas is properly scaled.
  53082. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  53083. * iOS.
  53084. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  53085. *
  53086. * @param {object} scene - Scene element
  53087. * @returns {Array}
  53088. */
  53089. module.exports.inject = function injectHeadTags (scene) {
  53090. var headEl = document.head;
  53091. var headScriptEl = headEl.querySelector('script');
  53092. var tag;
  53093. var headTags = [];
  53094. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  53095. if (scene.isIOS) {
  53096. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  53097. }
  53098. return headTags;
  53099. function createAndInjectTag (tagObj) {
  53100. if (!tagObj || tagObj.exists()) { return; }
  53101. tag = createTag(tagObj);
  53102. if (!tag) { return; }
  53103. if (headScriptEl) {
  53104. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  53105. } else {
  53106. headEl.appendChild(tag);
  53107. }
  53108. headTags.push(tag);
  53109. }
  53110. };
  53111. function createTag (tagObj) {
  53112. if (!tagObj || !tagObj.tagName) { return; }
  53113. var meta = document.createElement(tagObj.tagName);
  53114. meta.setAttribute(constants.AFRAME_INJECTED, '');
  53115. return extend(meta, tagObj.attributes);
  53116. }
  53117. },{"../../constants/":116,"../../utils":197}],130:[function(_dereq_,module,exports){
  53118. var bind = _dereq_('../../utils/bind');
  53119. var isIframed = _dereq_('../../utils/').isIframed;
  53120. /**
  53121. * Provides a post message API for scenes contained
  53122. * in an iframe.
  53123. */
  53124. module.exports = function initPostMessageAPI (scene) {
  53125. // Handles fullscreen behavior when inside an iframe.
  53126. if (!isIframed()) { return; }
  53127. // postMessage API handler
  53128. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  53129. };
  53130. function postMessageAPIHandler (event) {
  53131. var scene = this;
  53132. if (!event.data) { return; }
  53133. switch (event.data.type) {
  53134. case 'vr': {
  53135. switch (event.data.data) {
  53136. case 'enter':
  53137. scene.enterVR();
  53138. break;
  53139. case 'exit':
  53140. scene.exitVR();
  53141. break;
  53142. }
  53143. }
  53144. }
  53145. }
  53146. },{"../../utils/":197,"../../utils/bind":191}],131:[function(_dereq_,module,exports){
  53147. /*
  53148. Scene index for keeping track of created scenes.
  53149. */
  53150. module.exports = [];
  53151. },{}],132:[function(_dereq_,module,exports){
  53152. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  53153. module.exports = function initWakelock (scene) {
  53154. if (!scene.isMobile) { return; }
  53155. var wakelock = scene.wakelock = new Wakelock();
  53156. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  53157. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  53158. };
  53159. },{"../../../vendor/wakelock/wakelock":210}],133:[function(_dereq_,module,exports){
  53160. var utils = _dereq_('../utils/');
  53161. var PropertyTypes = _dereq_('./propertyTypes');
  53162. var debug = utils.debug;
  53163. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  53164. var propertyTypes = PropertyTypes.propertyTypes;
  53165. var warn = debug('core:schema:warn');
  53166. /**
  53167. * A schema is classified as a schema for a single property if:
  53168. * - `type` is defined on the schema as a string.
  53169. * - OR `default` is defined on the schema, as a reserved keyword.
  53170. * - OR schema is empty.
  53171. */
  53172. function isSingleProperty (schema) {
  53173. if ('type' in schema) {
  53174. return typeof schema.type === 'string';
  53175. }
  53176. return 'default' in schema;
  53177. }
  53178. module.exports.isSingleProperty = isSingleProperty;
  53179. /**
  53180. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  53181. *
  53182. * @param {object} schema
  53183. * @param {string} componentName
  53184. * @returns {object} Schema.
  53185. */
  53186. module.exports.process = function (schema, componentName) {
  53187. var propName;
  53188. // For single property schema, run processPropDefinition over the whole schema.
  53189. if (isSingleProperty(schema)) {
  53190. return processPropertyDefinition(schema, componentName);
  53191. }
  53192. // For multi-property schema, run processPropDefinition over each property definition.
  53193. for (propName in schema) {
  53194. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  53195. }
  53196. return schema;
  53197. };
  53198. /**
  53199. * Inject default value, parser, stringifier for single property.
  53200. *
  53201. * @param {object} propDefinition
  53202. * @param {string} componentName
  53203. */
  53204. function processPropertyDefinition (propDefinition, componentName) {
  53205. var defaultVal = propDefinition.default;
  53206. var isCustomType;
  53207. var propType;
  53208. var typeName = propDefinition.type;
  53209. // Type inference.
  53210. if (!propDefinition.type) {
  53211. if (defaultVal !== undefined &&
  53212. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  53213. // Type inference.
  53214. typeName = typeof defaultVal;
  53215. } else if (Array.isArray(defaultVal)) {
  53216. typeName = 'array';
  53217. } else {
  53218. // Fall back to string.
  53219. typeName = 'string';
  53220. }
  53221. } else if (propDefinition.type === 'bool') {
  53222. typeName = 'boolean';
  53223. } else if (propDefinition.type === 'float') {
  53224. typeName = 'number';
  53225. }
  53226. propType = propertyTypes[typeName];
  53227. if (!propType) {
  53228. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  53229. }
  53230. // Fill in parse and stringify using property types.
  53231. isCustomType = !!propDefinition.parse;
  53232. propDefinition.parse = propDefinition.parse || propType.parse;
  53233. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  53234. // Fill in type name.
  53235. propDefinition.type = typeName;
  53236. // Check that default value exists.
  53237. if ('default' in propDefinition) {
  53238. // Check that default values are valid.
  53239. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  53240. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  53241. '` in component `' + componentName + '`');
  53242. }
  53243. } else {
  53244. // Fill in default value.
  53245. propDefinition.default = propType.default;
  53246. }
  53247. return propDefinition;
  53248. }
  53249. module.exports.processPropertyDefinition = processPropertyDefinition;
  53250. /**
  53251. * Parse propData using schema. Use default values if not existing in propData.
  53252. *
  53253. * @param {object} propData - Unparsed properties.
  53254. * @param {object} schema - Property types definition.
  53255. * @param {boolean} getPartialData - Whether to return full component data or just the data
  53256. * with keys in `propData`.
  53257. * @param {string } componentName - Name of the component, used for the property warning.
  53258. * @param {boolean} silent - Suppress warning messages.
  53259. */
  53260. module.exports.parseProperties = (function () {
  53261. var propNames = [];
  53262. return function (propData, schema, getPartialData, componentName, silent) {
  53263. var i;
  53264. var propName;
  53265. var propDefinition;
  53266. var propValue;
  53267. propNames.length = 0;
  53268. for (propName in (getPartialData ? propData : schema)) {
  53269. if (getPartialData && propData[propName] === undefined) { continue; }
  53270. propNames.push(propName);
  53271. }
  53272. if (propData === null || typeof propData !== 'object') { return propData; }
  53273. // Validation errors.
  53274. for (propName in propData) {
  53275. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  53276. warn('Unknown property `' + propName +
  53277. '` for component/system `' + componentName + '`.');
  53278. }
  53279. }
  53280. for (i = 0; i < propNames.length; i++) {
  53281. propName = propNames[i];
  53282. propDefinition = schema[propName];
  53283. propValue = propData[propName];
  53284. if (!(schema[propName])) { return; }
  53285. propData[propName] = parseProperty(propValue, propDefinition);
  53286. }
  53287. return propData;
  53288. };
  53289. })();
  53290. /**
  53291. * Deserialize a single property.
  53292. */
  53293. function parseProperty (value, propDefinition) {
  53294. // Use default value if value is falsy.
  53295. if (value === undefined || value === null || value === '') {
  53296. value = propDefinition.default;
  53297. if (Array.isArray(value)) { value = value.slice(); }
  53298. }
  53299. // Invoke property type parser.
  53300. return propDefinition.parse(value, propDefinition.default);
  53301. }
  53302. module.exports.parseProperty = parseProperty;
  53303. /**
  53304. * Serialize a group of properties.
  53305. */
  53306. module.exports.stringifyProperties = function (propData, schema) {
  53307. var propName;
  53308. var propDefinition;
  53309. var propValue;
  53310. var stringifiedData = {};
  53311. var value;
  53312. for (propName in propData) {
  53313. propDefinition = schema[propName];
  53314. propValue = propData[propName];
  53315. value = propValue;
  53316. if (typeof value === 'object') {
  53317. value = stringifyProperty(propValue, propDefinition);
  53318. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  53319. }
  53320. stringifiedData[propName] = value;
  53321. }
  53322. return stringifiedData;
  53323. };
  53324. /**
  53325. * Serialize a single property.
  53326. */
  53327. function stringifyProperty (value, propDefinition) {
  53328. // This function stringifies but it's used in a context where
  53329. // there's always second stringification pass. By returning the original
  53330. // value when it's not an object we save one unnecessary call
  53331. // to JSON.stringify.
  53332. if (typeof value !== 'object') { return value; }
  53333. // if there's no schema for the property we use standar JSON stringify
  53334. if (!propDefinition || value === null) { return JSON.stringify(value); }
  53335. return propDefinition.stringify(value);
  53336. }
  53337. module.exports.stringifyProperty = stringifyProperty;
  53338. },{"../utils/":197,"./propertyTypes":126}],134:[function(_dereq_,module,exports){
  53339. var schema = _dereq_('./schema');
  53340. var processSchema = schema.process;
  53341. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  53342. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  53343. var THREE = _dereq_('../lib/three');
  53344. var utils = _dereq_('../utils');
  53345. // A-Frame properties to three.js uniform types.
  53346. var propertyToThreeMapping = {
  53347. array: 'v3',
  53348. color: 'v3',
  53349. int: 'i',
  53350. number: 'f',
  53351. map: 't',
  53352. time: 'f',
  53353. vec2: 'v2',
  53354. vec3: 'v3',
  53355. vec4: 'v4'
  53356. };
  53357. /**
  53358. * Shader class definition.
  53359. *
  53360. * Shaders extend the material component API so you can create your own library
  53361. * of customized materials
  53362. *
  53363. */
  53364. var Shader = module.exports.Shader = function () {};
  53365. Shader.prototype = {
  53366. /**
  53367. * Contains the type schema and defaults for the data values.
  53368. * Data is coerced into the types of the values of the defaults.
  53369. */
  53370. schema: {},
  53371. vertexShader:
  53372. 'void main() {' +
  53373. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  53374. '}',
  53375. fragmentShader:
  53376. 'void main() {' +
  53377. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  53378. '}',
  53379. /**
  53380. * Init handler. Similar to attachedCallback.
  53381. * Called during shader initialization and is only run once.
  53382. */
  53383. init: function (data) {
  53384. this.attributes = this.initVariables(data, 'attribute');
  53385. this.uniforms = this.initVariables(data, 'uniform');
  53386. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  53387. // attributes: this.attributes,
  53388. uniforms: this.uniforms,
  53389. vertexShader: this.vertexShader,
  53390. fragmentShader: this.fragmentShader
  53391. });
  53392. return this.material;
  53393. },
  53394. initVariables: function (data, type) {
  53395. var key;
  53396. var schema = this.schema;
  53397. var variables = {};
  53398. var varType;
  53399. for (key in schema) {
  53400. if (schema[key].is !== type) { continue; }
  53401. varType = propertyToThreeMapping[schema[key].type];
  53402. variables[key] = {
  53403. type: varType,
  53404. value: undefined // Let updateVariables handle setting these.
  53405. };
  53406. }
  53407. return variables;
  53408. },
  53409. /**
  53410. * Update handler. Similar to attributeChangedCallback.
  53411. * Called whenever the associated material data changes.
  53412. *
  53413. * @param {object} data - New material data.
  53414. */
  53415. update: function (data) {
  53416. this.updateVariables(data, 'attribute');
  53417. this.updateVariables(data, 'uniform');
  53418. },
  53419. updateVariables: function (data, type) {
  53420. var key;
  53421. var materialKey;
  53422. var schema = this.schema;
  53423. var variables;
  53424. variables = type === 'uniform' ? this.uniforms : this.attributes;
  53425. for (key in data) {
  53426. if (!schema[key] || schema[key].is !== type) { continue; }
  53427. if (schema[key].type === 'map') {
  53428. // If data unchanged, get out early.
  53429. if (!variables[key] || variables[key].value === data[key]) { continue; }
  53430. // Special handling is needed for textures.
  53431. materialKey = '_texture_' + key;
  53432. // We can't actually set the variable correctly until we've loaded the texture.
  53433. this.setMapOnTextureLoad(variables, key, materialKey);
  53434. // Kick off the texture update now that handler is added.
  53435. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  53436. continue;
  53437. }
  53438. variables[key].value = this.parseValue(schema[key].type, data[key]);
  53439. variables[key].needsUpdate = true;
  53440. }
  53441. },
  53442. parseValue: function (type, value) {
  53443. var color;
  53444. switch (type) {
  53445. case 'vec2': {
  53446. return new THREE.Vector2(value.x, value.y);
  53447. }
  53448. case 'vec3': {
  53449. return new THREE.Vector3(value.x, value.y, value.z);
  53450. }
  53451. case 'vec4': {
  53452. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  53453. }
  53454. case 'color': {
  53455. color = new THREE.Color(value);
  53456. return new THREE.Vector3(color.r, color.g, color.b);
  53457. }
  53458. case 'map': {
  53459. return THREE.ImageUtils.loadTexture(value);
  53460. }
  53461. default: {
  53462. return value;
  53463. }
  53464. }
  53465. },
  53466. setMapOnTextureLoad: function (variables, key, materialKey) {
  53467. var self = this;
  53468. this.el.addEventListener('materialtextureloaded', function () {
  53469. variables[key].value = self.material[materialKey];
  53470. variables[key].needsUpdate = true;
  53471. });
  53472. }
  53473. };
  53474. /**
  53475. * Registers a shader to A-Frame.
  53476. *
  53477. * @param {string} name - shader name.
  53478. * @param {object} definition - shader property and methods.
  53479. * @returns {object} Shader.
  53480. */
  53481. module.exports.registerShader = function (name, definition) {
  53482. var NewShader;
  53483. var proto = {};
  53484. // Format definition object to prototype object.
  53485. Object.keys(definition).forEach(function (key) {
  53486. proto[key] = {
  53487. value: definition[key],
  53488. writable: true
  53489. };
  53490. });
  53491. if (shaders[name]) {
  53492. throw new Error('The shader ' + name + ' has been already registered');
  53493. }
  53494. NewShader = function () { Shader.call(this); };
  53495. NewShader.prototype = Object.create(Shader.prototype, proto);
  53496. NewShader.prototype.name = name;
  53497. NewShader.prototype.constructor = NewShader;
  53498. shaders[name] = {
  53499. Shader: NewShader,
  53500. schema: processSchema(NewShader.prototype.schema)
  53501. };
  53502. shaderNames.push(name);
  53503. return NewShader;
  53504. };
  53505. },{"../lib/three":172,"../utils":197,"./schema":133}],135:[function(_dereq_,module,exports){
  53506. var components = _dereq_('./component');
  53507. var schema = _dereq_('./schema');
  53508. var utils = _dereq_('../utils/');
  53509. var parseProperties = schema.parseProperties;
  53510. var parseProperty = schema.parseProperty;
  53511. var processSchema = schema.process;
  53512. var isSingleProp = schema.isSingleProperty;
  53513. var styleParser = utils.styleParser;
  53514. var systems = module.exports.systems = {}; // Keep track of registered systems.
  53515. /**
  53516. * System class definition.
  53517. *
  53518. * Systems provide global scope and services to a group of instantiated components of the
  53519. * same class. They can also help abstract logic away from components such that components
  53520. * only have to worry about data.
  53521. *
  53522. * For example, a physics component that creates a physics world that oversees
  53523. * all entities with a physics or rigid body component.
  53524. *
  53525. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  53526. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  53527. * setAttribute behavior).
  53528. *
  53529. * @member {string} name - Name that system is registered under.
  53530. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  53531. */
  53532. var System = module.exports.System = function (sceneEl) {
  53533. var component = components && components.components[this.name];
  53534. // Set reference to scene.
  53535. this.el = sceneEl;
  53536. this.sceneEl = sceneEl;
  53537. // Set reference to matching component (if exists).
  53538. if (component) { component.Component.prototype.system = this; }
  53539. // Process system configuration.
  53540. this.buildData();
  53541. this.init();
  53542. this.update({});
  53543. };
  53544. System.prototype = {
  53545. /**
  53546. * Schema to configure system.
  53547. */
  53548. schema: {},
  53549. /**
  53550. * Init handler. Called during scene initialization and is only run once.
  53551. * Systems can use this to set initial state.
  53552. */
  53553. init: function () { /* no-op */ },
  53554. /**
  53555. * Update handler. Called during scene attribute updates.
  53556. * Systems can use this to dynamically update their state.
  53557. */
  53558. update: function (oldData) { /* no-op */ },
  53559. /**
  53560. * Build data and call update handler.
  53561. *
  53562. * @private
  53563. */
  53564. updateProperties: function (rawData) {
  53565. var oldData = this.data;
  53566. if (!Object.keys(schema).length) { return; }
  53567. this.buildData(rawData);
  53568. this.update(oldData);
  53569. },
  53570. /**
  53571. * Parse data.
  53572. */
  53573. buildData: function (rawData) {
  53574. var schema = this.schema;
  53575. if (!Object.keys(schema).length) { return; }
  53576. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  53577. if (isSingleProp(schema)) {
  53578. this.data = parseProperty(rawData, schema);
  53579. } else {
  53580. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  53581. }
  53582. },
  53583. /**
  53584. * Tick handler.
  53585. * Called on each tick of the scene render loop.
  53586. * Affected by play and pause.
  53587. *
  53588. * @param {number} time - Scene tick time.
  53589. * @param {number} timeDelta - Difference in current render time and previous render time.
  53590. */
  53591. tick: undefined,
  53592. /**
  53593. * Tock handler.
  53594. * Called on each tock of the scene render loop.
  53595. * Affected by play and pause.
  53596. *
  53597. * @param {number} time - Scene tick time.
  53598. * @param {number} timeDelta - Difference in current render time and previous render time.
  53599. */
  53600. tock: undefined,
  53601. /**
  53602. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  53603. */
  53604. play: function () { /* no-op */ },
  53605. /**
  53606. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  53607. */
  53608. pause: function () { /* no-op */ }
  53609. };
  53610. /**
  53611. * Registers a system to A-Frame.
  53612. *
  53613. * @param {string} name - Component name.
  53614. * @param {object} definition - Component property and methods.
  53615. * @returns {object} Component.
  53616. */
  53617. module.exports.registerSystem = function (name, definition) {
  53618. var i;
  53619. var NewSystem;
  53620. var proto = {};
  53621. var scenes = utils.findAllScenes(document);
  53622. // Format definition object to prototype object.
  53623. Object.keys(definition).forEach(function (key) {
  53624. proto[key] = {
  53625. value: definition[key],
  53626. writable: true
  53627. };
  53628. });
  53629. if (systems[name]) {
  53630. throw new Error('The system `' + name + '` has been already registered. ' +
  53631. 'Check that you are not loading two versions of the same system ' +
  53632. 'or two different systems of the same name.');
  53633. }
  53634. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  53635. NewSystem.prototype = Object.create(System.prototype, proto);
  53636. NewSystem.prototype.name = name;
  53637. NewSystem.prototype.constructor = NewSystem;
  53638. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  53639. systems[name] = NewSystem;
  53640. // Initialize systems for existing scenes
  53641. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  53642. };
  53643. },{"../utils/":197,"./component":124,"./schema":133}],136:[function(_dereq_,module,exports){
  53644. _dereq_('./pivot');
  53645. },{"./pivot":137}],137:[function(_dereq_,module,exports){
  53646. var registerComponent = _dereq_('../../core/component').registerComponent;
  53647. var THREE = _dereq_('../../lib/three');
  53648. var originalPosition = new THREE.Vector3();
  53649. var originalRotation = new THREE.Vector3();
  53650. /**
  53651. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  53652. */
  53653. registerComponent('pivot', {
  53654. dependencies: ['position'],
  53655. schema: {type: 'vec3'},
  53656. init: function () {
  53657. var data = this.data;
  53658. var el = this.el;
  53659. var originalParent = el.object3D.parent;
  53660. var originalGroup = el.object3D;
  53661. var outerGroup = new THREE.Group();
  53662. originalPosition.copy(originalGroup.position);
  53663. originalRotation.copy(originalGroup.rotation);
  53664. // Detach current group from parent.
  53665. originalParent.remove(originalGroup);
  53666. outerGroup.add(originalGroup);
  53667. // Set new group as the outer group.
  53668. originalParent.add(outerGroup);
  53669. // Set outer group as new object3D.
  53670. el.object3D = outerGroup;
  53671. // Apply pivot to original group.
  53672. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  53673. // Offset the pivot so that world position not affected.
  53674. // And restore position onto outer group.
  53675. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  53676. data.z + originalPosition.z);
  53677. // Transfer rotation to outer group.
  53678. outerGroup.rotation.copy(originalGroup.rotation);
  53679. originalGroup.rotation.set(0, 0, 0);
  53680. }
  53681. });
  53682. },{"../../core/component":124,"../../lib/three":172}],138:[function(_dereq_,module,exports){
  53683. /**
  53684. * Common mesh defaults, mappings, and transforms.
  53685. */
  53686. var components = _dereq_('../../core/component').components;
  53687. var shaders = _dereq_('../../core/shader').shaders;
  53688. var utils = _dereq_('../../utils/');
  53689. var materialMappings = {};
  53690. Object.keys(components.material.schema).forEach(addMapping);
  53691. Object.keys(shaders.standard.schema).forEach(addMapping);
  53692. function addMapping (prop) {
  53693. // To hyphenated.
  53694. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53695. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  53696. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  53697. materialMappings[htmlAttrName] = 'material.' + prop;
  53698. }
  53699. module.exports = function getMeshMixin () {
  53700. return {
  53701. defaultComponents: {material: {}},
  53702. mappings: utils.extend({}, materialMappings)
  53703. };
  53704. };
  53705. },{"../../core/component":124,"../../core/shader":134,"../../utils/":197}],139:[function(_dereq_,module,exports){
  53706. _dereq_('./primitives/a-camera');
  53707. _dereq_('./primitives/a-cursor');
  53708. _dereq_('./primitives/a-curvedimage');
  53709. _dereq_('./primitives/a-gltf-model');
  53710. _dereq_('./primitives/a-image');
  53711. _dereq_('./primitives/a-light');
  53712. _dereq_('./primitives/a-link');
  53713. _dereq_('./primitives/a-obj-model');
  53714. _dereq_('./primitives/a-sky');
  53715. _dereq_('./primitives/a-sound');
  53716. _dereq_('./primitives/a-text');
  53717. _dereq_('./primitives/a-video');
  53718. _dereq_('./primitives/a-videosphere');
  53719. _dereq_('./primitives/meshPrimitives');
  53720. },{"./primitives/a-camera":141,"./primitives/a-cursor":142,"./primitives/a-curvedimage":143,"./primitives/a-gltf-model":144,"./primitives/a-image":145,"./primitives/a-light":146,"./primitives/a-link":147,"./primitives/a-obj-model":148,"./primitives/a-sky":149,"./primitives/a-sound":150,"./primitives/a-text":151,"./primitives/a-video":152,"./primitives/a-videosphere":153,"./primitives/meshPrimitives":154}],140:[function(_dereq_,module,exports){
  53721. var AEntity = _dereq_('../../core/a-entity');
  53722. var components = _dereq_('../../core/component').components;
  53723. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  53724. var utils = _dereq_('../../utils/');
  53725. var debug = utils.debug;
  53726. var setComponentProperty = utils.entity.setComponentProperty;
  53727. var log = debug('extras:primitives:debug');
  53728. var warn = debug('extras:primitives:warn');
  53729. var primitives = module.exports.primitives = {};
  53730. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  53731. name = name.toLowerCase();
  53732. log('Registering <%s>', name);
  53733. // Deprecation warning for defaultAttributes usage.
  53734. if (definition.defaultAttributes) {
  53735. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  53736. }
  53737. var primitive = registerElement(name, {
  53738. prototype: Object.create(AEntity.prototype, {
  53739. defaultComponentsFromPrimitive: {
  53740. value: definition.defaultComponents || definition.defaultAttributes || {}
  53741. },
  53742. deprecated: {value: definition.deprecated || null},
  53743. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  53744. mappings: {value: definition.mappings || {}},
  53745. createdCallback: {
  53746. value: function () {
  53747. if (definition.deprecated) { console.warn(definition.deprecated); }
  53748. this.resolveMappingCollisions();
  53749. }
  53750. },
  53751. /**
  53752. * If a mapping collides with a registered component name
  53753. * it renames the mapping to componentname-property
  53754. */
  53755. resolveMappingCollisions: {
  53756. value: function () {
  53757. var mappings = this.mappings;
  53758. var self = this;
  53759. Object.keys(mappings).forEach(function resolveCollision (key) {
  53760. var newAttribute;
  53761. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  53762. if (components[key]) {
  53763. newAttribute = mappings[key].replace('.', '-');
  53764. mappings[newAttribute] = mappings[key];
  53765. delete mappings[key];
  53766. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  53767. 'The attribute ' + key + ' has the same name as a registered component and' +
  53768. ' has been renamed to ' + newAttribute);
  53769. }
  53770. });
  53771. }
  53772. },
  53773. getExtraComponents: {
  53774. value: function () {
  53775. var attr;
  53776. var data;
  53777. var i;
  53778. var mapping;
  53779. var mixins;
  53780. var path;
  53781. var self = this;
  53782. // Gather component data from default components.
  53783. data = utils.clone(this.defaultComponentsFromPrimitive);
  53784. // Factor in mixins to overwrite default components.
  53785. mixins = this.getAttribute('mixin');
  53786. if (mixins) {
  53787. mixins = mixins.trim().split(' ');
  53788. mixins.forEach(function applyMixin (mixinId) {
  53789. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  53790. Object.keys(mixinComponents).forEach(function setComponent (name) {
  53791. data[name] = extend(data[name], mixinComponents[name]);
  53792. });
  53793. });
  53794. }
  53795. // Gather component data from mappings.
  53796. for (i = 0; i < this.attributes.length; i++) {
  53797. attr = this.attributes[i];
  53798. mapping = this.mappings[attr.name];
  53799. if (mapping) {
  53800. path = utils.entity.getComponentPropertyPath(mapping);
  53801. if (path.constructor === Array) {
  53802. data[path[0]] = data[path[0]] || {};
  53803. data[path[0]][path[1]] = attr.value.trim();
  53804. } else {
  53805. data[path] = attr.value.trim();
  53806. }
  53807. continue;
  53808. }
  53809. }
  53810. return data;
  53811. /**
  53812. * For the base to be extensible, both objects must be pure JavaScript objects.
  53813. * The function assumes that base is undefined, or null or a pure object.
  53814. */
  53815. function extend (base, extension) {
  53816. if (isUndefined(base)) {
  53817. return copy(extension);
  53818. }
  53819. if (isUndefined(extension)) {
  53820. return copy(base);
  53821. }
  53822. if (isPureObject(base) && isPureObject(extension)) {
  53823. return utils.extendDeep(base, extension);
  53824. }
  53825. return copy(extension);
  53826. }
  53827. function isUndefined (value) {
  53828. return typeof value === 'undefined';
  53829. }
  53830. function copy (value) {
  53831. if (isPureObject(value)) {
  53832. return utils.extendDeep({}, value);
  53833. }
  53834. return value;
  53835. }
  53836. function isPureObject (value) {
  53837. return value !== null && value.constructor === Object;
  53838. }
  53839. }
  53840. },
  53841. /**
  53842. * Sync to attribute to component property whenever mapped attribute changes.
  53843. * If attribute is mapped to a component property, set the component property using
  53844. * the attribute value.
  53845. */
  53846. attributeChangedCallback: {
  53847. value: function (attr, oldVal, value) {
  53848. var componentName = this.mappings[attr];
  53849. if (attr in this.deprecatedMappings) {
  53850. console.warn(this.deprecatedMappings[attr]);
  53851. }
  53852. if (!attr || !componentName) { return; }
  53853. // Set value.
  53854. setComponentProperty(this, componentName, value);
  53855. }
  53856. }
  53857. })
  53858. });
  53859. // Store.
  53860. primitives[name] = primitive;
  53861. return primitive;
  53862. };
  53863. /**
  53864. * Add component mappings using schema.
  53865. */
  53866. function addComponentMapping (componentName, mappings) {
  53867. var schema = components[componentName].schema;
  53868. Object.keys(schema).map(function (prop) {
  53869. // Hyphenate where there is camelCase.
  53870. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53871. // If there is a mapping collision, prefix with component name and hyphen.
  53872. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  53873. mappings[attrName] = componentName + '.' + prop;
  53874. });
  53875. }
  53876. /**
  53877. * Helper to define a primitive, building mappings using a component schema.
  53878. */
  53879. function definePrimitive (tagName, defaultComponents, mappings) {
  53880. // If no initial mappings provided, start from empty map.
  53881. mappings = mappings || {};
  53882. // From the default components, add mapping automagically.
  53883. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  53884. addComponentMapping(componentName, mappings);
  53885. });
  53886. // Register the primitive.
  53887. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  53888. defaultComponents: defaultComponents,
  53889. mappings: mappings
  53890. }));
  53891. }
  53892. module.exports.definePrimitive = definePrimitive;
  53893. },{"../../core/a-entity":120,"../../core/a-register-element":123,"../../core/component":124,"../../utils/":197}],141:[function(_dereq_,module,exports){
  53894. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53895. registerPrimitive('a-camera', {
  53896. defaultComponents: {
  53897. 'camera': {},
  53898. 'look-controls': {},
  53899. 'wasd-controls': {},
  53900. 'position': {x: 0, y: 1.6, z: 0}
  53901. },
  53902. mappings: {
  53903. active: 'camera.active',
  53904. far: 'camera.far',
  53905. fov: 'camera.fov',
  53906. 'look-controls-enabled': 'look-controls.enabled',
  53907. near: 'camera.near',
  53908. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  53909. 'wasd-controls-enabled': 'wasd-controls.enabled',
  53910. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  53911. zoom: 'camera.zoom'
  53912. }
  53913. });
  53914. },{"../primitives":140}],142:[function(_dereq_,module,exports){
  53915. var getMeshMixin = _dereq_('../getMeshMixin');
  53916. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53917. var utils = _dereq_('../../../utils/');
  53918. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  53919. defaultComponents: {
  53920. cursor: {},
  53921. geometry: {
  53922. primitive: 'ring',
  53923. radiusOuter: 0.016,
  53924. radiusInner: 0.01,
  53925. segmentsTheta: 32
  53926. },
  53927. material: {
  53928. color: '#000',
  53929. shader: 'flat',
  53930. opacity: 0.8
  53931. },
  53932. position: {
  53933. x: 0,
  53934. y: 0,
  53935. z: -1
  53936. }
  53937. },
  53938. mappings: {
  53939. far: 'raycaster.far',
  53940. fuse: 'cursor.fuse',
  53941. 'fuse-timeout': 'cursor.fuseTimeout',
  53942. interval: 'raycaster.interval',
  53943. objects: 'raycaster.objects'
  53944. }
  53945. }));
  53946. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],143:[function(_dereq_,module,exports){
  53947. var getMeshMixin = _dereq_('../getMeshMixin');
  53948. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53949. var utils = _dereq_('../../../utils/');
  53950. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  53951. defaultComponents: {
  53952. geometry: {
  53953. height: 1,
  53954. primitive: 'cylinder',
  53955. radius: 2,
  53956. segmentsRadial: 48,
  53957. thetaLength: 270,
  53958. openEnded: true,
  53959. thetaStart: 0
  53960. },
  53961. material: {
  53962. color: '#FFF',
  53963. shader: 'flat',
  53964. side: 'double',
  53965. transparent: true,
  53966. repeat: '-1 1'
  53967. }
  53968. },
  53969. mappings: {
  53970. height: 'geometry.height',
  53971. 'open-ended': 'geometry.openEnded',
  53972. radius: 'geometry.radius',
  53973. segments: 'geometry.segmentsRadial',
  53974. start: 'geometry.thetaStart',
  53975. 'theta-length': 'geometry.thetaLength',
  53976. 'theta-start': 'geometry.thetaStart',
  53977. 'width': 'geometry.thetaLength'
  53978. }
  53979. }));
  53980. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],144:[function(_dereq_,module,exports){
  53981. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53982. registerPrimitive('a-gltf-model', {
  53983. mappings: {
  53984. src: 'gltf-model'
  53985. }
  53986. });
  53987. },{"../primitives":140}],145:[function(_dereq_,module,exports){
  53988. var getMeshMixin = _dereq_('../getMeshMixin');
  53989. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53990. var utils = _dereq_('../../../utils/');
  53991. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  53992. defaultComponents: {
  53993. geometry: {
  53994. primitive: 'plane'
  53995. },
  53996. material: {
  53997. color: '#FFF',
  53998. shader: 'flat',
  53999. side: 'double',
  54000. transparent: true
  54001. }
  54002. },
  54003. mappings: {
  54004. height: 'geometry.height',
  54005. width: 'geometry.width'
  54006. }
  54007. }));
  54008. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],146:[function(_dereq_,module,exports){
  54009. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54010. registerPrimitive('a-light', {
  54011. defaultComponents: {
  54012. light: {}
  54013. },
  54014. mappings: {
  54015. angle: 'light.angle',
  54016. color: 'light.color',
  54017. 'ground-color': 'light.groundColor',
  54018. decay: 'light.decay',
  54019. distance: 'light.distance',
  54020. intensity: 'light.intensity',
  54021. penumbra: 'light.penumbra',
  54022. type: 'light.type',
  54023. target: 'light.target'
  54024. }
  54025. });
  54026. },{"../primitives":140}],147:[function(_dereq_,module,exports){
  54027. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54028. registerPrimitive('a-link', {
  54029. defaultComponents: {
  54030. link: {
  54031. visualAspectEnabled: true
  54032. }
  54033. },
  54034. mappings: {
  54035. href: 'link.href',
  54036. image: 'link.image',
  54037. title: 'link.title'
  54038. }
  54039. });
  54040. },{"../primitives":140}],148:[function(_dereq_,module,exports){
  54041. var meshMixin = _dereq_('../getMeshMixin')();
  54042. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54043. var utils = _dereq_('../../../utils/');
  54044. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  54045. defaultComponents: {
  54046. 'obj-model': {}
  54047. },
  54048. mappings: {
  54049. src: 'obj-model.obj',
  54050. mtl: 'obj-model.mtl'
  54051. }
  54052. }));
  54053. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],149:[function(_dereq_,module,exports){
  54054. var getMeshMixin = _dereq_('../getMeshMixin');
  54055. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54056. var utils = _dereq_('../../../utils/');
  54057. var meshPrimitives = _dereq_('./meshPrimitives');
  54058. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  54059. defaultComponents: {
  54060. geometry: {
  54061. primitive: 'sphere',
  54062. radius: 5000,
  54063. segmentsWidth: 64,
  54064. segmentsHeight: 32
  54065. },
  54066. material: {
  54067. color: '#FFF',
  54068. side: 'back',
  54069. shader: 'flat',
  54070. npot: true
  54071. },
  54072. scale: '-1 1 1'
  54073. },
  54074. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  54075. }));
  54076. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140,"./meshPrimitives":154}],150:[function(_dereq_,module,exports){
  54077. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54078. registerPrimitive('a-sound', {
  54079. defaultComponents: {
  54080. sound: {}
  54081. },
  54082. mappings: {
  54083. src: 'sound.src',
  54084. on: 'sound.on',
  54085. autoplay: 'sound.autoplay',
  54086. loop: 'sound.loop',
  54087. volume: 'sound.volume'
  54088. }
  54089. });
  54090. },{"../primitives":140}],151:[function(_dereq_,module,exports){
  54091. // <a-text> using `definePrimitive` helper.
  54092. var definePrimitive = _dereq_('../primitives').definePrimitive;
  54093. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  54094. },{"../primitives":140}],152:[function(_dereq_,module,exports){
  54095. var getMeshMixin = _dereq_('../getMeshMixin');
  54096. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54097. var utils = _dereq_('../../../utils/');
  54098. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  54099. defaultComponents: {
  54100. geometry: {
  54101. primitive: 'plane'
  54102. },
  54103. material: {
  54104. color: '#FFF',
  54105. shader: 'flat',
  54106. side: 'double',
  54107. transparent: true
  54108. }
  54109. },
  54110. mappings: {
  54111. height: 'geometry.height',
  54112. width: 'geometry.width'
  54113. }
  54114. }));
  54115. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],153:[function(_dereq_,module,exports){
  54116. var getMeshMixin = _dereq_('../getMeshMixin');
  54117. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54118. var utils = _dereq_('../../../utils/');
  54119. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  54120. defaultComponents: {
  54121. geometry: {
  54122. primitive: 'sphere',
  54123. radius: 5000,
  54124. segmentsWidth: 64,
  54125. segmentsHeight: 32
  54126. },
  54127. material: {
  54128. color: '#FFF',
  54129. shader: 'flat',
  54130. side: 'back',
  54131. npot: true
  54132. },
  54133. scale: '-1 1 1'
  54134. },
  54135. mappings: {
  54136. radius: 'geometry.radius',
  54137. 'segments-height': 'geometry.segmentsHeight',
  54138. 'segments-width': 'geometry.segmentsWidth'
  54139. }
  54140. }));
  54141. },{"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],154:[function(_dereq_,module,exports){
  54142. /**
  54143. * Automated mesh primitive registration.
  54144. */
  54145. var getMeshMixin = _dereq_('../getMeshMixin');
  54146. var geometries = _dereq_('../../../core/geometry').geometries;
  54147. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  54148. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  54149. var utils = _dereq_('../../../utils/');
  54150. // For testing.
  54151. var meshPrimitives = module.exports = {};
  54152. // Generate primitive for each geometry type.
  54153. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  54154. var geometry = geometries[geometryName];
  54155. var geometryHyphened = unCamelCase(geometryName);
  54156. // Generate mappings.
  54157. var mappings = {};
  54158. Object.keys(geometry.schema).forEach(function createMapping (property) {
  54159. mappings[unCamelCase(property)] = 'geometry.' + property;
  54160. });
  54161. // Register.
  54162. var tagName = 'a-' + geometryHyphened;
  54163. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  54164. defaultComponents: {geometry: {primitive: geometryName}},
  54165. mappings: mappings
  54166. }));
  54167. meshPrimitives[tagName] = primitive;
  54168. });
  54169. /**
  54170. * camelCase to hyphened-string.
  54171. */
  54172. function unCamelCase (str) {
  54173. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  54174. }
  54175. },{"../../../core/geometry":125,"../../../utils/":197,"../getMeshMixin":138,"../primitives":140}],155:[function(_dereq_,module,exports){
  54176. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54177. var THREE = _dereq_('../lib/three');
  54178. registerGeometry('box', {
  54179. schema: {
  54180. depth: {default: 1, min: 0},
  54181. height: {default: 1, min: 0},
  54182. width: {default: 1, min: 0},
  54183. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  54184. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  54185. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  54186. },
  54187. init: function (data) {
  54188. this.geometry = new THREE.BoxGeometry(
  54189. data.width, data.height, data.depth,
  54190. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  54191. }
  54192. });
  54193. },{"../core/geometry":125,"../lib/three":172}],156:[function(_dereq_,module,exports){
  54194. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54195. var THREE = _dereq_('../lib/three');
  54196. var degToRad = THREE.Math.degToRad;
  54197. registerGeometry('circle', {
  54198. schema: {
  54199. radius: {default: 1, min: 0},
  54200. segments: {default: 32, min: 3, type: 'int'},
  54201. thetaLength: {default: 360, min: 0},
  54202. thetaStart: {default: 0}
  54203. },
  54204. init: function (data) {
  54205. this.geometry = new THREE.CircleGeometry(
  54206. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  54207. }
  54208. });
  54209. },{"../core/geometry":125,"../lib/three":172}],157:[function(_dereq_,module,exports){
  54210. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54211. var THREE = _dereq_('../lib/three');
  54212. var degToRad = THREE.Math.degToRad;
  54213. registerGeometry('cone', {
  54214. schema: {
  54215. height: {default: 1, min: 0},
  54216. openEnded: {default: false},
  54217. radiusBottom: {default: 1, min: 0},
  54218. radiusTop: {default: 0.01, min: 0},
  54219. segmentsHeight: {default: 18, min: 1, type: 'int'},
  54220. segmentsRadial: {default: 36, min: 3, type: 'int'},
  54221. thetaLength: {default: 360, min: 0},
  54222. thetaStart: {default: 0}
  54223. },
  54224. init: function (data) {
  54225. this.geometry = new THREE.CylinderGeometry(
  54226. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  54227. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  54228. degToRad(data.thetaLength));
  54229. }
  54230. });
  54231. },{"../core/geometry":125,"../lib/three":172}],158:[function(_dereq_,module,exports){
  54232. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54233. var THREE = _dereq_('../lib/three');
  54234. var degToRad = THREE.Math.degToRad;
  54235. registerGeometry('cylinder', {
  54236. schema: {
  54237. height: {default: 1, min: 0},
  54238. openEnded: {default: false},
  54239. radius: {default: 1, min: 0},
  54240. segmentsHeight: {default: 18, min: 1, type: 'int'},
  54241. segmentsRadial: {default: 36, min: 3, type: 'int'},
  54242. thetaLength: {default: 360, min: 0},
  54243. thetaStart: {default: 0}
  54244. },
  54245. init: function (data) {
  54246. this.geometry = new THREE.CylinderGeometry(
  54247. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  54248. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  54249. }
  54250. });
  54251. },{"../core/geometry":125,"../lib/three":172}],159:[function(_dereq_,module,exports){
  54252. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54253. var THREE = _dereq_('../lib/three');
  54254. registerGeometry('dodecahedron', {
  54255. schema: {
  54256. detail: {default: 0, min: 0, max: 5, type: 'int'},
  54257. radius: {default: 1, min: 0}
  54258. },
  54259. init: function (data) {
  54260. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  54261. }
  54262. });
  54263. },{"../core/geometry":125,"../lib/three":172}],160:[function(_dereq_,module,exports){
  54264. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54265. var THREE = _dereq_('../lib/three');
  54266. registerGeometry('icosahedron', {
  54267. schema: {
  54268. detail: {default: 0, min: 0, max: 5, type: 'int'},
  54269. radius: {default: 1, min: 0}
  54270. },
  54271. init: function (data) {
  54272. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  54273. }
  54274. });
  54275. },{"../core/geometry":125,"../lib/three":172}],161:[function(_dereq_,module,exports){
  54276. _dereq_('./box.js');
  54277. _dereq_('./circle.js');
  54278. _dereq_('./cone.js');
  54279. _dereq_('./cylinder.js');
  54280. _dereq_('./dodecahedron.js');
  54281. _dereq_('./icosahedron.js');
  54282. _dereq_('./octahedron.js');
  54283. _dereq_('./plane.js');
  54284. _dereq_('./ring.js');
  54285. _dereq_('./sphere.js');
  54286. _dereq_('./tetrahedron.js');
  54287. _dereq_('./torus.js');
  54288. _dereq_('./torusKnot.js');
  54289. _dereq_('./triangle.js');
  54290. },{"./box.js":155,"./circle.js":156,"./cone.js":157,"./cylinder.js":158,"./dodecahedron.js":159,"./icosahedron.js":160,"./octahedron.js":162,"./plane.js":163,"./ring.js":164,"./sphere.js":165,"./tetrahedron.js":166,"./torus.js":167,"./torusKnot.js":168,"./triangle.js":169}],162:[function(_dereq_,module,exports){
  54291. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54292. var THREE = _dereq_('../lib/three');
  54293. registerGeometry('octahedron', {
  54294. schema: {
  54295. detail: {default: 0, min: 0, max: 5, type: 'int'},
  54296. radius: {default: 1, min: 0}
  54297. },
  54298. init: function (data) {
  54299. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  54300. }
  54301. });
  54302. },{"../core/geometry":125,"../lib/three":172}],163:[function(_dereq_,module,exports){
  54303. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54304. var THREE = _dereq_('../lib/three');
  54305. registerGeometry('plane', {
  54306. schema: {
  54307. height: {default: 1, min: 0},
  54308. width: {default: 1, min: 0},
  54309. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  54310. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  54311. },
  54312. init: function (data) {
  54313. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  54314. }
  54315. });
  54316. },{"../core/geometry":125,"../lib/three":172}],164:[function(_dereq_,module,exports){
  54317. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54318. var THREE = _dereq_('../lib/three');
  54319. var degToRad = THREE.Math.degToRad;
  54320. registerGeometry('ring', {
  54321. schema: {
  54322. radiusInner: {default: 0.8, min: 0},
  54323. radiusOuter: {default: 1.2, min: 0},
  54324. segmentsPhi: {default: 10, min: 1, type: 'int'},
  54325. segmentsTheta: {default: 32, min: 3, type: 'int'},
  54326. thetaLength: {default: 360, min: 0},
  54327. thetaStart: {default: 0}
  54328. },
  54329. init: function (data) {
  54330. this.geometry = new THREE.RingGeometry(
  54331. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  54332. degToRad(data.thetaStart), degToRad(data.thetaLength));
  54333. }
  54334. });
  54335. },{"../core/geometry":125,"../lib/three":172}],165:[function(_dereq_,module,exports){
  54336. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54337. var THREE = _dereq_('../lib/three');
  54338. var degToRad = THREE.Math.degToRad;
  54339. registerGeometry('sphere', {
  54340. schema: {
  54341. radius: {default: 1, min: 0},
  54342. phiLength: {default: 360},
  54343. phiStart: {default: 0, min: 0},
  54344. thetaLength: {default: 180, min: 0},
  54345. thetaStart: {default: 0},
  54346. segmentsHeight: {default: 18, min: 2, type: 'int'},
  54347. segmentsWidth: {default: 36, min: 3, type: 'int'}
  54348. },
  54349. init: function (data) {
  54350. this.geometry = new THREE.SphereGeometry(
  54351. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  54352. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  54353. }
  54354. });
  54355. },{"../core/geometry":125,"../lib/three":172}],166:[function(_dereq_,module,exports){
  54356. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54357. var THREE = _dereq_('../lib/three');
  54358. registerGeometry('tetrahedron', {
  54359. schema: {
  54360. detail: {default: 0, min: 0, max: 5, type: 'int'},
  54361. radius: {default: 1, min: 0}
  54362. },
  54363. init: function (data) {
  54364. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  54365. }
  54366. });
  54367. },{"../core/geometry":125,"../lib/three":172}],167:[function(_dereq_,module,exports){
  54368. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54369. var THREE = _dereq_('../lib/three');
  54370. var degToRad = THREE.Math.degToRad;
  54371. registerGeometry('torus', {
  54372. schema: {
  54373. arc: {default: 360},
  54374. radius: {default: 1, min: 0},
  54375. radiusTubular: {default: 0.2, min: 0},
  54376. segmentsRadial: {default: 36, min: 2, type: 'int'},
  54377. segmentsTubular: {default: 32, min: 3, type: 'int'}
  54378. },
  54379. init: function (data) {
  54380. this.geometry = new THREE.TorusGeometry(
  54381. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  54382. degToRad(data.arc));
  54383. }
  54384. });
  54385. },{"../core/geometry":125,"../lib/three":172}],168:[function(_dereq_,module,exports){
  54386. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54387. var THREE = _dereq_('../lib/three');
  54388. registerGeometry('torusKnot', {
  54389. schema: {
  54390. p: {default: 2, min: 1},
  54391. q: {default: 3, min: 1},
  54392. radius: {default: 1, min: 0},
  54393. radiusTubular: {default: 0.2, min: 0},
  54394. segmentsRadial: {default: 8, min: 3, type: 'int'},
  54395. segmentsTubular: {default: 100, min: 3, type: 'int'}
  54396. },
  54397. init: function (data) {
  54398. this.geometry = new THREE.TorusKnotGeometry(
  54399. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  54400. data.p, data.q);
  54401. }
  54402. });
  54403. },{"../core/geometry":125,"../lib/three":172}],169:[function(_dereq_,module,exports){
  54404. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54405. var THREE = _dereq_('../lib/three');
  54406. var quaternion = new THREE.Quaternion();
  54407. var rotateVector = new THREE.Vector3(0, 0, 1);
  54408. var uvMinVector = new THREE.Vector2();
  54409. var uvMaxVector = new THREE.Vector2();
  54410. var uvScaleVector = new THREE.Vector2();
  54411. registerGeometry('triangle', {
  54412. schema: {
  54413. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  54414. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  54415. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  54416. },
  54417. init: function (data) {
  54418. var geometry;
  54419. var normal;
  54420. var triangle;
  54421. var uvA;
  54422. var uvB;
  54423. var uvC;
  54424. triangle = new THREE.Triangle();
  54425. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  54426. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  54427. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  54428. normal = triangle.getNormal(new THREE.Vector3());
  54429. // Rotate the 3D triangle to be parallel to XY plane.
  54430. quaternion.setFromUnitVectors(normal, rotateVector);
  54431. uvA = triangle.a.clone().applyQuaternion(quaternion);
  54432. uvB = triangle.b.clone().applyQuaternion(quaternion);
  54433. uvC = triangle.c.clone().applyQuaternion(quaternion);
  54434. // Compute UVs.
  54435. // Normalize x/y values of UV so they are within 0 to 1.
  54436. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  54437. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  54438. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  54439. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  54440. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  54441. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  54442. geometry = this.geometry = new THREE.Geometry();
  54443. geometry.vertices.push(triangle.a);
  54444. geometry.vertices.push(triangle.b);
  54445. geometry.vertices.push(triangle.c);
  54446. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  54447. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  54448. }
  54449. });
  54450. },{"../core/geometry":125,"../lib/three":172}],170:[function(_dereq_,module,exports){
  54451. // Polyfill `Promise`.
  54452. window.Promise = window.Promise || _dereq_('promise-polyfill');
  54453. // WebVR polyfill
  54454. // Check before the polyfill runs.
  54455. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  54456. !!window.navigator.getVRDevices;
  54457. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  54458. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  54459. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  54460. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  54461. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  54462. // Only for iOS on versions older than 10.
  54463. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  54464. var WebVRPolyfill = _dereq_('webvr-polyfill');
  54465. var polyfillConfig = {
  54466. BUFFER_SCALE: bufferScale,
  54467. CARDBOARD_UI_DISABLED: true,
  54468. ROTATE_INSTRUCTIONS_DISABLED: true
  54469. };
  54470. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  54471. }
  54472. var utils = _dereq_('./utils/');
  54473. var debug = utils.debug;
  54474. if (utils.isIE11) {
  54475. // Polyfill `CustomEvent`.
  54476. _dereq_('custom-event-polyfill');
  54477. // Polyfill String.startsWith.
  54478. _dereq_('../vendor/starts-with-polyfill');
  54479. }
  54480. var error = debug('A-Frame:error');
  54481. var warn = debug('A-Frame:warn');
  54482. if (window.document.currentScript && window.document.currentScript.parentNode !==
  54483. window.document.head && !window.debug) {
  54484. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  54485. 'ensure everything for A-Frame is properly registered before they are used from ' +
  54486. 'HTML.');
  54487. }
  54488. // Error if not using a server.
  54489. if (window.location.protocol === 'file:') {
  54490. error(
  54491. 'This HTML file is currently being served via the file:// protocol. ' +
  54492. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  54493. 'Please use a local or hosted server: ' +
  54494. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  54495. }
  54496. _dereq_('present'); // Polyfill `performance.now()`.
  54497. // CSS.
  54498. if (utils.device.isBrowserEnvironment) {
  54499. _dereq_('./style/aframe.css');
  54500. _dereq_('./style/rStats.css');
  54501. }
  54502. // Required before `AEntity` so that all components are registered.
  54503. var AScene = _dereq_('./core/scene/a-scene').AScene;
  54504. var components = _dereq_('./core/component').components;
  54505. var registerComponent = _dereq_('./core/component').registerComponent;
  54506. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  54507. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  54508. var registerShader = _dereq_('./core/shader').registerShader;
  54509. var registerSystem = _dereq_('./core/system').registerSystem;
  54510. var shaders = _dereq_('./core/shader').shaders;
  54511. var systems = _dereq_('./core/system').systems;
  54512. // Exports THREE to window so three.js can be used without alteration.
  54513. var THREE = window.THREE = _dereq_('./lib/three');
  54514. var pkg = _dereq_('../package');
  54515. _dereq_('./components/index'); // Register standard components.
  54516. _dereq_('./geometries/index'); // Register standard geometries.
  54517. _dereq_('./shaders/index'); // Register standard shaders.
  54518. _dereq_('./systems/index'); // Register standard systems.
  54519. var ANode = _dereq_('./core/a-node');
  54520. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  54521. _dereq_('./core/a-assets');
  54522. _dereq_('./core/a-cubemap');
  54523. _dereq_('./core/a-mixin');
  54524. // Extras.
  54525. _dereq_('./extras/components/');
  54526. _dereq_('./extras/primitives/');
  54527. console.log('A-Frame Version: 0.9.2 (Date 2019-09-29, Commit #41547f59)');
  54528. console.log('three Version (https://github.com/supermedium/three.js):',
  54529. pkg.dependencies['super-three']);
  54530. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  54531. module.exports = window.AFRAME = {
  54532. AComponent: _dereq_('./core/component').Component,
  54533. AEntity: AEntity,
  54534. ANode: ANode,
  54535. ANIME: _dereq_('super-animejs'),
  54536. AScene: AScene,
  54537. components: components,
  54538. coreComponents: Object.keys(components),
  54539. geometries: _dereq_('./core/geometry').geometries,
  54540. registerComponent: registerComponent,
  54541. registerElement: _dereq_('./core/a-register-element').registerElement,
  54542. registerGeometry: registerGeometry,
  54543. registerPrimitive: registerPrimitive,
  54544. registerShader: registerShader,
  54545. registerSystem: registerSystem,
  54546. primitives: {
  54547. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  54548. primitives: _dereq_('./extras/primitives/primitives').primitives
  54549. },
  54550. scenes: _dereq_('./core/scene/scenes'),
  54551. schema: _dereq_('./core/schema'),
  54552. shaders: shaders,
  54553. systems: systems,
  54554. THREE: THREE,
  54555. utils: utils,
  54556. version: pkg.version
  54557. };
  54558. },{"../package":72,"../vendor/starts-with-polyfill":208,"./components/index":81,"./core/a-assets":118,"./core/a-cubemap":119,"./core/a-entity":120,"./core/a-mixin":121,"./core/a-node":122,"./core/a-register-element":123,"./core/component":124,"./core/geometry":125,"./core/scene/a-scene":127,"./core/scene/scenes":131,"./core/schema":133,"./core/shader":134,"./core/system":135,"./extras/components/":136,"./extras/primitives/":139,"./extras/primitives/getMeshMixin":138,"./extras/primitives/primitives":140,"./geometries/index":161,"./lib/three":172,"./shaders/index":174,"./style/aframe.css":179,"./style/rStats.css":180,"./systems/index":184,"./utils/":197,"./utils/isIOSOlderThan10":199,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":67}],171:[function(_dereq_,module,exports){
  54559. window.aframeStats = function (scene) {
  54560. var _rS = null;
  54561. var _scene = scene;
  54562. var _values = {
  54563. te: {
  54564. caption: 'Entities'
  54565. },
  54566. lt: {
  54567. caption: 'Load Time'
  54568. }
  54569. };
  54570. var _groups = [ {
  54571. caption: 'A-Frame',
  54572. values: [ 'te', 'lt' ]
  54573. } ];
  54574. function _update () {
  54575. _rS('te').set(getEntityCount());
  54576. if (window.performance.getEntriesByName) {
  54577. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  54578. }
  54579. }
  54580. function getEntityCount () {
  54581. var elements = _scene.querySelectorAll('*');
  54582. Array.prototype.slice.call(elements).filter(function (el) {
  54583. return el.isEntity;
  54584. });
  54585. return elements.length;
  54586. }
  54587. function _start () {}
  54588. function _end () {}
  54589. function _attach (r) {
  54590. _rS = r;
  54591. }
  54592. return {
  54593. update: _update,
  54594. start: _start,
  54595. end: _end,
  54596. attach: _attach,
  54597. values: _values,
  54598. groups: _groups,
  54599. fractions: []
  54600. };
  54601. };
  54602. if (typeof module === 'object') {
  54603. module.exports = {
  54604. aframeStats: window.aframeStats
  54605. };
  54606. }
  54607. },{}],172:[function(_dereq_,module,exports){
  54608. (function (global){
  54609. var THREE = global.THREE = _dereq_('super-three');
  54610. // Allow cross-origin images to be loaded.
  54611. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  54612. // Must be on `THREE.TextureLoader`.
  54613. if (THREE.TextureLoader) {
  54614. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  54615. }
  54616. // This is for images loaded from the model loaders.
  54617. if (THREE.ImageLoader) {
  54618. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  54619. }
  54620. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  54621. if (THREE.Cache) {
  54622. THREE.Cache.enabled = true;
  54623. }
  54624. // TODO: Eventually include these only if they are needed by a component.
  54625. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  54626. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  54627. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  54628. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  54629. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  54630. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  54631. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  54632. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  54633. module.exports = THREE;
  54634. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  54635. },{"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}],173:[function(_dereq_,module,exports){
  54636. var registerShader = _dereq_('../core/shader').registerShader;
  54637. var THREE = _dereq_('../lib/three');
  54638. var utils = _dereq_('../utils/');
  54639. /**
  54640. * Flat shader using THREE.MeshBasicMaterial.
  54641. */
  54642. module.exports.Shader = registerShader('flat', {
  54643. schema: {
  54644. color: {type: 'color'},
  54645. fog: {default: true},
  54646. height: {default: 256},
  54647. offset: {type: 'vec2', default: {x: 0, y: 0}},
  54648. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  54649. src: {type: 'map'},
  54650. width: {default: 512},
  54651. wireframe: {default: false},
  54652. wireframeLinewidth: {default: 2}
  54653. },
  54654. /**
  54655. * Initializes the shader.
  54656. * Adds a reference from the scene to this entity as the camera.
  54657. */
  54658. init: function (data) {
  54659. this.rendererSystem = this.el.sceneEl.systems.renderer;
  54660. this.materialData = {color: new THREE.Color()};
  54661. this.textureSrc = null;
  54662. getMaterialData(data, this.materialData);
  54663. this.rendererSystem.applyColorCorrection(this.materialData.color);
  54664. this.material = new THREE.MeshBasicMaterial(this.materialData);
  54665. utils.material.updateMap(this, data);
  54666. },
  54667. update: function (data) {
  54668. this.updateMaterial(data);
  54669. utils.material.updateMap(this, data);
  54670. },
  54671. /**
  54672. * Updating existing material.
  54673. *
  54674. * @param {object} data - Material component data.
  54675. */
  54676. updateMaterial: function (data) {
  54677. var key;
  54678. getMaterialData(data, this.materialData);
  54679. this.rendererSystem.applyColorCorrection(this.materialData.color);
  54680. for (key in this.materialData) {
  54681. this.material[key] = this.materialData[key];
  54682. }
  54683. }
  54684. });
  54685. /**
  54686. * Builds and normalize material data, normalizing stuff along the way.
  54687. *
  54688. * @param {object} data - Material data.
  54689. * @param {object} materialData - Object to reuse.
  54690. * @returns {object} Updated material data.
  54691. */
  54692. function getMaterialData (data, materialData) {
  54693. materialData.color.set(data.color);
  54694. materialData.fog = data.fog;
  54695. materialData.wireframe = data.wireframe;
  54696. materialData.wireframeLinewidth = data.wireframeLinewidth;
  54697. return materialData;
  54698. }
  54699. },{"../core/shader":134,"../lib/three":172,"../utils/":197}],174:[function(_dereq_,module,exports){
  54700. _dereq_('./flat');
  54701. _dereq_('./standard');
  54702. _dereq_('./sdf');
  54703. _dereq_('./msdf');
  54704. _dereq_('./ios10hls');
  54705. },{"./flat":173,"./ios10hls":175,"./msdf":176,"./sdf":177,"./standard":178}],175:[function(_dereq_,module,exports){
  54706. var registerShader = _dereq_('../core/shader').registerShader;
  54707. /**
  54708. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  54709. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  54710. */
  54711. module.exports.Shader = registerShader('ios10hls', {
  54712. schema: {
  54713. src: {type: 'map', is: 'uniform'},
  54714. opacity: {type: 'number', is: 'uniform', default: 1}
  54715. },
  54716. vertexShader: [
  54717. 'varying vec2 vUV;',
  54718. 'void main(void) {',
  54719. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54720. ' vUV = uv;',
  54721. '}'
  54722. ].join('\n'),
  54723. fragmentShader: [
  54724. 'uniform sampler2D src;',
  54725. 'uniform float opacity;',
  54726. 'varying vec2 vUV;',
  54727. 'void main() {',
  54728. ' vec2 offset = vec2(0, 0);',
  54729. ' vec2 repeat = vec2(1, 1);',
  54730. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  54731. ' gl_FragColor = vec4(color.rgb, opacity);',
  54732. '}'
  54733. ].join('\n')
  54734. });
  54735. },{"../core/shader":134}],176:[function(_dereq_,module,exports){
  54736. var registerShader = _dereq_('../core/shader').registerShader;
  54737. /**
  54738. * Multi-channel signed distance field.
  54739. * Used by text component.
  54740. */
  54741. module.exports.Shader = registerShader('msdf', {
  54742. schema: {
  54743. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  54744. color: {type: 'color', is: 'uniform', default: 'white'},
  54745. map: {type: 'map', is: 'uniform'},
  54746. negate: {type: 'boolean', is: 'uniform', default: true},
  54747. opacity: {type: 'number', is: 'uniform', default: 1.0}
  54748. },
  54749. raw: true,
  54750. vertexShader: [
  54751. 'attribute vec2 uv;',
  54752. 'attribute vec3 position;',
  54753. 'uniform mat4 projectionMatrix;',
  54754. 'uniform mat4 modelViewMatrix;',
  54755. 'varying vec2 vUV;',
  54756. 'void main(void) {',
  54757. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54758. ' vUV = uv;',
  54759. '}'
  54760. ].join('\n'),
  54761. fragmentShader: [
  54762. '#ifdef GL_OES_standard_derivatives',
  54763. '#extension GL_OES_standard_derivatives: enable',
  54764. '#endif',
  54765. 'precision highp float;',
  54766. 'uniform bool negate;',
  54767. 'uniform float alphaTest;',
  54768. 'uniform float opacity;',
  54769. 'uniform sampler2D map;',
  54770. 'uniform vec3 color;',
  54771. 'varying vec2 vUV;',
  54772. 'float median(float r, float g, float b) {',
  54773. ' return max(min(r, g), min(max(r, g), b));',
  54774. '}',
  54775. // FIXME: Experimentally determined constants.
  54776. '#define BIG_ENOUGH 0.001',
  54777. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  54778. 'void main() {',
  54779. ' vec3 sample = texture2D(map, vUV).rgb;',
  54780. ' if (negate) { sample = 1.0 - sample; }',
  54781. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  54782. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  54783. ' float dscale = 0.353505;',
  54784. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  54785. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  54786. // When texel is too small, blend raw alpha value rather than supersampling.
  54787. // FIXME: Experimentally determined constant.
  54788. ' // Do modified alpha test.',
  54789. ' if (isBigEnough > BIG_ENOUGH) {',
  54790. ' float ratio = BIG_ENOUGH / isBigEnough;',
  54791. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  54792. ' }',
  54793. ' // Do modified alpha test.',
  54794. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  54795. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  54796. '}'
  54797. ].join('\n')
  54798. });
  54799. },{"../core/shader":134}],177:[function(_dereq_,module,exports){
  54800. var registerShader = _dereq_('../core/shader').registerShader;
  54801. /**
  54802. * Signed distance field.
  54803. * Used by text component.
  54804. */
  54805. module.exports.Shader = registerShader('sdf', {
  54806. schema: {
  54807. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  54808. color: {type: 'color', is: 'uniform', default: 'white'},
  54809. map: {type: 'map', is: 'uniform'},
  54810. opacity: {type: 'number', is: 'uniform', default: 1.0}
  54811. },
  54812. raw: true,
  54813. vertexShader: [
  54814. 'attribute vec2 uv;',
  54815. 'attribute vec3 position;',
  54816. 'uniform mat4 projectionMatrix;',
  54817. 'uniform mat4 modelViewMatrix;',
  54818. 'varying vec2 vUV;',
  54819. 'void main(void) {',
  54820. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54821. ' vUV = uv;',
  54822. '}'
  54823. ].join('\n'),
  54824. fragmentShader: [
  54825. '#ifdef GL_OES_standard_derivatives',
  54826. '#extension GL_OES_standard_derivatives: enable',
  54827. '#endif',
  54828. 'precision highp float;',
  54829. 'uniform float alphaTest;',
  54830. 'uniform float opacity;',
  54831. 'uniform sampler2D map;',
  54832. 'uniform vec3 color;',
  54833. 'varying vec2 vUV;',
  54834. '#ifdef GL_OES_standard_derivatives',
  54835. ' float contour(float width, float value) {',
  54836. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  54837. ' }',
  54838. '#else',
  54839. ' float aastep(float value, float afwidth) {',
  54840. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  54841. ' }',
  54842. '#endif',
  54843. // FIXME: Experimentally determined constants.
  54844. '#define BIG_ENOUGH 0.001',
  54845. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  54846. '#define ALL_SMOOTH 0.4',
  54847. '#define ALL_ROUGH 0.02',
  54848. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  54849. 'void main() {',
  54850. // When we have derivatives and can get texel size for supersampling.
  54851. ' #ifdef GL_OES_standard_derivatives',
  54852. ' vec2 uv = vUV;',
  54853. ' vec4 texColor = texture2D(map, uv);',
  54854. ' float dist = texColor.a;',
  54855. ' float width = fwidth(dist);',
  54856. ' float alpha = contour(dist, width);',
  54857. ' float dscale = 0.353505;',
  54858. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  54859. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  54860. // When texel is too small, blend raw alpha value rather than supersampling.
  54861. // FIXME: experimentally determined constant
  54862. ' if (isBigEnough > BIG_ENOUGH) {',
  54863. ' float ratio = BIG_ENOUGH / isBigEnough;',
  54864. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  54865. ' }',
  54866. // Otherwise do weighted supersampling.
  54867. // FIXME: why this weighting?
  54868. ' if (isBigEnough <= BIG_ENOUGH) {',
  54869. ' vec4 box = vec4 (uv - duv, uv + duv);',
  54870. ' alpha = (alpha + 0.5 * (',
  54871. ' contour(texture2D(map, box.xy).a, width)',
  54872. ' + contour(texture2D(map, box.zw).a, width)',
  54873. ' + contour(texture2D(map, box.xw).a, width)',
  54874. ' + contour(texture2D(map, box.zy).a, width)',
  54875. ' )) / 3.0;',
  54876. ' }',
  54877. // Do modified alpha test.
  54878. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  54879. ' #else',
  54880. // When we don't have derivatives, use approximations.
  54881. ' vec4 texColor = texture2D(map, vUV);',
  54882. ' float value = texColor.a;',
  54883. // FIXME: if we understood font pixel dimensions, this could probably be improved
  54884. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  54885. ' float alpha = aastep(value, afwidth);',
  54886. // Use gl_FragCoord.w to guess when we should blend.
  54887. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  54888. ' 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);',
  54889. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  54890. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  54891. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  54892. ' #endif',
  54893. ' gl_FragColor = vec4(color, opacity * alpha);',
  54894. '}'
  54895. ].join('\n')
  54896. });
  54897. },{"../core/shader":134}],178:[function(_dereq_,module,exports){
  54898. var registerShader = _dereq_('../core/shader').registerShader;
  54899. var THREE = _dereq_('../lib/three');
  54900. var utils = _dereq_('../utils/');
  54901. var CubeLoader = new THREE.CubeTextureLoader();
  54902. var texturePromises = {};
  54903. /**
  54904. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  54905. */
  54906. module.exports.Shader = registerShader('standard', {
  54907. schema: {
  54908. ambientOcclusionMap: {type: 'map'},
  54909. ambientOcclusionMapIntensity: {default: 1},
  54910. ambientOcclusionTextureOffset: {type: 'vec2'},
  54911. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54912. color: {type: 'color'},
  54913. displacementMap: {type: 'map'},
  54914. displacementScale: {default: 1},
  54915. displacementBias: {default: 0.5},
  54916. displacementTextureOffset: {type: 'vec2'},
  54917. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54918. emissive: {type: 'color', default: '#000'},
  54919. emissiveIntensity: {default: 1},
  54920. envMap: {default: ''},
  54921. fog: {default: true},
  54922. height: {default: 256},
  54923. metalness: {default: 0.0, min: 0.0, max: 1.0},
  54924. metalnessMap: {type: 'map'},
  54925. metalnessTextureOffset: {type: 'vec2'},
  54926. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54927. normalMap: {type: 'map'},
  54928. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  54929. normalTextureOffset: {type: 'vec2'},
  54930. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54931. offset: {type: 'vec2', default: {x: 0, y: 0}},
  54932. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  54933. roughness: {default: 0.5, min: 0.0, max: 1.0},
  54934. roughnessMap: {type: 'map'},
  54935. roughnessTextureOffset: {type: 'vec2'},
  54936. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54937. sphericalEnvMap: {type: 'map'},
  54938. src: {type: 'map'},
  54939. width: {default: 512},
  54940. wireframe: {default: false},
  54941. wireframeLinewidth: {default: 2}
  54942. },
  54943. /**
  54944. * Initializes the shader.
  54945. * Adds a reference from the scene to this entity as the camera.
  54946. */
  54947. init: function (data) {
  54948. this.rendererSystem = this.el.sceneEl.systems.renderer;
  54949. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  54950. getMaterialData(data, this.materialData);
  54951. this.rendererSystem.applyColorCorrection(this.materialData.color);
  54952. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  54953. this.material = new THREE.MeshStandardMaterial(this.materialData);
  54954. utils.material.updateMap(this, data);
  54955. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54956. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54957. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54958. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  54959. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  54960. this.updateEnvMap(data);
  54961. },
  54962. update: function (data) {
  54963. this.updateMaterial(data);
  54964. utils.material.updateMap(this, data);
  54965. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54966. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54967. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54968. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  54969. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  54970. this.updateEnvMap(data);
  54971. },
  54972. /**
  54973. * Updating existing material.
  54974. *
  54975. * @param {object} data - Material component data.
  54976. * @returns {object} Material.
  54977. */
  54978. updateMaterial: function (data) {
  54979. var key;
  54980. var material = this.material;
  54981. getMaterialData(data, this.materialData);
  54982. this.rendererSystem.applyColorCorrection(this.materialData.color);
  54983. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  54984. for (key in this.materialData) {
  54985. material[key] = this.materialData[key];
  54986. }
  54987. },
  54988. /**
  54989. * Handle environment cubemap. Textures are cached in texturePromises.
  54990. */
  54991. updateEnvMap: function (data) {
  54992. var self = this;
  54993. var material = this.material;
  54994. var envMap = data.envMap;
  54995. var sphericalEnvMap = data.sphericalEnvMap;
  54996. // No envMap defined or already loading.
  54997. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  54998. material.envMap = null;
  54999. material.needsUpdate = true;
  55000. return;
  55001. }
  55002. this.isLoadingEnvMap = true;
  55003. // if a spherical env map is defined then use it.
  55004. if (sphericalEnvMap) {
  55005. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  55006. self.isLoadingEnvMap = false;
  55007. texture.mapping = THREE.SphericalReflectionMapping;
  55008. material.envMap = texture;
  55009. utils.material.handleTextureEvents(self.el, texture);
  55010. material.needsUpdate = true;
  55011. });
  55012. return;
  55013. }
  55014. // Another material is already loading this texture. Wait on promise.
  55015. if (texturePromises[envMap]) {
  55016. texturePromises[envMap].then(function (cube) {
  55017. self.isLoadingEnvMap = false;
  55018. material.envMap = cube;
  55019. utils.material.handleTextureEvents(self.el, cube);
  55020. material.needsUpdate = true;
  55021. });
  55022. return;
  55023. }
  55024. // Material is first to load this texture. Load and resolve texture.
  55025. texturePromises[envMap] = new Promise(function (resolve) {
  55026. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  55027. CubeLoader.load(urls, function (cube) {
  55028. // Texture loaded.
  55029. self.isLoadingEnvMap = false;
  55030. material.envMap = cube;
  55031. utils.material.handleTextureEvents(self.el, cube);
  55032. resolve(cube);
  55033. });
  55034. });
  55035. });
  55036. }
  55037. });
  55038. /**
  55039. * Builds and normalize material data, normalizing stuff along the way.
  55040. *
  55041. * @param {object} data - Material data.
  55042. * @param {object} materialData - Object to use.
  55043. * @returns {object} Updated materialData.
  55044. */
  55045. function getMaterialData (data, materialData) {
  55046. materialData.color.set(data.color);
  55047. materialData.emissive.set(data.emissive);
  55048. materialData.emissiveIntensity = data.emissiveIntensity;
  55049. materialData.fog = data.fog;
  55050. materialData.metalness = data.metalness;
  55051. materialData.roughness = data.roughness;
  55052. materialData.wireframe = data.wireframe;
  55053. materialData.wireframeLinewidth = data.wireframeLinewidth;
  55054. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  55055. if (data.ambientOcclusionMap) {
  55056. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  55057. }
  55058. if (data.displacementMap) {
  55059. materialData.displacementScale = data.displacementScale;
  55060. materialData.displacementBias = data.displacementBias;
  55061. }
  55062. return materialData;
  55063. }
  55064. },{"../core/shader":134,"../lib/three":172,"../utils/":197}],179:[function(_dereq_,module,exports){
  55065. 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-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-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-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff}.a-enter-vr-button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20245.82%20141.73%22%3E%3Cdefs%3E%3Cstyle%3E.a%7Bfill%3A%23fff%3Bfill-rule%3Aevenodd%3B%7D%3C%2Fstyle%3E%3C%2Fdefs%3E%3Ctitle%3Emask%3C%2Ftitle%3E%3Cpath%20class%3D%22a%22%20d%3D%22M175.56%2C111.37c-22.52%2C0-40.77-18.84-40.77-42.07S153%2C27.24%2C175.56%2C27.24s40.77%2C18.84%2C40.77%2C42.07S198.08%2C111.37%2C175.56%2C111.37ZM26.84%2C69.31c0-23.23%2C18.25-42.07%2C40.77-42.07s40.77%2C18.84%2C40.77%2C42.07-18.26%2C42.07-40.77%2C42.07S26.84%2C92.54%2C26.84%2C69.31ZM27.27%2C0C11.54%2C0%2C0%2C12.34%2C0%2C28.58V110.9c0%2C16.24%2C11.54%2C30.83%2C27.27%2C30.83H99.57c2.17%2C0%2C4.19-1.83%2C5.4-3.7L116.47%2C118a8%2C8%2C0%2C0%2C1%2C12.52-.18l11.51%2C20.34c1.2%2C1.86%2C3.22%2C3.61%2C5.39%2C3.61h72.29c15.74%2C0%2C27.63-14.6%2C27.63-30.83V28.58C245.82%2C12.34%2C233.93%2C0%2C218.19%2C0H27.27Z%22%2F%3E%3C%2Fsvg%3E) 50% 50%/70% 70% no-repeat rgba(0,0,0,.35);border:0;bottom:0;cursor:pointer;min-width:50px;min-height:30px;padding-right:5%;padding-top:4%;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999}.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#666}[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}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  55066. },{"browserify-css":4}],180:[function(_dereq_,module,exports){
  55067. 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;
  55068. },{"browserify-css":4}],181:[function(_dereq_,module,exports){
  55069. var constants = _dereq_('../constants/');
  55070. var registerSystem = _dereq_('../core/system').registerSystem;
  55071. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  55072. /**
  55073. * Camera system. Manages which camera is active among multiple cameras in scene.
  55074. *
  55075. * @member {object} activeCameraEl - Active camera entity.
  55076. */
  55077. module.exports.System = registerSystem('camera', {
  55078. init: function () {
  55079. this.activeCameraEl = null;
  55080. this.render = this.render.bind(this);
  55081. this.unwrapRender = this.unwrapRender.bind(this);
  55082. this.wrapRender = this.wrapRender.bind(this);
  55083. this.initialCameraFound = false;
  55084. this.numUserCameras = 0;
  55085. this.numUserCamerasChecked = 0;
  55086. this.setupInitialCamera();
  55087. },
  55088. /**
  55089. * Setup initial camera, either searching for camera or
  55090. * creating a default camera if user has not added one during the initial scene traversal.
  55091. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  55092. * loads.
  55093. *
  55094. * Default camera offset height is at average eye level (~1.6m).
  55095. */
  55096. setupInitialCamera: function () {
  55097. var cameraEls;
  55098. var i;
  55099. var sceneEl = this.sceneEl;
  55100. var self = this;
  55101. // Camera already defined or the one defined it is an spectator one.
  55102. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  55103. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  55104. return;
  55105. }
  55106. // Search for initial user-defined camera.
  55107. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  55108. // No user cameras, create default one.
  55109. if (!cameraEls.length) {
  55110. this.createDefaultCamera();
  55111. return;
  55112. }
  55113. this.numUserCameras = cameraEls.length;
  55114. for (i = 0; i < cameraEls.length; i++) {
  55115. cameraEls[i].addEventListener('object3dset', function (evt) {
  55116. if (evt.detail.type !== 'camera') { return; }
  55117. self.checkUserCamera(this);
  55118. });
  55119. // Load camera and wait for camera to initialize.
  55120. if (cameraEls[i].isNode) {
  55121. cameraEls[i].load();
  55122. } else {
  55123. cameraEls[i].addEventListener('nodeready', function () {
  55124. this.load();
  55125. });
  55126. }
  55127. }
  55128. },
  55129. /**
  55130. * Check if a user-defined camera entity is appropriate to be initial camera.
  55131. * (active + non-spectator).
  55132. *
  55133. * Keep track of the number of cameras we checked and whether we found one.
  55134. */
  55135. checkUserCamera: function (cameraEl) {
  55136. var cameraData;
  55137. var sceneEl = this.el.sceneEl;
  55138. this.numUserCamerasChecked++;
  55139. // Already found one.
  55140. if (this.initialCameraFound) { return; }
  55141. // Check if camera is appropriate for being the initial camera.
  55142. cameraData = cameraEl.getAttribute('camera');
  55143. if (!cameraData.active || cameraData.spectator) {
  55144. // No user cameras eligible, create default camera.
  55145. if (this.numUserCamerasChecked === this.numUserCameras) {
  55146. this.createDefaultCamera();
  55147. }
  55148. return;
  55149. }
  55150. this.initialCameraFound = true;
  55151. sceneEl.camera = cameraEl.getObject3D('camera');
  55152. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  55153. },
  55154. createDefaultCamera: function () {
  55155. var defaultCameraEl;
  55156. var sceneEl = this.sceneEl;
  55157. // Set up default camera.
  55158. defaultCameraEl = document.createElement('a-entity');
  55159. defaultCameraEl.setAttribute('camera', {active: true});
  55160. defaultCameraEl.setAttribute('position', {
  55161. x: 0,
  55162. y: constants.DEFAULT_CAMERA_HEIGHT,
  55163. z: 0
  55164. });
  55165. defaultCameraEl.setAttribute('wasd-controls', '');
  55166. defaultCameraEl.setAttribute('look-controls', '');
  55167. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  55168. defaultCameraEl.addEventListener('object3dset', function (evt) {
  55169. if (evt.detail.type !== 'camera') { return; }
  55170. sceneEl.camera = evt.detail.object;
  55171. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  55172. });
  55173. sceneEl.appendChild(defaultCameraEl);
  55174. },
  55175. /**
  55176. * Set a different active camera.
  55177. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  55178. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  55179. * the new camera.
  55180. */
  55181. disableActiveCamera: function () {
  55182. var cameraEls;
  55183. var newActiveCameraEl;
  55184. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  55185. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  55186. newActiveCameraEl.setAttribute('camera', 'active', true);
  55187. },
  55188. /**
  55189. * Set active camera to be used by renderer.
  55190. * Removes the default camera (if present).
  55191. * Disables all other cameras in the scene.
  55192. *
  55193. * @param {Element} newCameraEl - Entity with camera component.
  55194. */
  55195. setActiveCamera: function (newCameraEl) {
  55196. var cameraEl;
  55197. var cameraEls;
  55198. var i;
  55199. var newCamera;
  55200. var previousCamera = this.activeCameraEl;
  55201. var sceneEl = this.sceneEl;
  55202. // Same camera.
  55203. newCamera = newCameraEl.getObject3D('camera');
  55204. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  55205. // Grab the default camera.
  55206. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  55207. var defaultCameraEl = defaultCameraWrapper &&
  55208. defaultCameraWrapper.querySelector('[camera]');
  55209. // Remove default camera if new camera is not the default camera.
  55210. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  55211. // Make new camera active.
  55212. this.activeCameraEl = newCameraEl;
  55213. this.activeCameraEl.play();
  55214. sceneEl.camera = newCamera;
  55215. // Disable current camera
  55216. if (previousCamera) {
  55217. previousCamera.setAttribute('camera', 'active', false);
  55218. }
  55219. // Disable other cameras in the scene
  55220. cameraEls = sceneEl.querySelectorAll('[camera]');
  55221. for (i = 0; i < cameraEls.length; i++) {
  55222. cameraEl = cameraEls[i];
  55223. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  55224. cameraEl.setAttribute('camera', 'active', false);
  55225. cameraEl.pause();
  55226. }
  55227. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  55228. },
  55229. /**
  55230. * Set spectator camera to render the scene on a 2D display.
  55231. *
  55232. * @param {Element} newCameraEl - Entity with camera component.
  55233. */
  55234. setSpectatorCamera: function (newCameraEl) {
  55235. var newCamera;
  55236. var previousCamera = this.spectatorCameraEl;
  55237. var sceneEl = this.sceneEl;
  55238. var spectatorCameraEl;
  55239. // Same camera.
  55240. newCamera = newCameraEl.getObject3D('camera');
  55241. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  55242. // Disable current camera
  55243. if (previousCamera) {
  55244. previousCamera.setAttribute('camera', 'spectator', false);
  55245. }
  55246. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  55247. sceneEl.addEventListener('enter-vr', this.wrapRender);
  55248. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  55249. spectatorCameraEl.setAttribute('camera', 'active', false);
  55250. spectatorCameraEl.play();
  55251. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  55252. },
  55253. /**
  55254. * Disables current spectator camera.
  55255. */
  55256. disableSpectatorCamera: function () {
  55257. this.spectatorCameraEl = undefined;
  55258. },
  55259. /**
  55260. * Wrap the render method of the renderer to render
  55261. * the spectator camera after vrDisplay.submitFrame.
  55262. */
  55263. wrapRender: function () {
  55264. if (!this.spectatorCameraEl) { return; }
  55265. this.originalRender = this.sceneEl.renderer.render;
  55266. this.sceneEl.renderer.render = this.render;
  55267. },
  55268. unwrapRender: function () {
  55269. if (!this.originalRender) { return; }
  55270. this.sceneEl.renderer.render = this.originalRender;
  55271. this.originalRender = undefined;
  55272. },
  55273. render: function (scene, camera) {
  55274. var isVREnabled;
  55275. var sceneEl = this.sceneEl;
  55276. var spectatorCamera;
  55277. isVREnabled = sceneEl.renderer.vr.enabled;
  55278. this.originalRender.call(sceneEl.renderer, scene, camera);
  55279. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  55280. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  55281. sceneEl.renderer.vr.enabled = false;
  55282. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  55283. sceneEl.renderer.vr.enabled = isVREnabled;
  55284. }
  55285. });
  55286. /**
  55287. * Remove injected default camera from scene, if present.
  55288. *
  55289. * @param {Element} sceneEl
  55290. */
  55291. function removeDefaultCamera (sceneEl) {
  55292. var defaultCamera;
  55293. var camera = sceneEl.camera;
  55294. if (!camera) { return; }
  55295. // Remove default camera if present.
  55296. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  55297. if (!defaultCamera) { return; }
  55298. sceneEl.removeChild(defaultCamera);
  55299. }
  55300. },{"../constants/":116,"../core/system":135}],182:[function(_dereq_,module,exports){
  55301. var geometries = _dereq_('../core/geometry').geometries;
  55302. var registerSystem = _dereq_('../core/system').registerSystem;
  55303. var THREE = _dereq_('../lib/three');
  55304. /**
  55305. * System for geometry component.
  55306. * Handle geometry caching.
  55307. *
  55308. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  55309. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  55310. * know whether to dispose on removal.
  55311. */
  55312. module.exports.System = registerSystem('geometry', {
  55313. init: function () {
  55314. this.cache = {};
  55315. this.cacheCount = {};
  55316. },
  55317. /**
  55318. * Reset cache. Mainly for testing.
  55319. */
  55320. clearCache: function () {
  55321. this.cache = {};
  55322. this.cacheCount = {};
  55323. },
  55324. /**
  55325. * Attempt to retrieve from cache.
  55326. *
  55327. * @returns {Object|null} A geometry if it exists, else null.
  55328. */
  55329. getOrCreateGeometry: function (data) {
  55330. var cache = this.cache;
  55331. var cachedGeometry;
  55332. var hash;
  55333. // Skip all caching logic.
  55334. if (data.skipCache) { return createGeometry(data); }
  55335. // Try to retrieve from cache first.
  55336. hash = this.hash(data);
  55337. cachedGeometry = cache[hash];
  55338. incrementCacheCount(this.cacheCount, hash);
  55339. if (cachedGeometry) { return cachedGeometry; }
  55340. // Create geometry.
  55341. cachedGeometry = createGeometry(data);
  55342. // Cache and return geometry.
  55343. cache[hash] = cachedGeometry;
  55344. return cachedGeometry;
  55345. },
  55346. /**
  55347. * Let system know that an entity is no longer using a geometry.
  55348. */
  55349. unuseGeometry: function (data) {
  55350. var cache = this.cache;
  55351. var cacheCount = this.cacheCount;
  55352. var geometry;
  55353. var hash;
  55354. if (data.skipCache) { return; }
  55355. hash = this.hash(data);
  55356. if (!cache[hash]) { return; }
  55357. decrementCacheCount(cacheCount, hash);
  55358. // Another entity is still using this geometry. No need to do anything.
  55359. if (cacheCount[hash] > 0) { return; }
  55360. // No more entities are using this geometry. Dispose.
  55361. geometry = cache[hash];
  55362. geometry.dispose();
  55363. delete cache[hash];
  55364. delete cacheCount[hash];
  55365. },
  55366. /**
  55367. * Use JSON.stringify to turn component data into hash.
  55368. * Should be deterministic within a single browser engine.
  55369. * If not, then look into json-stable-stringify.
  55370. */
  55371. hash: function (data) {
  55372. return JSON.stringify(data);
  55373. }
  55374. });
  55375. /**
  55376. * Create geometry using component data.
  55377. *
  55378. * @param {object} data - Component data.
  55379. * @returns {object} Geometry.
  55380. */
  55381. function createGeometry (data) {
  55382. var geometryType = data.primitive;
  55383. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  55384. var geometryInstance = new GeometryClass();
  55385. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  55386. geometryInstance.init(data);
  55387. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  55388. }
  55389. /**
  55390. * Decreate count of entity using a geometry.
  55391. */
  55392. function decrementCacheCount (cacheCount, hash) {
  55393. cacheCount[hash]--;
  55394. }
  55395. /**
  55396. * Increase count of entity using a geometry.
  55397. */
  55398. function incrementCacheCount (cacheCount, hash) {
  55399. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  55400. }
  55401. /**
  55402. * Transform geometry to BufferGeometry if `doBuffer`.
  55403. *
  55404. * @param {object} geometry
  55405. * @param {boolean} doBuffer
  55406. * @returns {object} Geometry.
  55407. */
  55408. function toBufferGeometry (geometry, doBuffer) {
  55409. var bufferGeometry;
  55410. if (!doBuffer) { return geometry; }
  55411. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  55412. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  55413. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  55414. return bufferGeometry;
  55415. }
  55416. },{"../core/geometry":125,"../core/system":135,"../lib/three":172}],183:[function(_dereq_,module,exports){
  55417. var registerSystem = _dereq_('../core/system').registerSystem;
  55418. var THREE = _dereq_('../lib/three');
  55419. /**
  55420. * glTF model system.
  55421. *
  55422. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  55423. * provided externally.
  55424. *
  55425. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  55426. */
  55427. module.exports.System = registerSystem('gltf-model', {
  55428. schema: {
  55429. dracoDecoderPath: {default: ''}
  55430. },
  55431. init: function () {
  55432. var path = this.data.dracoDecoderPath;
  55433. this.dracoLoader = new THREE.DRACOLoader();
  55434. this.dracoLoader.setDecoderPath(path);
  55435. },
  55436. update: function () {
  55437. var path;
  55438. if (this.dracoLoader) { return; }
  55439. path = this.data.dracoDecoderPath;
  55440. this.dracoLoader = new THREE.DRACOLoader();
  55441. this.dracoLoader.setDecoderPath(path);
  55442. },
  55443. getDRACOLoader: function () {
  55444. return this.dracoLoader;
  55445. }
  55446. });
  55447. },{"../core/system":135,"../lib/three":172}],184:[function(_dereq_,module,exports){
  55448. _dereq_('./camera');
  55449. _dereq_('./geometry');
  55450. _dereq_('./gltf-model');
  55451. _dereq_('./light');
  55452. _dereq_('./material');
  55453. _dereq_('./renderer');
  55454. _dereq_('./shadow');
  55455. _dereq_('./tracked-controls-webvr');
  55456. _dereq_('./tracked-controls-webxr');
  55457. },{"./camera":181,"./geometry":182,"./gltf-model":183,"./light":185,"./material":186,"./renderer":187,"./shadow":188,"./tracked-controls-webvr":189,"./tracked-controls-webxr":190}],185:[function(_dereq_,module,exports){
  55458. var registerSystem = _dereq_('../core/system').registerSystem;
  55459. var bind = _dereq_('../utils/bind');
  55460. var constants = _dereq_('../constants/');
  55461. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  55462. /**
  55463. * Light system.
  55464. *
  55465. * Prescribes default lighting if not specified (one ambient, one directional).
  55466. * Removes default lighting from the scene when a new light is added.
  55467. *
  55468. * @param {bool} defaultLights - Whether default lighting are defined.
  55469. * @param {bool} userDefinedLights - Whether user lighting is defined.
  55470. */
  55471. module.exports.System = registerSystem('light', {
  55472. schema: {
  55473. defaultLightsEnabled: {default: true}
  55474. },
  55475. init: function () {
  55476. this.defaultLights = false;
  55477. this.userDefinedLights = false;
  55478. // Wait for all entities to fully load before checking for existence of lights.
  55479. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  55480. // will do so asynchronously.
  55481. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  55482. },
  55483. /**
  55484. * Notify scene that light has been added and to remove the default.
  55485. *
  55486. * @param {object} el - element holding the light component.
  55487. */
  55488. registerLight: function (el) {
  55489. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  55490. // User added a light, remove default lights through DOM.
  55491. this.removeDefaultLights();
  55492. this.userDefinedLights = true;
  55493. }
  55494. },
  55495. removeDefaultLights: function () {
  55496. var defaultLights;
  55497. var sceneEl = this.sceneEl;
  55498. if (!this.defaultLights) { return; }
  55499. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  55500. for (var i = 0; i < defaultLights.length; i++) {
  55501. sceneEl.removeChild(defaultLights[i]);
  55502. }
  55503. this.defaultLights = false;
  55504. },
  55505. /**
  55506. * Prescibe default lights to the scene.
  55507. * Does so by injecting markup such that this state is not invisible.
  55508. * These lights are removed if the user adds any lights.
  55509. */
  55510. setupDefaultLights: function () {
  55511. var sceneEl = this.sceneEl;
  55512. var ambientLight;
  55513. var directionalLight;
  55514. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  55515. return;
  55516. }
  55517. ambientLight = document.createElement('a-entity');
  55518. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  55519. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  55520. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  55521. sceneEl.appendChild(ambientLight);
  55522. directionalLight = document.createElement('a-entity');
  55523. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  55524. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  55525. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  55526. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  55527. sceneEl.appendChild(directionalLight);
  55528. this.defaultLights = true;
  55529. }
  55530. });
  55531. },{"../constants/":116,"../core/system":135,"../utils/bind":191}],186:[function(_dereq_,module,exports){
  55532. var registerSystem = _dereq_('../core/system').registerSystem;
  55533. var THREE = _dereq_('../lib/three');
  55534. var utils = _dereq_('../utils/');
  55535. var isHLS = _dereq_('../utils/material').isHLS;
  55536. var bind = utils.bind;
  55537. var debug = utils.debug;
  55538. var error = debug('components:texture:error');
  55539. var TextureLoader = new THREE.TextureLoader();
  55540. var warn = debug('components:texture:warn');
  55541. TextureLoader.setCrossOrigin('anonymous');
  55542. /**
  55543. * System for material component.
  55544. * Handle material registration, updates (for fog), and texture caching.
  55545. *
  55546. * @member {object} materials - Registered materials.
  55547. * @member {object} textureCounts - Number of times each texture is used. Tracked
  55548. * separately from textureCache, because the cache (1) is populated in
  55549. * multiple places, and (2) may be cleared at any time.
  55550. * @member {object} textureCache - Texture cache for:
  55551. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  55552. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  55553. */
  55554. module.exports.System = registerSystem('material', {
  55555. init: function () {
  55556. this.materials = {};
  55557. this.textureCounts = {};
  55558. this.textureCache = {};
  55559. this.sceneEl.addEventListener(
  55560. 'materialtextureloaded',
  55561. bind(this.onMaterialTextureLoaded, this)
  55562. );
  55563. },
  55564. clearTextureCache: function () {
  55565. this.textureCache = {};
  55566. },
  55567. /**
  55568. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  55569. *
  55570. * @param {string, or element} src - Texture URL or element.
  55571. * @param {string} data - Relevant texture data used for caching.
  55572. * @param {function} cb - Callback to pass texture to.
  55573. */
  55574. loadTexture: function (src, data, cb) {
  55575. var self = this;
  55576. // Canvas.
  55577. if (src.tagName === 'CANVAS') {
  55578. this.loadCanvas(src, data, cb);
  55579. return;
  55580. }
  55581. // Video element.
  55582. if (src.tagName === 'VIDEO') {
  55583. if (!src.src && !src.srcObject && !src.childElementCount) {
  55584. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  55585. }
  55586. this.loadVideo(src, data, cb);
  55587. return;
  55588. }
  55589. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  55590. function loadImageCb (src) { self.loadImage(src, data, cb); }
  55591. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  55592. },
  55593. /**
  55594. * High-level function for loading image textures (THREE.Texture).
  55595. *
  55596. * @param {Element|string} src - Texture source.
  55597. * @param {object} data - Texture data.
  55598. * @param {function} cb - Callback to pass texture to.
  55599. */
  55600. loadImage: function (src, data, handleImageTextureLoaded) {
  55601. var hash = this.hash(data);
  55602. var textureCache = this.textureCache;
  55603. // Texture already being loaded or already loaded. Wait on promise.
  55604. if (textureCache[hash]) {
  55605. textureCache[hash].then(handleImageTextureLoaded);
  55606. return;
  55607. }
  55608. // Texture not yet being loaded. Start loading it.
  55609. textureCache[hash] = loadImageTexture(src, data);
  55610. textureCache[hash].then(handleImageTextureLoaded);
  55611. },
  55612. /**
  55613. * High-level function for loading canvas textures (THREE.Texture).
  55614. *
  55615. * @param {Element|string} src - Texture source.
  55616. * @param {object} data - Texture data.
  55617. * @param {function} cb - Callback to pass texture to.
  55618. */
  55619. loadCanvas: function (src, data, cb) {
  55620. var texture;
  55621. texture = new THREE.CanvasTexture(src);
  55622. setTextureProperties(texture, data);
  55623. cb(texture);
  55624. },
  55625. /**
  55626. * Load video texture (THREE.VideoTexture).
  55627. * Which is just an image texture that RAFs + needsUpdate.
  55628. * Note that creating a video texture is synchronous unlike loading an image texture.
  55629. * Made asynchronous to be consistent with image textures.
  55630. *
  55631. * @param {Element|string} src - Texture source.
  55632. * @param {object} data - Texture data.
  55633. * @param {function} cb - Callback to pass texture to.
  55634. */
  55635. loadVideo: function (src, data, cb) {
  55636. var hash;
  55637. var texture;
  55638. var textureCache = this.textureCache;
  55639. var videoEl;
  55640. var videoTextureResult;
  55641. function handleVideoTextureLoaded (result) {
  55642. result.texture.needsUpdate = true;
  55643. cb(result.texture, result.videoEl);
  55644. }
  55645. // Video element provided.
  55646. if (typeof src !== 'string') {
  55647. // Check cache before creating texture.
  55648. videoEl = src;
  55649. hash = this.hashVideo(data, videoEl);
  55650. if (textureCache[hash]) {
  55651. textureCache[hash].then(handleVideoTextureLoaded);
  55652. return;
  55653. }
  55654. // If not in cache, fix up the attributes then start to create the texture.
  55655. fixVideoAttributes(videoEl);
  55656. }
  55657. // Only URL provided. Use video element to create texture.
  55658. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  55659. // Generated video element already cached. Use that.
  55660. hash = this.hashVideo(data, videoEl);
  55661. if (textureCache[hash]) {
  55662. textureCache[hash].then(handleVideoTextureLoaded);
  55663. return;
  55664. }
  55665. // Create new video texture.
  55666. texture = new THREE.VideoTexture(videoEl);
  55667. texture.minFilter = THREE.LinearFilter;
  55668. setTextureProperties(texture, data);
  55669. // If iOS and video is HLS, do some hacks.
  55670. if (this.sceneEl.isIOS &&
  55671. isHLS(videoEl.src || videoEl.getAttribute('src'),
  55672. videoEl.type || videoEl.getAttribute('type'))) {
  55673. // Actually BGRA. Tell shader to correct later.
  55674. texture.format = THREE.RGBAFormat;
  55675. texture.needsCorrectionBGRA = true;
  55676. // Apparently needed for HLS. Tell shader to correct later.
  55677. texture.flipY = false;
  55678. texture.needsCorrectionFlipY = true;
  55679. }
  55680. // Cache as promise to be consistent with image texture caching.
  55681. videoTextureResult = {texture: texture, videoEl: videoEl};
  55682. textureCache[hash] = Promise.resolve(videoTextureResult);
  55683. handleVideoTextureLoaded(videoTextureResult);
  55684. },
  55685. /**
  55686. * Create a hash of the material properties for texture cache key.
  55687. */
  55688. hash: function (data) {
  55689. if (data.src.tagName) {
  55690. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  55691. data = utils.extendDeep({}, data);
  55692. data.src = data.src.src;
  55693. }
  55694. return JSON.stringify(data);
  55695. },
  55696. hashVideo: function (data, videoEl) {
  55697. return calculateVideoCacheHash(data, videoEl);
  55698. },
  55699. /**
  55700. * Keep track of material in case an update trigger is needed (e.g., fog).
  55701. *
  55702. * @param {object} material
  55703. */
  55704. registerMaterial: function (material) {
  55705. this.materials[material.uuid] = material;
  55706. },
  55707. /**
  55708. * Stop tracking material, and dispose of any textures not being used by
  55709. * another material component.
  55710. *
  55711. * @param {object} material
  55712. */
  55713. unregisterMaterial: function (material) {
  55714. delete this.materials[material.uuid];
  55715. // If any textures on this material are no longer in use, dispose of them.
  55716. var textureCounts = this.textureCounts;
  55717. Object.keys(material)
  55718. .filter(function (propName) {
  55719. return material[propName] && material[propName].isTexture;
  55720. })
  55721. .forEach(function (mapName) {
  55722. textureCounts[material[mapName].uuid]--;
  55723. if (textureCounts[material[mapName].uuid] <= 0) {
  55724. material[mapName].dispose();
  55725. }
  55726. });
  55727. },
  55728. /**
  55729. * Trigger update to all registered materials.
  55730. */
  55731. updateMaterials: function (material) {
  55732. var materials = this.materials;
  55733. Object.keys(materials).forEach(function (uuid) {
  55734. materials[uuid].needsUpdate = true;
  55735. });
  55736. },
  55737. /**
  55738. * Track textures used by material components, so that they can be safely
  55739. * disposed when no longer in use. Textures must be registered here, and not
  55740. * through registerMaterial(), because textures may not be attached at the
  55741. * time the material is registered.
  55742. *
  55743. * @param {Event} e
  55744. */
  55745. onMaterialTextureLoaded: function (e) {
  55746. if (!this.textureCounts[e.detail.texture.uuid]) {
  55747. this.textureCounts[e.detail.texture.uuid] = 0;
  55748. }
  55749. this.textureCounts[e.detail.texture.uuid]++;
  55750. }
  55751. });
  55752. /**
  55753. * Calculates consistent hash from a video element using its attributes.
  55754. * If the video element has an ID, use that.
  55755. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  55756. *
  55757. * @param data {object} - Texture data such as repeat.
  55758. * @param videoEl {Element} - Video element.
  55759. * @returns {string}
  55760. */
  55761. function calculateVideoCacheHash (data, videoEl) {
  55762. var i;
  55763. var id = videoEl.getAttribute('id');
  55764. var hash;
  55765. var videoAttributes;
  55766. if (id) { return id; }
  55767. // Calculate hash using sorted video attributes.
  55768. hash = '';
  55769. videoAttributes = data || {};
  55770. for (i = 0; i < videoEl.attributes.length; i++) {
  55771. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  55772. }
  55773. Object.keys(videoAttributes).sort().forEach(function (name) {
  55774. hash += name + ':' + videoAttributes[name] + ';';
  55775. });
  55776. return hash;
  55777. }
  55778. /**
  55779. * Load image texture.
  55780. *
  55781. * @private
  55782. * @param {string|object} src - An <img> element or url to an image file.
  55783. * @param {object} data - Data to set texture properties like `repeat`.
  55784. * @returns {Promise} Resolves once texture is loaded.
  55785. */
  55786. function loadImageTexture (src, data) {
  55787. return new Promise(doLoadImageTexture);
  55788. function doLoadImageTexture (resolve, reject) {
  55789. var isEl = typeof src !== 'string';
  55790. function resolveTexture (texture) {
  55791. setTextureProperties(texture, data);
  55792. texture.needsUpdate = true;
  55793. resolve(texture);
  55794. }
  55795. // Create texture from an element.
  55796. if (isEl) {
  55797. resolveTexture(new THREE.Texture(src));
  55798. return;
  55799. }
  55800. // Request and load texture from src string. THREE will create underlying element.
  55801. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  55802. TextureLoader.load(
  55803. src,
  55804. resolveTexture,
  55805. function () { /* no-op */ },
  55806. function (xhr) {
  55807. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  55808. xhr.statusText);
  55809. }
  55810. );
  55811. }
  55812. }
  55813. /**
  55814. * Set texture properties such as repeat and offset.
  55815. *
  55816. * @param {object} data - With keys like `repeat`.
  55817. */
  55818. function setTextureProperties (texture, data) {
  55819. var offset = data.offset || {x: 0, y: 0};
  55820. var repeat = data.repeat || {x: 1, y: 1};
  55821. var npot = data.npot || false;
  55822. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  55823. // and filters must not use mipmaps (i.e. Nearest or Linear).
  55824. if (npot) {
  55825. texture.wrapS = THREE.ClampToEdgeWrapping;
  55826. texture.wrapT = THREE.ClampToEdgeWrapping;
  55827. texture.magFilter = THREE.LinearFilter;
  55828. texture.minFilter = THREE.LinearFilter;
  55829. }
  55830. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  55831. if (repeat.x !== 1 || repeat.y !== 1) {
  55832. texture.wrapS = THREE.RepeatWrapping;
  55833. texture.wrapT = THREE.RepeatWrapping;
  55834. texture.repeat.set(repeat.x, repeat.y);
  55835. }
  55836. // Don't bother setting offset if it is 0/0.
  55837. if (offset.x !== 0 || offset.y !== 0) {
  55838. texture.offset.set(offset.x, offset.y);
  55839. }
  55840. }
  55841. /**
  55842. * Create video element to be used as a texture.
  55843. *
  55844. * @param {string} src - Url to a video file.
  55845. * @param {number} width - Width of the video.
  55846. * @param {number} height - Height of the video.
  55847. * @returns {Element} Video element.
  55848. */
  55849. function createVideoEl (src, width, height) {
  55850. var videoEl = document.createElement('video');
  55851. videoEl.width = width;
  55852. videoEl.height = height;
  55853. // Support inline videos for iOS webviews.
  55854. videoEl.setAttribute('playsinline', '');
  55855. videoEl.setAttribute('webkit-playsinline', '');
  55856. videoEl.autoplay = true;
  55857. videoEl.loop = true;
  55858. videoEl.crossOrigin = 'anonymous';
  55859. videoEl.addEventListener('error', function () {
  55860. warn('`$s` is not a valid video', src);
  55861. }, true);
  55862. videoEl.src = src;
  55863. return videoEl;
  55864. }
  55865. /**
  55866. * Fixes a video element's attributes to prevent developers from accidentally passing the
  55867. * wrong attribute values to commonly misused video attributes.
  55868. *
  55869. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  55870. * as booleans. Existence of those attributes will mean truthy.
  55871. *
  55872. * For example, translates <video loop="false"> to <video>.
  55873. *
  55874. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  55875. * @param {Element} videoEl - Video element.
  55876. * @returns {Element} Video element with the correct properties updated.
  55877. */
  55878. function fixVideoAttributes (videoEl) {
  55879. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  55880. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  55881. if (videoEl.getAttribute('loop') === 'false') {
  55882. videoEl.removeAttribute('loop');
  55883. }
  55884. if (videoEl.getAttribute('preload') === 'false') {
  55885. videoEl.preload = 'none';
  55886. }
  55887. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  55888. // To support inline videos in iOS webviews.
  55889. videoEl.setAttribute('playsinline', '');
  55890. videoEl.setAttribute('webkit-playsinline', '');
  55891. return videoEl;
  55892. }
  55893. },{"../core/system":135,"../lib/three":172,"../utils/":197,"../utils/material":200}],187:[function(_dereq_,module,exports){
  55894. var registerSystem = _dereq_('../core/system').registerSystem;
  55895. var utils = _dereq_('../utils/');
  55896. var THREE = _dereq_('../lib/three');
  55897. var debug = utils.debug;
  55898. var warn = debug('components:renderer:warn');
  55899. /**
  55900. * Determines state of various renderer properties.
  55901. */
  55902. module.exports.System = registerSystem('renderer', {
  55903. schema: {
  55904. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  55905. highRefreshRate: {default: utils.device.isOculusBrowser()},
  55906. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  55907. maxCanvasWidth: {default: 1920},
  55908. maxCanvasHeight: {default: 1920},
  55909. physicallyCorrectLights: {default: false},
  55910. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  55911. sortObjects: {default: false},
  55912. colorManagement: {default: false},
  55913. gammaOutput: {default: false},
  55914. alpha: {default: true},
  55915. foveationLevel: {default: 0}
  55916. },
  55917. init: function () {
  55918. var data = this.data;
  55919. var sceneEl = this.el;
  55920. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  55921. var renderer = sceneEl.renderer;
  55922. renderer.sortObjects = data.sortObjects;
  55923. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  55924. if (data.colorManagement || data.gammaOutput) {
  55925. renderer.gammaOutput = true;
  55926. renderer.gammaFactor = 2.2;
  55927. if (data.gammaOutput) {
  55928. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  55929. }
  55930. }
  55931. if (sceneEl.hasAttribute('antialias')) {
  55932. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  55933. }
  55934. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  55935. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  55936. }
  55937. },
  55938. applyColorCorrection: function (colorOrTexture) {
  55939. if (!this.data.colorManagement || !colorOrTexture) {
  55940. return;
  55941. } else if (colorOrTexture.isColor) {
  55942. colorOrTexture.convertSRGBToLinear();
  55943. } else if (colorOrTexture.isTexture) {
  55944. colorOrTexture.encoding = THREE.sRGBEncoding;
  55945. }
  55946. }
  55947. });
  55948. },{"../core/system":135,"../lib/three":172,"../utils/":197}],188:[function(_dereq_,module,exports){
  55949. var registerSystem = _dereq_('../core/system').registerSystem;
  55950. var THREE = _dereq_('../lib/three');
  55951. var SHADOW_MAP_TYPE_MAP = {
  55952. basic: THREE.BasicShadowMap,
  55953. pcf: THREE.PCFShadowMap,
  55954. pcfsoft: THREE.PCFSoftShadowMap
  55955. };
  55956. /**
  55957. * Shadow system.
  55958. *
  55959. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  55960. * options on the WebGLRenderer for configuring shadow appearance.
  55961. */
  55962. module.exports.System = registerSystem('shadow', {
  55963. schema: {
  55964. enabled: {default: true},
  55965. autoUpdate: {default: true},
  55966. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  55967. },
  55968. init: function () {
  55969. var sceneEl = this.sceneEl;
  55970. var data = this.data;
  55971. this.shadowMapEnabled = false;
  55972. if (!sceneEl.renderer) { return; } // For tests.
  55973. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  55974. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  55975. this.setShadowMapEnabled(this.shadowMapEnabled);
  55976. },
  55977. update: function (prevData) {
  55978. if (prevData.enabled !== this.data.enabled) {
  55979. this.setShadowMapEnabled(this.data.enabled);
  55980. }
  55981. },
  55982. /**
  55983. * Enables/disables the renderer shadow map.
  55984. * @param {boolean} enabled
  55985. */
  55986. setShadowMapEnabled: function (enabled) {
  55987. var renderer = this.sceneEl.renderer;
  55988. this.shadowMapEnabled = this.data.enabled && enabled;
  55989. if (renderer) {
  55990. renderer.shadowMap.enabled = this.shadowMapEnabled;
  55991. }
  55992. }
  55993. });
  55994. },{"../core/system":135,"../lib/three":172}],189:[function(_dereq_,module,exports){
  55995. var registerSystem = _dereq_('../core/system').registerSystem;
  55996. var utils = _dereq_('../utils');
  55997. /**
  55998. * Tracked controls system.
  55999. * Maintain list with available tracked controllers.
  56000. */
  56001. module.exports.System = registerSystem('tracked-controls-webvr', {
  56002. init: function () {
  56003. var self = this;
  56004. this.controllers = [];
  56005. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  56006. this.updateControllerList();
  56007. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  56008. if (!navigator.getVRDisplays) { return; }
  56009. this.sceneEl.addEventListener('enter-vr', function () {
  56010. navigator.getVRDisplays().then(function (displays) {
  56011. if (displays.length) { self.vrDisplay = displays[0]; }
  56012. });
  56013. });
  56014. },
  56015. tick: function () {
  56016. if (this.isChrome) {
  56017. // Retrieve new controller handlers with updated state (pose, buttons...)
  56018. this.updateControllerList();
  56019. } else {
  56020. this.throttledUpdateControllerList();
  56021. }
  56022. },
  56023. /**
  56024. * Update controller list.
  56025. */
  56026. updateControllerList: function () {
  56027. var controllers = this.controllers;
  56028. var gamepad;
  56029. var gamepads;
  56030. var i;
  56031. var prevCount;
  56032. gamepads = navigator.getGamepads && navigator.getGamepads();
  56033. if (!gamepads) { return; }
  56034. prevCount = controllers.length;
  56035. controllers.length = 0;
  56036. for (i = 0; i < gamepads.length; ++i) {
  56037. gamepad = gamepads[i];
  56038. if (gamepad && gamepad.pose) {
  56039. controllers.push(gamepad);
  56040. }
  56041. }
  56042. if (controllers.length !== prevCount) {
  56043. this.el.emit('controllersupdated', undefined, false);
  56044. }
  56045. }
  56046. });
  56047. },{"../core/system":135,"../utils":197}],190:[function(_dereq_,module,exports){
  56048. var registerSystem = _dereq_('../core/system').registerSystem;
  56049. var utils = _dereq_('../utils');
  56050. /**
  56051. * Tracked controls system.
  56052. * Maintain list with available tracked controllers.
  56053. */
  56054. module.exports.System = registerSystem('tracked-controls-webxr', {
  56055. init: function () {
  56056. this.controllers = [];
  56057. this.oldControllersLength = 0;
  56058. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  56059. },
  56060. tick: function () {
  56061. this.throttledUpdateControllerList();
  56062. },
  56063. updateControllerList: function () {
  56064. var xrSession = this.el.xrSession;
  56065. var self = this;
  56066. if (!xrSession) { return; }
  56067. this.controllers = this.el.xrSession.inputSources;
  56068. if (this.oldControllersLength === this.controllers.length) { return; }
  56069. this.oldControllersLength = this.controllers.length;
  56070. xrSession.requestReferenceSpace('local-floor').then(function (referenceSpace) {
  56071. self.referenceSpace = referenceSpace;
  56072. });
  56073. this.el.emit('controllersupdated', undefined, false);
  56074. }
  56075. });
  56076. },{"../core/system":135,"../utils":197}],191:[function(_dereq_,module,exports){
  56077. /**
  56078. * Faster version of Function.prototype.bind
  56079. * @param {Function} fn - Function to wrap.
  56080. * @param {Object} ctx - What to bind as context.
  56081. * @param {...*} arguments - Arguments to pass through.
  56082. */
  56083. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  56084. return (function (prependedArgs) {
  56085. return function bound () {
  56086. // Concat the bound function arguments with those passed to original bind
  56087. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  56088. return fn.apply(ctx, args);
  56089. };
  56090. })(Array.prototype.slice.call(arguments, 2));
  56091. };
  56092. },{}],192:[function(_dereq_,module,exports){
  56093. /* global THREE */
  56094. var debug = _dereq_('./debug');
  56095. var extend = _dereq_('object-assign');
  56096. var warn = debug('utils:coordinates:warn');
  56097. // Order of coordinates parsed by coordinates.parse.
  56098. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  56099. // Coordinate string regex. Handles negative, positive, and decimals.
  56100. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  56101. module.exports.regex = regex;
  56102. var OBJECT = 'object';
  56103. var whitespaceRegex = /\s+/g;
  56104. /**
  56105. * Parses coordinates from an "x y z" string.
  56106. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  56107. *
  56108. * @param {string} val - An "x y z" string.
  56109. * @param {string} defaults - fallback value.
  56110. * @returns {object} An object with keys [x, y, z].
  56111. */
  56112. function parse (value, defaultVec) {
  56113. var coordinate;
  56114. var defaultVal;
  56115. var key;
  56116. var i;
  56117. var vec;
  56118. var x;
  56119. var y;
  56120. var z;
  56121. var w;
  56122. if (value && value instanceof Object) {
  56123. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  56124. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  56125. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  56126. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  56127. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  56128. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  56129. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  56130. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  56131. return value;
  56132. }
  56133. if (value === null || value === undefined) {
  56134. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  56135. }
  56136. coordinate = value.trim().split(whitespaceRegex);
  56137. vec = {};
  56138. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  56139. key = COORDINATE_KEYS[i];
  56140. if (coordinate[i]) {
  56141. vec[key] = parseFloat(coordinate[i], 10);
  56142. } else {
  56143. defaultVal = defaultVec && defaultVec[key];
  56144. if (defaultVal === undefined) { continue; }
  56145. vec[key] = parseIfString(defaultVal);
  56146. }
  56147. }
  56148. return vec;
  56149. }
  56150. module.exports.parse = parse;
  56151. /**
  56152. * Stringify coordinates from an object with keys [x y z].
  56153. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  56154. *
  56155. * @param {object|string} data - An object with keys [x y z].
  56156. * @returns {string} An "x y z" string.
  56157. */
  56158. function stringify (data) {
  56159. var str;
  56160. if (typeof data !== OBJECT) { return data; }
  56161. str = data.x + ' ' + data.y;
  56162. if (data.z != null) { str += ' ' + data.z; }
  56163. if (data.w != null) { str += ' ' + data.w; }
  56164. return str;
  56165. }
  56166. module.exports.stringify = stringify;
  56167. /**
  56168. * @returns {bool}
  56169. */
  56170. function isCoordinates (value) {
  56171. return regex.test(value);
  56172. }
  56173. module.exports.isCoordinates = isCoordinates;
  56174. module.exports.isCoordinate = function (value) {
  56175. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  56176. return isCoordinates(value);
  56177. };
  56178. function parseIfString (val) {
  56179. if (val !== null && val !== undefined && val.constructor === String) {
  56180. return parseFloat(val, 10);
  56181. }
  56182. return val;
  56183. }
  56184. /**
  56185. * Convert {x, y, z} object to three.js Vector3.
  56186. */
  56187. module.exports.toVector3 = function (vec3) {
  56188. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  56189. };
  56190. },{"./debug":193,"object-assign":39}],193:[function(_dereq_,module,exports){
  56191. (function (process){
  56192. var debugLib = _dereq_('debug');
  56193. var extend = _dereq_('object-assign');
  56194. var settings = {
  56195. colors: {
  56196. debug: 'gray',
  56197. error: 'red',
  56198. info: 'gray',
  56199. warn: 'orange'
  56200. }
  56201. };
  56202. /**
  56203. * Monkeypatches `debug` so we can colorize error/warning messages.
  56204. *
  56205. * (See issue: https://github.com/visionmedia/debug/issues/137)
  56206. */
  56207. var debug = function (namespace) {
  56208. var d = debugLib(namespace);
  56209. d.color = getDebugNamespaceColor(namespace);
  56210. return d;
  56211. };
  56212. extend(debug, debugLib);
  56213. /**
  56214. * Returns the type of the namespace (e.g., `error`, `warn`).
  56215. *
  56216. * @param {String} namespace
  56217. * The debug logger's namespace (e.g., `components:geometry:warn`).
  56218. * @returns {String} The type of the namespace (e.g., `warn`).
  56219. * @api private
  56220. */
  56221. function getDebugNamespaceType (namespace) {
  56222. var chunks = namespace.split(':');
  56223. return chunks[chunks.length - 1]; // Return the last one
  56224. }
  56225. /**
  56226. * Returns the color of the namespace (e.g., `orange`).
  56227. *
  56228. * @param {String} namespace
  56229. * The debug logger's namespace (e.g., `components:geometry:warn`).
  56230. * @returns {String} The color of the namespace (e.g., `orange`).
  56231. * @api private
  56232. */
  56233. function getDebugNamespaceColor (namespace) {
  56234. var type = getDebugNamespaceType(namespace);
  56235. var color = settings.colors && settings.colors[type];
  56236. return color || null;
  56237. }
  56238. /**
  56239. * Returns `localStorage` if possible.
  56240. *
  56241. * This is necessary because Safari throws when a user disables
  56242. * cookies or `localStorage` and you attempt to access it.
  56243. *
  56244. * @returns {localStorage}
  56245. * @api private
  56246. */
  56247. function storage () {
  56248. try {
  56249. return window.localStorage;
  56250. } catch (e) {
  56251. }
  56252. }
  56253. /**
  56254. * To enable console logging, type this in the Console of your Dev Tools:
  56255. *
  56256. * localStorage.logs = 1
  56257. *
  56258. * To disable console logging:
  56259. *
  56260. * localStorage.logs = 0
  56261. *
  56262. */
  56263. var ls = storage();
  56264. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  56265. debug.enable('*');
  56266. } else {
  56267. debug.enable('*:error,*:info,*:warn');
  56268. }
  56269. if (process.browser) { window.logs = debug; }
  56270. module.exports = debug;
  56271. }).call(this,_dereq_('_process'))
  56272. },{"_process":49,"debug":8,"object-assign":39}],194:[function(_dereq_,module,exports){
  56273. (function (process){
  56274. var error = _dereq_('debug')('device:error');
  56275. var vrDisplay;
  56276. var supportsXRSession = false;
  56277. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  56278. window.addEventListener('vrdisplayactivate', function (evt) {
  56279. var canvasEl;
  56280. // WebXR takes priority if available.
  56281. if (navigator.xr) { return; }
  56282. canvasEl = document.createElement('canvas');
  56283. vrDisplay = evt.display;
  56284. // We need to make sure the canvas has a WebGL context associated with it.
  56285. // Otherwise, the requestPresent could be denied.
  56286. canvasEl.getContext('webgl', {});
  56287. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  56288. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  56289. });
  56290. // Support both WebVR and WebXR APIs.
  56291. if (navigator.xr) {
  56292. navigator.xr.supportsSession('immersive-vr').then(function () {
  56293. supportsXRSession = true;
  56294. }).catch(function (err) {
  56295. error('WebXR Request Device: ' + err.message);
  56296. });
  56297. } else {
  56298. if (navigator.getVRDisplays) {
  56299. navigator.getVRDisplays().then(function (displays) {
  56300. var sceneEl = document.querySelector('a-scene');
  56301. vrDisplay = displays.length && displays[0];
  56302. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  56303. });
  56304. }
  56305. }
  56306. module.exports.isWebXRAvailable = navigator.xr !== undefined;
  56307. function getVRDisplay () { return vrDisplay; }
  56308. module.exports.getVRDisplay = getVRDisplay;
  56309. /**
  56310. * Determine if a headset is connected by checking if a vrDisplay is available.
  56311. */
  56312. function checkHeadsetConnected () { return supportsXRSession || !!getVRDisplay(); }
  56313. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  56314. /**
  56315. * Checks if browser is mobile and not stand-alone dedicated vr device.
  56316. * @return {Boolean} True if mobile browser detected.
  56317. */
  56318. var isMobile = (function () {
  56319. var _isMobile = false;
  56320. (function (a) {
  56321. // eslint-disable-next-line no-useless-escape
  56322. 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))) {
  56323. _isMobile = true;
  56324. }
  56325. if (isIOS() || isTablet() || isR7()) {
  56326. _isMobile = true;
  56327. }
  56328. if (isMobileVR()) {
  56329. _isMobile = false;
  56330. }
  56331. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  56332. return function () { return _isMobile; };
  56333. })();
  56334. module.exports.isMobile = isMobile;
  56335. /**
  56336. * Detect tablet devices.
  56337. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  56338. */
  56339. function isTablet (mockUserAgent) {
  56340. var userAgent = mockUserAgent || window.navigator.userAgent;
  56341. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  56342. }
  56343. module.exports.isTablet = isTablet;
  56344. function isIOS () {
  56345. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  56346. }
  56347. module.exports.isIOS = isIOS;
  56348. /**
  56349. * Detect browsers in Stand-Alone headsets
  56350. */
  56351. function isOculusBrowser () {
  56352. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  56353. }
  56354. module.exports.isOculusBrowser = isOculusBrowser;
  56355. /**
  56356. * Detect browsers in Stand-Alone headsets
  56357. */
  56358. function isMobileVR () {
  56359. return isOculusBrowser() || /(Mobile VR)/i.test(window.navigator.userAgent);
  56360. }
  56361. module.exports.isMobileVR = isMobileVR;
  56362. function isR7 () {
  56363. return /R7 Build/.test(window.navigator.userAgent);
  56364. }
  56365. module.exports.isR7 = isR7;
  56366. /**
  56367. * Checks mobile device orientation.
  56368. * @return {Boolean} True if landscape orientation.
  56369. */
  56370. module.exports.isLandscape = function () {
  56371. var orientation = window.orientation;
  56372. if (isR7()) { orientation += 90; }
  56373. return orientation === 90 || orientation === -90;
  56374. };
  56375. /**
  56376. * Check if running in a browser or spoofed browser (bundler).
  56377. * We need to check a node api that isn't mocked on either side.
  56378. * `require` and `module.exports` are mocked in browser by bundlers.
  56379. * `window` is mocked in node.
  56380. * `process` is also mocked by browserify, but has custom properties.
  56381. */
  56382. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  56383. /**
  56384. * Check if running in node on the server.
  56385. */
  56386. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  56387. /**
  56388. * Update an Object3D pose if a polyfilled vrDisplay is present.
  56389. */
  56390. module.exports.PolyfillControls = function PolyfillControls (object) {
  56391. var frameData;
  56392. var vrDisplay = window.webvrpolyfill && window.webvrpolyfill.getPolyfillDisplays()[0];
  56393. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  56394. this.update = function () {
  56395. var pose;
  56396. if (!vrDisplay) { return; }
  56397. vrDisplay.getFrameData(frameData);
  56398. pose = frameData.pose;
  56399. if (pose.orientation !== null) {
  56400. object.quaternion.fromArray(pose.orientation);
  56401. }
  56402. if (pose.position !== null) {
  56403. object.position.fromArray(pose.position);
  56404. } else {
  56405. object.position.set(0, 0, 0);
  56406. }
  56407. };
  56408. };
  56409. }).call(this,_dereq_('_process'))
  56410. },{"_process":49,"debug":8}],195:[function(_dereq_,module,exports){
  56411. /**
  56412. * Split a delimited component property string (e.g., `material.color`) to an object
  56413. * containing `component` name and `property` name. If there is no delimiter, just return the
  56414. * string back.
  56415. *
  56416. * Cache arrays from splitting strings via delimiter to save on memory.
  56417. *
  56418. * @param {string} str - e.g., `material.opacity`.
  56419. * @param {string} delimiter - e.g., `.`.
  56420. * @returns {array} e.g., `['material', 'opacity']`.
  56421. */
  56422. var propertyPathCache = {};
  56423. function getComponentPropertyPath (str, delimiter) {
  56424. delimiter = delimiter || '.';
  56425. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  56426. if (str.indexOf(delimiter) !== -1) {
  56427. propertyPathCache[delimiter][str] = str.split(delimiter);
  56428. } else {
  56429. propertyPathCache[delimiter][str] = str;
  56430. }
  56431. return propertyPathCache[delimiter][str];
  56432. }
  56433. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  56434. module.exports.propertyPathCache = propertyPathCache;
  56435. /**
  56436. * Get component property using encoded component name + component property name with a
  56437. * delimiter.
  56438. */
  56439. module.exports.getComponentProperty = function (el, name, delimiter) {
  56440. var splitName;
  56441. delimiter = delimiter || '.';
  56442. if (name.indexOf(delimiter) !== -1) {
  56443. splitName = getComponentPropertyPath(name, delimiter);
  56444. if (splitName.constructor === String) {
  56445. return el.getAttribute(splitName);
  56446. }
  56447. return el.getAttribute(splitName[0])[splitName[1]];
  56448. }
  56449. return el.getAttribute(name);
  56450. };
  56451. /**
  56452. * Set component property using encoded component name + component property name with a
  56453. * delimiter.
  56454. */
  56455. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  56456. var splitName;
  56457. delimiter = delimiter || '.';
  56458. if (name.indexOf(delimiter) !== -1) {
  56459. splitName = getComponentPropertyPath(name, delimiter);
  56460. if (splitName.constructor === String) {
  56461. el.setAttribute(splitName, value);
  56462. } else {
  56463. el.setAttribute(splitName[0], splitName[1], value);
  56464. }
  56465. return;
  56466. }
  56467. el.setAttribute(name, value);
  56468. };
  56469. },{}],196:[function(_dereq_,module,exports){
  56470. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  56471. var width = canvasEl.style.width;
  56472. var height = canvasEl.style.height;
  56473. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  56474. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  56475. // By changing the size 1 pixel and restoring the previous value
  56476. // we trigger a size recalculation cycle.
  56477. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  56478. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  56479. setTimeout(function () {
  56480. canvasEl.style.width = width;
  56481. canvasEl.style.height = height;
  56482. }, 200);
  56483. };
  56484. },{}],197:[function(_dereq_,module,exports){
  56485. /* global location */
  56486. /* Centralized place to reference utilities since utils is exposed to the user. */
  56487. var debug = _dereq_('./debug');
  56488. var deepAssign = _dereq_('deep-assign');
  56489. var device = _dereq_('./device');
  56490. var objectAssign = _dereq_('object-assign');
  56491. var objectPool = _dereq_('./object-pool');
  56492. var warn = debug('utils:warn');
  56493. module.exports.bind = _dereq_('./bind');
  56494. module.exports.coordinates = _dereq_('./coordinates');
  56495. module.exports.debug = debug;
  56496. module.exports.device = device;
  56497. module.exports.entity = _dereq_('./entity');
  56498. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  56499. module.exports.isIE11 = _dereq_('./is-ie11');
  56500. module.exports.material = _dereq_('./material');
  56501. module.exports.objectPool = objectPool;
  56502. module.exports.split = _dereq_('./split').split;
  56503. module.exports.styleParser = _dereq_('./styleParser');
  56504. module.exports.trackedControls = _dereq_('./tracked-controls');
  56505. module.exports.checkHeadsetConnected = function () {
  56506. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  56507. return device.checkHeadsetConnected(arguments);
  56508. };
  56509. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  56510. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  56511. };
  56512. module.exports.isIOS = function () {
  56513. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  56514. return device.isIOS(arguments);
  56515. };
  56516. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  56517. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  56518. };
  56519. module.exports.isMobile = function () {
  56520. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  56521. return device.isMobile(arguments);
  56522. };
  56523. /**
  56524. * Returns throttle function that gets called at most once every interval.
  56525. *
  56526. * @param {function} functionToThrottle
  56527. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  56528. * @param {object} optionalContext - If given, bind function to throttle to this context.
  56529. * @returns {function} Throttled function.
  56530. */
  56531. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  56532. var lastTime;
  56533. if (optionalContext) {
  56534. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  56535. }
  56536. return function () {
  56537. var time = Date.now();
  56538. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  56539. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  56540. lastTime = time;
  56541. functionToThrottle.apply(null, arguments);
  56542. }
  56543. };
  56544. };
  56545. /**
  56546. * Returns throttle function that gets called at most once every interval.
  56547. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  56548. *
  56549. * @param {function} functionToThrottle
  56550. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  56551. * @param {object} optionalContext - If given, bind function to throttle to this context.
  56552. * @returns {function} Throttled function.
  56553. */
  56554. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  56555. var lastTime;
  56556. if (optionalContext) {
  56557. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  56558. }
  56559. return function (time, delta) {
  56560. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  56561. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  56562. lastTime = time;
  56563. functionToThrottle(time, sinceLastTime);
  56564. }
  56565. };
  56566. };
  56567. /**
  56568. * Returns debounce function that gets called only once after a set of repeated calls.
  56569. *
  56570. * @param {function} functionToDebounce
  56571. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  56572. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  56573. * @returns {function} Debounced function.
  56574. */
  56575. module.exports.debounce = function (func, wait, immediate) {
  56576. var timeout;
  56577. return function () {
  56578. var context = this;
  56579. var args = arguments;
  56580. var later = function () {
  56581. timeout = null;
  56582. if (!immediate) func.apply(context, args);
  56583. };
  56584. var callNow = immediate && !timeout;
  56585. clearTimeout(timeout);
  56586. timeout = setTimeout(later, wait);
  56587. if (callNow) func.apply(context, args);
  56588. };
  56589. };
  56590. /**
  56591. * Mix the properties of source object(s) into a destination object.
  56592. *
  56593. * @param {object} dest - The object to which properties will be copied.
  56594. * @param {...object} source - The object(s) from which properties will be copied.
  56595. */
  56596. module.exports.extend = objectAssign;
  56597. module.exports.extendDeep = deepAssign;
  56598. module.exports.clone = function (obj) {
  56599. return JSON.parse(JSON.stringify(obj));
  56600. };
  56601. /**
  56602. * Checks if two values are equal.
  56603. * Includes objects and arrays and nested objects and arrays.
  56604. * Try to keep this function performant as it will be called often to see if a component
  56605. * should be updated.
  56606. *
  56607. * @param {object} a - First object.
  56608. * @param {object} b - Second object.
  56609. * @returns {boolean} Whether two objects are deeply equal.
  56610. */
  56611. var deepEqual = (function () {
  56612. var arrayPool = objectPool.createPool(function () { return []; });
  56613. return function (a, b) {
  56614. var key;
  56615. var keysA;
  56616. var keysB;
  56617. var i;
  56618. var valA;
  56619. var valB;
  56620. // If not objects or arrays, compare as values.
  56621. if (a === undefined || b === undefined || a === null || b === null ||
  56622. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  56623. (a.constructor === Array && b.constructor === Array))) {
  56624. return a === b;
  56625. }
  56626. // Different number of keys, not equal.
  56627. keysA = arrayPool.use();
  56628. keysB = arrayPool.use();
  56629. keysA.length = 0;
  56630. keysB.length = 0;
  56631. for (key in a) { keysA.push(key); }
  56632. for (key in b) { keysB.push(key); }
  56633. if (keysA.length !== keysB.length) {
  56634. arrayPool.recycle(keysA);
  56635. arrayPool.recycle(keysB);
  56636. return false;
  56637. }
  56638. // Return `false` at the first sign of inequality.
  56639. for (i = 0; i < keysA.length; ++i) {
  56640. valA = a[keysA[i]];
  56641. valB = b[keysA[i]];
  56642. // Check nested array and object.
  56643. if ((typeof valA === 'object' || typeof valB === 'object') ||
  56644. (Array.isArray(valA) && Array.isArray(valB))) {
  56645. if (valA === valB) { continue; }
  56646. if (!deepEqual(valA, valB)) {
  56647. arrayPool.recycle(keysA);
  56648. arrayPool.recycle(keysB);
  56649. return false;
  56650. }
  56651. } else if (valA !== valB) {
  56652. arrayPool.recycle(keysA);
  56653. arrayPool.recycle(keysB);
  56654. return false;
  56655. }
  56656. }
  56657. arrayPool.recycle(keysA);
  56658. arrayPool.recycle(keysB);
  56659. return true;
  56660. };
  56661. })();
  56662. module.exports.deepEqual = deepEqual;
  56663. /**
  56664. * Computes the difference between two objects.
  56665. *
  56666. * @param {object} a - First object to compare (e.g., oldData).
  56667. * @param {object} b - Second object to compare (e.g., newData).
  56668. * @returns {object}
  56669. * Difference object where set of keys note which values were not equal, and values are
  56670. * `b`'s values.
  56671. */
  56672. module.exports.diff = (function () {
  56673. var keys = [];
  56674. return function (a, b, targetObject) {
  56675. var aVal;
  56676. var bVal;
  56677. var bKey;
  56678. var diff;
  56679. var key;
  56680. var i;
  56681. var isComparingObjects;
  56682. diff = targetObject || {};
  56683. // Collect A keys.
  56684. keys.length = 0;
  56685. for (key in a) { keys.push(key); }
  56686. if (!b) { return diff; }
  56687. // Collect B keys.
  56688. for (bKey in b) {
  56689. if (keys.indexOf(bKey) === -1) {
  56690. keys.push(bKey);
  56691. }
  56692. }
  56693. for (i = 0; i < keys.length; i++) {
  56694. key = keys[i];
  56695. aVal = a[key];
  56696. bVal = b[key];
  56697. isComparingObjects = aVal && bVal &&
  56698. aVal.constructor === Object && bVal.constructor === Object;
  56699. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  56700. (!isComparingObjects && aVal !== bVal)) {
  56701. diff[key] = bVal;
  56702. }
  56703. }
  56704. return diff;
  56705. };
  56706. })();
  56707. /**
  56708. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  56709. * @param {Event} event Event object.
  56710. * @returns {Boolean} Whether the key event should be captured.
  56711. */
  56712. module.exports.shouldCaptureKeyEvent = function (event) {
  56713. if (event.metaKey) { return false; }
  56714. return document.activeElement === document.body;
  56715. };
  56716. /**
  56717. * Splits a string into an array based on a delimiter.
  56718. *
  56719. * @param {string=} [str=''] Source string
  56720. * @param {string=} [delimiter=' '] Delimiter to use
  56721. * @returns {array} Array of delimited strings
  56722. */
  56723. module.exports.splitString = function (str, delimiter) {
  56724. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  56725. // First collapse the whitespace (or whatever the delimiter is).
  56726. var regex = new RegExp(delimiter, 'g');
  56727. str = (str || '').replace(regex, delimiter);
  56728. // Then split.
  56729. return str.split(delimiter);
  56730. };
  56731. /**
  56732. * Extracts data from the element given an object that contains expected keys.
  56733. *
  56734. * @param {Element} Source element.
  56735. * @param {Object} [defaults={}] Object of default key-value pairs.
  56736. * @returns {Object}
  56737. */
  56738. module.exports.getElData = function (el, defaults) {
  56739. defaults = defaults || {};
  56740. var data = {};
  56741. Object.keys(defaults).forEach(copyAttribute);
  56742. function copyAttribute (key) {
  56743. if (el.hasAttribute(key)) {
  56744. data[key] = el.getAttribute(key);
  56745. }
  56746. }
  56747. return data;
  56748. };
  56749. /**
  56750. * Retrieves querystring value.
  56751. * @param {String} name Name of querystring key.
  56752. * @return {String} Value
  56753. */
  56754. module.exports.getUrlParameter = function (name) {
  56755. // eslint-disable-next-line no-useless-escape
  56756. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  56757. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  56758. var results = regex.exec(location.search);
  56759. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  56760. };
  56761. /**
  56762. * Detects whether context is within iframe.
  56763. */
  56764. module.exports.isIframed = function () {
  56765. return window.top !== window.self;
  56766. };
  56767. /**
  56768. * Finds all elements under the element that have the isScene
  56769. * property set to true
  56770. */
  56771. module.exports.findAllScenes = function (el) {
  56772. var matchingElements = [];
  56773. var allElements = el.getElementsByTagName('*');
  56774. for (var i = 0, n = allElements.length; i < n; i++) {
  56775. if (allElements[i].isScene) {
  56776. // Element exists with isScene set.
  56777. matchingElements.push(allElements[i]);
  56778. }
  56779. }
  56780. return matchingElements;
  56781. };
  56782. // Must be at bottom to avoid circular dependency.
  56783. module.exports.srcLoader = _dereq_('./src-loader');
  56784. },{"./bind":191,"./coordinates":192,"./debug":193,"./device":194,"./entity":195,"./forceCanvasResizeSafariMobile":196,"./is-ie11":198,"./material":200,"./object-pool":201,"./split":202,"./src-loader":203,"./styleParser":204,"./tracked-controls":205,"deep-assign":10,"object-assign":39}],198:[function(_dereq_,module,exports){
  56785. // https://stackoverflow.com/a/17907562
  56786. function getInternetExplorerVersion () {
  56787. var version = -1;
  56788. var userAgent = navigator.userAgent;
  56789. var re;
  56790. if (navigator.appName === 'Microsoft Internet Explorer') {
  56791. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  56792. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  56793. } else if (navigator.appName === 'Netscape') {
  56794. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  56795. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  56796. }
  56797. return version;
  56798. }
  56799. module.exports = getInternetExplorerVersion() === 11;
  56800. },{}],199:[function(_dereq_,module,exports){
  56801. /**
  56802. * Check if device is iOS and older than version 10.
  56803. */
  56804. module.exports = function isIOSOlderThan10 (userAgent) {
  56805. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  56806. };
  56807. },{}],200:[function(_dereq_,module,exports){
  56808. var THREE = _dereq_('../lib/three');
  56809. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  56810. var COLOR_MAPS = new Set([
  56811. 'emissiveMap',
  56812. 'envMap',
  56813. 'map',
  56814. 'specularMap'
  56815. ]);
  56816. /**
  56817. * Update `material` texture property (usually but not always `map`)
  56818. * from `data` property (usually but not always `src`)
  56819. *
  56820. * @param {object} shader - A-Frame shader instance.
  56821. * @param {object} data
  56822. */
  56823. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  56824. var el = shader.el;
  56825. var material = shader.material;
  56826. var rendererSystem = el.sceneEl.systems.renderer;
  56827. var src = data[dataName];
  56828. // Because a single material / shader may have multiple textures,
  56829. // we need to remember the source value for this data property
  56830. // to avoid redundant operations which can be expensive otherwise
  56831. // (e.g. video texture loads).
  56832. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  56833. if (!src) {
  56834. // Forget the prior material src.
  56835. delete shader.materialSrcs[materialName];
  56836. // Remove the texture.
  56837. setMap(null);
  56838. return;
  56839. }
  56840. // Don't process if material src hasn't changed.
  56841. if (src === shader.materialSrcs[materialName]) { return; }
  56842. // Remember the new src for this texture (there may be multiple).
  56843. shader.materialSrcs[materialName] = src;
  56844. // If the new material src is already a texture, just use it.
  56845. if (src instanceof THREE.Texture) { setMap(src); } else {
  56846. // Load texture for the new material src.
  56847. // (And check if we should still use it once available in callback.)
  56848. el.sceneEl.systems.material.loadTexture(src,
  56849. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  56850. checkSetMap);
  56851. }
  56852. function checkSetMap (texture) {
  56853. // If the source has been changed, don't use loaded texture.
  56854. if (shader.materialSrcs[materialName] !== src) { return; }
  56855. setMap(texture);
  56856. }
  56857. function setMap (texture) {
  56858. material[materialName] = texture;
  56859. if (texture && COLOR_MAPS.has(materialName)) {
  56860. rendererSystem.applyColorCorrection(texture);
  56861. }
  56862. material.needsUpdate = true;
  56863. handleTextureEvents(el, texture);
  56864. }
  56865. };
  56866. /**
  56867. * Update `material.map` given `data.src`. For standard and flat shaders.
  56868. *
  56869. * @param {object} shader - A-Frame shader instance.
  56870. * @param {object} data
  56871. */
  56872. module.exports.updateMap = function (shader, data) {
  56873. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  56874. };
  56875. /**
  56876. * Updates the material's maps which give the illusion of extra geometry.
  56877. *
  56878. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  56879. * @param {object} shader - A-Frame shader instance
  56880. * @param {object} data
  56881. */
  56882. module.exports.updateDistortionMap = function (longType, shader, data) {
  56883. var shortType = longType;
  56884. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  56885. var el = shader.el;
  56886. var material = shader.material;
  56887. var rendererSystem = el.sceneEl.systems.renderer;
  56888. var src = data[longType + 'Map'];
  56889. var info = {};
  56890. info.src = src;
  56891. // Pass through the repeat and offset to be handled by the material loader.
  56892. info.offset = data[longType + 'TextureOffset'];
  56893. info.repeat = data[longType + 'TextureRepeat'];
  56894. info.wrap = data[longType + 'TextureWrap'];
  56895. if (src) {
  56896. if (src === shader[longType + 'TextureSrc']) { return; }
  56897. // Texture added or changed.
  56898. shader[longType + 'TextureSrc'] = src;
  56899. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  56900. return;
  56901. }
  56902. // Texture removed.
  56903. if (!material.map) { return; }
  56904. setMap(null);
  56905. function setMap (texture) {
  56906. var slot = shortType + 'Map';
  56907. material[slot] = texture;
  56908. if (texture && COLOR_MAPS.has(slot)) {
  56909. rendererSystem.applyColorCorrection(texture);
  56910. }
  56911. material.needsUpdate = true;
  56912. handleTextureEvents(el, texture);
  56913. }
  56914. };
  56915. /**
  56916. * Emit event on entities on texture-related events.
  56917. *
  56918. * @param {Element} el - Entity.
  56919. * @param {object} texture - three.js Texture.
  56920. */
  56921. function handleTextureEvents (el, texture) {
  56922. if (!texture) { return; }
  56923. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  56924. // Video events.
  56925. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  56926. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  56927. // Check to see if we need to use iOS 10 HLS shader.
  56928. // Only override the shader if it is stock shader that we know doesn't correct.
  56929. if (!el.components || !el.components.material) { return; }
  56930. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  56931. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  56932. el.setAttribute('material', 'shader', 'ios10hls');
  56933. }
  56934. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  56935. });
  56936. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  56937. // Works for non-looping videos only.
  56938. el.emit('materialvideoended', {src: texture.image, texture: texture});
  56939. });
  56940. }
  56941. module.exports.handleTextureEvents = handleTextureEvents;
  56942. /**
  56943. * Given video element src and type, guess whether stream is HLS.
  56944. *
  56945. * @param {string} src - src from video element (generally URL to content).
  56946. * @param {string} type - type from video element (generally MIME type if present).
  56947. */
  56948. module.exports.isHLS = function (src, type) {
  56949. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  56950. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  56951. return false;
  56952. };
  56953. },{"../lib/three":172}],201:[function(_dereq_,module,exports){
  56954. /*
  56955. Adapted deePool by Kyle Simpson.
  56956. MIT License: http://getify.mit-license.org
  56957. */
  56958. var EMPTY_SLOT = Object.freeze(Object.create(null));
  56959. // Default object factory.
  56960. function defaultObjectFactory () { return {}; }
  56961. /**
  56962. * Create a new pool.
  56963. */
  56964. module.exports.createPool = function createPool (objectFactory) {
  56965. var objPool = [];
  56966. var nextFreeSlot = null; // Pool location to look for a free object to use.
  56967. objectFactory = objectFactory || defaultObjectFactory;
  56968. function use () {
  56969. var objToUse;
  56970. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  56971. grow(objPool.length || 5);
  56972. }
  56973. objToUse = objPool[nextFreeSlot];
  56974. objPool[nextFreeSlot++] = EMPTY_SLOT;
  56975. clearObject(objToUse);
  56976. return objToUse;
  56977. }
  56978. function recycle (obj) {
  56979. if (!(obj instanceof Object)) { return; }
  56980. if (nextFreeSlot === null || nextFreeSlot === -1) {
  56981. objPool[objPool.length] = obj;
  56982. return;
  56983. }
  56984. objPool[--nextFreeSlot] = obj;
  56985. }
  56986. function grow (count) {
  56987. var currentLength;
  56988. var i;
  56989. count = count === undefined ? objPool.length : count;
  56990. if (count > 0 && nextFreeSlot == null) {
  56991. nextFreeSlot = 0;
  56992. }
  56993. if (count > 0) {
  56994. currentLength = objPool.length;
  56995. objPool.length += Number(count);
  56996. for (i = currentLength; i < objPool.length; i++) {
  56997. // Add new obj to pool.
  56998. objPool[i] = objectFactory();
  56999. }
  57000. }
  57001. return objPool.length;
  57002. }
  57003. function size () {
  57004. return objPool.length;
  57005. }
  57006. return {
  57007. grow: grow,
  57008. pool: objPool,
  57009. recycle: recycle,
  57010. size: size,
  57011. use: use
  57012. };
  57013. };
  57014. function clearObject (obj) {
  57015. var key;
  57016. if (!obj || obj.constructor !== Object) { return; }
  57017. for (key in obj) { obj[key] = undefined; }
  57018. }
  57019. module.exports.clearObject = clearObject;
  57020. function removeUnusedKeys (obj, schema) {
  57021. var key;
  57022. if (!obj || obj.constructor !== Object) { return; }
  57023. for (key in obj) {
  57024. if (!(key in schema)) {
  57025. delete obj[key];
  57026. }
  57027. }
  57028. }
  57029. module.exports.removeUnusedKeys = removeUnusedKeys;
  57030. },{}],202:[function(_dereq_,module,exports){
  57031. /**
  57032. * String split with cached result.
  57033. */
  57034. module.exports.split = (function () {
  57035. var splitCache = {};
  57036. return function (str, delimiter) {
  57037. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  57038. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  57039. splitCache[delimiter][str] = str.split(delimiter);
  57040. return splitCache[delimiter][str];
  57041. };
  57042. })();
  57043. },{}],203:[function(_dereq_,module,exports){
  57044. /* global Image, XMLHttpRequest */
  57045. var debug = _dereq_('./debug');
  57046. var warn = debug('utils:src-loader:warn');
  57047. /**
  57048. * Validate a texture, either as a selector or as a URL.
  57049. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  57050. * callback.
  57051. *
  57052. * `src` will be passed into the callback
  57053. *
  57054. * @params {string|Element} src - URL or media element.
  57055. * @params {function} isImageCb - callback if texture is an image.
  57056. * @params {function} isVideoCb - callback if texture is a video.
  57057. */
  57058. function validateSrc (src, isImageCb, isVideoCb) {
  57059. checkIsImage(src, function isAnImageUrl (isImage) {
  57060. if (isImage) {
  57061. isImageCb(src);
  57062. return;
  57063. }
  57064. isVideoCb(src);
  57065. });
  57066. }
  57067. /**
  57068. * Validates six images as a cubemap, either as selector or comma-separated
  57069. * URLs.
  57070. *
  57071. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  57072. must be wrapped by `url()`.
  57073. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  57074. must be wrapped by `url()`.
  57075. */
  57076. function validateCubemapSrc (src, cb) {
  57077. var aCubemap;
  57078. var cubemapSrcRegex = '';
  57079. var i;
  57080. var urls;
  57081. var validatedUrls = [];
  57082. for (i = 0; i < 5; i++) {
  57083. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  57084. }
  57085. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  57086. urls = src.match(new RegExp(cubemapSrcRegex));
  57087. // `src` is a comma-separated list of URLs.
  57088. // In this case, re-use validateSrc for each side of the cube.
  57089. function isImageCb (url) {
  57090. validatedUrls.push(url);
  57091. if (validatedUrls.length === 6) {
  57092. cb(validatedUrls);
  57093. }
  57094. }
  57095. if (urls) {
  57096. for (i = 1; i < 7; i++) {
  57097. validateSrc(parseUrl(urls[i]), isImageCb);
  57098. }
  57099. return;
  57100. }
  57101. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  57102. aCubemap = validateAndGetQuerySelector(src);
  57103. if (!aCubemap) { return; }
  57104. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  57105. return cb(aCubemap.srcs);
  57106. }
  57107. // Else if aCubeMap is not a <a-cubemap>.
  57108. warn('Selector "%s" does not point to <a-cubemap>', src);
  57109. }
  57110. /**
  57111. * Parses src from `url(src)`.
  57112. * @param {string} src - String to parse.
  57113. * @return {string} The parsed src, if parseable.
  57114. */
  57115. function parseUrl (src) {
  57116. var parsedSrc = src.match(/\url\((.+)\)/);
  57117. if (!parsedSrc) { return; }
  57118. return parsedSrc[1];
  57119. }
  57120. /**
  57121. * Call back whether `src` is an image.
  57122. *
  57123. * @param {string|Element} src - URL or element that will be tested.
  57124. * @param {function} onResult - Callback with whether `src` is an image.
  57125. */
  57126. function checkIsImage (src, onResult) {
  57127. var request;
  57128. if (src.tagName) {
  57129. onResult(src.tagName === 'IMG');
  57130. return;
  57131. }
  57132. request = new XMLHttpRequest();
  57133. // Try to send HEAD request to check if image first.
  57134. request.open('HEAD', src);
  57135. request.addEventListener('load', function (event) {
  57136. var contentType;
  57137. if (request.status >= 200 && request.status < 300) {
  57138. contentType = request.getResponseHeader('Content-Type');
  57139. if (contentType == null) {
  57140. checkIsImageFallback(src, onResult);
  57141. } else {
  57142. if (contentType.startsWith('image')) {
  57143. onResult(true);
  57144. } else {
  57145. onResult(false);
  57146. }
  57147. }
  57148. } else {
  57149. checkIsImageFallback(src, onResult);
  57150. }
  57151. request.abort();
  57152. });
  57153. request.send();
  57154. }
  57155. function checkIsImageFallback (src, onResult) {
  57156. var tester = new Image();
  57157. tester.addEventListener('load', onLoad);
  57158. function onLoad () { onResult(true); }
  57159. tester.addEventListener('error', onError);
  57160. function onError () { onResult(false); }
  57161. tester.src = src;
  57162. }
  57163. /**
  57164. * Query and validate a query selector,
  57165. *
  57166. * @param {string} selector - DOM selector.
  57167. * @return {object|null|undefined} Selected DOM element if exists.
  57168. null if query yields no results.
  57169. undefined if `selector` is not a valid selector.
  57170. */
  57171. function validateAndGetQuerySelector (selector) {
  57172. try {
  57173. var el = document.querySelector(selector);
  57174. if (!el) {
  57175. warn('No element was found matching the selector: "%s"', selector);
  57176. }
  57177. return el;
  57178. } catch (e) { // Capture exception if it's not a valid selector.
  57179. warn('"%s" is not a valid selector', selector);
  57180. return undefined;
  57181. }
  57182. }
  57183. module.exports = {
  57184. parseUrl: parseUrl,
  57185. validateSrc: validateSrc,
  57186. validateCubemapSrc: validateCubemapSrc
  57187. };
  57188. },{"./debug":193}],204:[function(_dereq_,module,exports){
  57189. /**
  57190. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  57191. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  57192. * by Josh Johnston (MIT License).
  57193. */
  57194. var DASH_REGEX = /-([a-z])/g;
  57195. /**
  57196. * Deserialize style-like string into an object of properties.
  57197. *
  57198. * @param {string} value - HTML attribute value.
  57199. * @param {object} obj - Reused object for object pooling.
  57200. * @returns {object} Property data.
  57201. */
  57202. module.exports.parse = function (value, obj) {
  57203. var parsedData;
  57204. if (typeof value !== 'string') { return value; }
  57205. parsedData = styleParse(value, obj);
  57206. // The style parser returns an object { "" : "test"} when fed a string
  57207. if (parsedData['']) { return value; }
  57208. return transformKeysToCamelCase(parsedData);
  57209. };
  57210. /**
  57211. * Serialize an object of properties into a style-like string.
  57212. *
  57213. * @param {object} data - Property data.
  57214. * @returns {string}
  57215. */
  57216. module.exports.stringify = function (data) {
  57217. if (typeof data === 'string') { return data; }
  57218. return styleStringify(data);
  57219. };
  57220. /**
  57221. * Converts string from hyphen to camelCase.
  57222. *
  57223. * @param {string} str - String to camelCase.
  57224. * @return {string} CamelCased string.
  57225. */
  57226. function toCamelCase (str) {
  57227. return str.replace(DASH_REGEX, upperCase);
  57228. }
  57229. module.exports.toCamelCase = toCamelCase;
  57230. /**
  57231. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  57232. * `maxValue`).
  57233. *
  57234. * @param {object} obj - The object to camelCase keys.
  57235. * @return {object} The object with keys camelCased.
  57236. */
  57237. function transformKeysToCamelCase (obj) {
  57238. var camelKey;
  57239. var key;
  57240. for (key in obj) {
  57241. camelKey = toCamelCase(key);
  57242. if (key === camelKey) { continue; }
  57243. obj[camelKey] = obj[key];
  57244. delete obj[key];
  57245. }
  57246. return obj;
  57247. }
  57248. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  57249. /**
  57250. * Split a string into chunks matching `<key>: <value>`
  57251. */
  57252. var getKeyValueChunks = (function () {
  57253. var chunks = [];
  57254. var hasUnclosedUrl = /url\([^)]+$/;
  57255. return function getKeyValueChunks (raw) {
  57256. var chunk = '';
  57257. var nextSplit;
  57258. var offset = 0;
  57259. var sep = ';';
  57260. chunks.length = 0;
  57261. while (offset < raw.length) {
  57262. nextSplit = raw.indexOf(sep, offset);
  57263. if (nextSplit === -1) { nextSplit = raw.length; }
  57264. chunk += raw.substring(offset, nextSplit);
  57265. // data URIs can contain semicolons, so make sure we get the whole thing
  57266. if (hasUnclosedUrl.test(chunk)) {
  57267. chunk += ';';
  57268. offset = nextSplit + 1;
  57269. continue;
  57270. }
  57271. chunks.push(chunk.trim());
  57272. chunk = '';
  57273. offset = nextSplit + 1;
  57274. }
  57275. return chunks;
  57276. };
  57277. })();
  57278. /**
  57279. * Convert a style attribute string to an object.
  57280. *
  57281. * @param {object} str - Attribute string.
  57282. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  57283. */
  57284. function styleParse (str, obj) {
  57285. var chunks;
  57286. var i;
  57287. var item;
  57288. var pos;
  57289. var key;
  57290. var val;
  57291. obj = obj || {};
  57292. chunks = getKeyValueChunks(str);
  57293. for (i = 0; i < chunks.length; i++) {
  57294. item = chunks[i];
  57295. if (!item) { continue; }
  57296. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  57297. pos = item.indexOf(':');
  57298. key = item.substr(0, pos).trim();
  57299. val = item.substr(pos + 1).trim();
  57300. obj[key] = val;
  57301. }
  57302. return obj;
  57303. }
  57304. /**
  57305. * Convert an object into an attribute string
  57306. **/
  57307. function styleStringify (obj) {
  57308. var key;
  57309. var keyCount = 0;
  57310. var i = 0;
  57311. var str = '';
  57312. for (key in obj) { keyCount++; }
  57313. for (key in obj) {
  57314. str += (key + ': ' + obj[key]);
  57315. if (i < keyCount - 1) { str += '; '; }
  57316. i++;
  57317. }
  57318. return str;
  57319. }
  57320. function upperCase (str) { return str[1].toUpperCase(); }
  57321. },{}],205:[function(_dereq_,module,exports){
  57322. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  57323. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  57324. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  57325. /**
  57326. * Called on controller component `.play` handlers.
  57327. * Check if controller matches parameters and inject tracked-controls component.
  57328. * Handle event listeners.
  57329. * Generate controllerconnected or controllerdisconnected events.
  57330. *
  57331. * @param {object} component - Tracked controls component.
  57332. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  57333. * @param {object} queryObject - Map of values to match.
  57334. */
  57335. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  57336. var el = component.el;
  57337. var controller;
  57338. var hasWebXR = el.sceneEl.hasWebXR;
  57339. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  57340. var isPresent;
  57341. controller = isControllerPresent(component, idPrefix, queryObject);
  57342. isPresent = !!controller;
  57343. // If component was previously paused and now playing, re-add event listeners.
  57344. // Handle the event listeners here since this helper method is control of calling
  57345. // `.addEventListeners` and `.removeEventListeners`.
  57346. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  57347. component.addEventListeners();
  57348. }
  57349. // Nothing changed, no need to do anything.
  57350. if (isPresent === component.controllerPresent) { return isPresent; }
  57351. component.controllerPresent = isPresent;
  57352. // Update controller presence.
  57353. if (isPresent) {
  57354. component.injectTrackedControls();
  57355. if (!hasWebXR) { component.addEventListeners(); }
  57356. el.emit('controllerconnected', {name: component.name, component: component});
  57357. } else {
  57358. component.removeEventListeners();
  57359. el.emit('controllerdisconnected', {name: component.name, component: component});
  57360. }
  57361. };
  57362. /**
  57363. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  57364. *
  57365. * @param {object} component - Tracked controls component.
  57366. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  57367. * @param {object} queryObject - Map of values to match.
  57368. */
  57369. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  57370. var gamepads;
  57371. var sceneEl = component.el.sceneEl;
  57372. var trackedControlsSystem;
  57373. var filterControllerIndex = queryObject.index || 0;
  57374. if (!idPrefix) { return false; }
  57375. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  57376. if (!trackedControlsSystem) { return false; }
  57377. gamepads = trackedControlsSystem.controllers;
  57378. if (!gamepads.length) { return false; }
  57379. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  57380. filterControllerIndex);
  57381. }
  57382. /**
  57383. *
  57384. * @param {object} component - Tracked controls component.
  57385. */
  57386. function isControllerPresentWebXR (component, idPrefix, queryObject) {
  57387. var controllers;
  57388. var sceneEl = component.el.sceneEl;
  57389. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  57390. if (!trackedControlsSystem) { return false; }
  57391. controllers = trackedControlsSystem.controllers;
  57392. if (!controllers || !controllers.length) { return false; }
  57393. return findMatchingControllerWebXR(controllers, queryObject.hand);
  57394. }
  57395. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  57396. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  57397. /**
  57398. * Walk through the given controllers to find any where the device ID equals
  57399. * filterIdExact, or startsWith filterIdPrefix.
  57400. * A controller where this considered true is considered a 'match'.
  57401. *
  57402. * For each matching controller:
  57403. * If filterHand is set, and the controller:
  57404. * is handed, we further verify that controller.hand equals filterHand.
  57405. * is unhanded (controller.hand is ''), we skip until we have found a
  57406. * number of matching controllers that equals filterControllerIndex
  57407. * If filterHand is not set, we skip until we have found the nth matching
  57408. * controller, where n equals filterControllerIndex
  57409. *
  57410. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  57411. * one or both of: [filterHand, filterControllerIndex]
  57412. *
  57413. * @param {object} controllers - Array of gamepads to search
  57414. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  57415. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  57416. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  57417. * @param {object} filterControllerIndex - Find the nth matching controller,
  57418. * where n equals filterControllerIndex. defaults to 0.
  57419. */
  57420. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  57421. filterControllerIndex) {
  57422. var controller;
  57423. var i;
  57424. var matchingControllerOccurence = 0;
  57425. var targetControllerMatch = filterControllerIndex || 0;
  57426. for (i = 0; i < controllers.length; i++) {
  57427. controller = controllers[i];
  57428. // Determine if the controller ID matches our criteria.
  57429. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  57430. continue;
  57431. }
  57432. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  57433. // If the hand filter and controller handedness are defined we compare them.
  57434. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  57435. // If we have detected an unhanded controller and the component was asking
  57436. // for a particular hand, we need to treat the controllers in the array as
  57437. // pairs of controllers. This effectively means that we need to skip
  57438. // NUM_HANDS matches for each controller number, instead of 1.
  57439. if (filterHand && !controller.hand) {
  57440. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  57441. }
  57442. // We are looking for the nth occurence of a matching controller
  57443. // (n equals targetControllerMatch).
  57444. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  57445. ++matchingControllerOccurence;
  57446. }
  57447. return undefined;
  57448. }
  57449. function findMatchingControllerWebXR (controllers, handedness) {
  57450. var i;
  57451. var controllerHandedness;
  57452. for (i = 0; i < controllers.length; i++) {
  57453. controllerHandedness = controllers[i].handedness;
  57454. if (!handedness || (controllerHandedness === '' && handedness === 'right') ||
  57455. controllers[i].handedness === handedness) {
  57456. return controllers[i];
  57457. }
  57458. }
  57459. return undefined;
  57460. }
  57461. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  57462. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  57463. /**
  57464. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  57465. *
  57466. * @param {object} component - Controller component in use.
  57467. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  57468. * @param {object} evt - Event to process.
  57469. */
  57470. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  57471. var axes;
  57472. var buttonType;
  57473. var changed;
  57474. var detail;
  57475. var j;
  57476. for (buttonType in axesMapping) {
  57477. axes = axesMapping[buttonType];
  57478. changed = false;
  57479. for (j = 0; j < axes.length; j++) {
  57480. if (evt.detail.changed[axes[j]]) { changed = true; }
  57481. }
  57482. if (!changed) { continue; }
  57483. // Axis has changed. Emit the specific moved event with axis values in detail.
  57484. detail = {};
  57485. for (j = 0; j < axes.length; j++) {
  57486. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  57487. }
  57488. component.el.emit(buttonType + 'moved', detail);
  57489. }
  57490. };
  57491. /**
  57492. * Handle a button event and reemits the events.
  57493. *
  57494. * @param {string} id - id of the button.
  57495. * @param {string} evtName - name of the reemitted event
  57496. * @param {object} component - reference to the component
  57497. * @param {string} hand - handedness of the controller: left or right.
  57498. */
  57499. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  57500. var mapping = hand ? component.mapping[hand] : component.mapping;
  57501. var buttonName = mapping.buttons[id];
  57502. component.el.emit(buttonName + evtName);
  57503. if (component.updateModel) {
  57504. component.updateModel(buttonName, evtName);
  57505. }
  57506. };
  57507. },{"../constants":116}],206:[function(_dereq_,module,exports){
  57508. window.glStats = function () {
  57509. var _rS = null;
  57510. var _totalDrawArraysCalls = 0,
  57511. _totalDrawElementsCalls = 0,
  57512. _totalUseProgramCalls = 0,
  57513. _totalFaces = 0,
  57514. _totalVertices = 0,
  57515. _totalPoints = 0,
  57516. _totalBindTexures = 0;
  57517. function _h ( f, c ) {
  57518. return function () {
  57519. c.apply( this, arguments );
  57520. f.apply( this, arguments );
  57521. };
  57522. }
  57523. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  57524. _totalDrawArraysCalls++;
  57525. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  57526. else _totalVertices += arguments[ 2 ];
  57527. } );
  57528. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  57529. _totalDrawElementsCalls++;
  57530. _totalFaces += arguments[ 1 ] / 3;
  57531. _totalVertices += arguments[ 1 ];
  57532. } );
  57533. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  57534. _totalUseProgramCalls++;
  57535. } );
  57536. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  57537. _totalBindTexures++;
  57538. } );
  57539. var _values = {
  57540. allcalls: {
  57541. over: 3000,
  57542. caption: 'Calls (hook)'
  57543. },
  57544. drawelements: {
  57545. caption: 'drawElements (hook)'
  57546. },
  57547. drawarrays: {
  57548. caption: 'drawArrays (hook)'
  57549. }
  57550. };
  57551. var _groups = [ {
  57552. caption: 'WebGL',
  57553. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  57554. } ];
  57555. var _fractions = [ {
  57556. base: 'allcalls',
  57557. steps: [ 'drawelements', 'drawarrays' ]
  57558. } ];
  57559. function _update () {
  57560. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  57561. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  57562. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  57563. _rS( 'bindTexture' ).set( _totalBindTexures );
  57564. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  57565. _rS( 'glfaces' ).set( _totalFaces );
  57566. _rS( 'glvertices' ).set( _totalVertices );
  57567. _rS( 'glpoints' ).set( _totalPoints );
  57568. }
  57569. function _start () {
  57570. _totalDrawArraysCalls = 0;
  57571. _totalDrawElementsCalls = 0;
  57572. _totalUseProgramCalls = 0;
  57573. _totalFaces = 0;
  57574. _totalVertices = 0;
  57575. _totalPoints = 0;
  57576. _totalBindTexures = 0;
  57577. }
  57578. function _end () {}
  57579. function _attach ( r ) {
  57580. _rS = r;
  57581. }
  57582. return {
  57583. update: _update,
  57584. start: _start,
  57585. end: _end,
  57586. attach: _attach,
  57587. values: _values,
  57588. groups: _groups,
  57589. fractions: _fractions
  57590. };
  57591. };
  57592. window.threeStats = function ( renderer ) {
  57593. var _rS = null;
  57594. var _values = {
  57595. 'renderer.info.memory.geometries': {
  57596. caption: 'Geometries'
  57597. },
  57598. 'renderer.info.memory.textures': {
  57599. caption: 'Textures'
  57600. },
  57601. 'renderer.info.programs': {
  57602. caption: 'Programs'
  57603. },
  57604. 'renderer.info.render.calls': {
  57605. caption: 'Calls'
  57606. },
  57607. 'renderer.info.render.triangles': {
  57608. caption: 'Triangles',
  57609. over: 1000
  57610. },
  57611. 'renderer.info.render.points': {
  57612. caption: 'Points'
  57613. }
  57614. };
  57615. var _groups = [ {
  57616. caption: 'Three.js - Memory',
  57617. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  57618. }, {
  57619. caption: 'Three.js - Render',
  57620. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  57621. } ];
  57622. var _fractions = [];
  57623. function _update () {
  57624. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  57625. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  57626. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  57627. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  57628. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  57629. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  57630. }
  57631. function _start () {}
  57632. function _end () {}
  57633. function _attach ( r ) {
  57634. _rS = r;
  57635. }
  57636. return {
  57637. update: _update,
  57638. start: _start,
  57639. end: _end,
  57640. attach: _attach,
  57641. values: _values,
  57642. groups: _groups,
  57643. fractions: _fractions
  57644. };
  57645. };
  57646. /*
  57647. * From https://github.com/paulirish/memory-stats.js
  57648. */
  57649. window.BrowserStats = function () {
  57650. var _rS = null;
  57651. var _usedJSHeapSize = 0,
  57652. _totalJSHeapSize = 0;
  57653. if ( window.performance && !performance.memory ) {
  57654. performance.memory = {
  57655. usedJSHeapSize: 0,
  57656. totalJSHeapSize: 0
  57657. };
  57658. }
  57659. if ( performance.memory.totalJSHeapSize === 0 ) {
  57660. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  57661. }
  57662. var _values = {
  57663. memory: {
  57664. caption: 'Used Memory',
  57665. average: true,
  57666. avgMs: 1000,
  57667. over: 22
  57668. },
  57669. total: {
  57670. caption: 'Total Memory'
  57671. }
  57672. };
  57673. var _groups = [ {
  57674. caption: 'Browser',
  57675. values: [ 'memory', 'total' ]
  57676. } ];
  57677. var _fractions = [ {
  57678. base: 'total',
  57679. steps: [ 'memory' ]
  57680. } ];
  57681. var log1024 = Math.log( 1024 );
  57682. function _size ( v ) {
  57683. var precision = 100; //Math.pow(10, 2);
  57684. var i = Math.floor( Math.log( v ) / log1024 );
  57685. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  57686. }
  57687. function _update () {
  57688. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  57689. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  57690. _rS( 'memory' ).set( _usedJSHeapSize );
  57691. _rS( 'total' ).set( _totalJSHeapSize );
  57692. }
  57693. function _start () {
  57694. _usedJSHeapSize = 0;
  57695. }
  57696. function _end () {}
  57697. function _attach ( r ) {
  57698. _rS = r;
  57699. }
  57700. return {
  57701. update: _update,
  57702. start: _start,
  57703. end: _end,
  57704. attach: _attach,
  57705. values: _values,
  57706. groups: _groups,
  57707. fractions: _fractions
  57708. };
  57709. };
  57710. if (typeof module === 'object') {
  57711. module.exports = {
  57712. glStats: window.glStats,
  57713. threeStats: window.threeStats,
  57714. BrowserStats: window.BrowserStats
  57715. };
  57716. }
  57717. },{}],207:[function(_dereq_,module,exports){
  57718. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  57719. 'use strict';
  57720. ( function () {
  57721. if ( 'performance' in window == false ) {
  57722. window.performance = {};
  57723. }
  57724. var performance = window.performance;
  57725. if ( 'now' in performance == false ) {
  57726. var nowOffset = Date.now();
  57727. if ( performance.timing && performance.timing.navigationStart ) {
  57728. nowOffset = performance.timing.navigationStart;
  57729. }
  57730. performance.now = function now () {
  57731. return Date.now() - nowOffset;
  57732. };
  57733. }
  57734. if( !performance.mark ) {
  57735. performance.mark = function(){}
  57736. }
  57737. if( !performance.measure ) {
  57738. performance.measure = function(){}
  57739. }
  57740. } )();
  57741. window.rStats = function rStats ( settings ) {
  57742. function iterateKeys ( array, callback ) {
  57743. var keys = Object.keys( array );
  57744. for ( var j = 0, l = keys.length; j < l; j++ ) {
  57745. callback( keys[ j ] );
  57746. }
  57747. }
  57748. function importCSS ( url ) {
  57749. var element = document.createElement( 'link' );
  57750. element.href = url;
  57751. element.rel = 'stylesheet';
  57752. element.type = 'text/css';
  57753. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  57754. }
  57755. var _settings = settings || {};
  57756. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  57757. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  57758. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  57759. var _css = _settings.css || [ _cssFont, _cssRStats ];
  57760. _css.forEach(function (uri) {
  57761. importCSS( uri );
  57762. });
  57763. if ( !_settings.values ) _settings.values = {};
  57764. var _base, _div, _elHeight = 10, _elWidth = 200;
  57765. var _perfCounters = {};
  57766. function Graph ( _dom, _id, _defArg ) {
  57767. var _def = _defArg || {};
  57768. var _canvas = document.createElement( 'canvas' ),
  57769. _ctx = _canvas.getContext( '2d' ),
  57770. _max = 0,
  57771. _current = 0;
  57772. var c = _def.color ? _def.color : '#666666';
  57773. var _dotCanvas = document.createElement( 'canvas' ),
  57774. _dotCtx = _dotCanvas.getContext( '2d' );
  57775. _dotCanvas.width = 1;
  57776. _dotCanvas.height = 2 * _elHeight;
  57777. _dotCtx.fillStyle = '#444444';
  57778. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  57779. _dotCtx.fillStyle = c;
  57780. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  57781. _dotCtx.fillStyle = '#ffffff';
  57782. _dotCtx.globalAlpha = 0.5;
  57783. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  57784. _dotCtx.globalAlpha = 1;
  57785. var _alarmCanvas = document.createElement( 'canvas' ),
  57786. _alarmCtx = _alarmCanvas.getContext( '2d' );
  57787. _alarmCanvas.width = 1;
  57788. _alarmCanvas.height = 2 * _elHeight;
  57789. _alarmCtx.fillStyle = '#444444';
  57790. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  57791. _alarmCtx.fillStyle = '#b70000';
  57792. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  57793. _alarmCtx.globalAlpha = 0.5;
  57794. _alarmCtx.fillStyle = '#ffffff';
  57795. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  57796. _alarmCtx.globalAlpha = 1;
  57797. function _init () {
  57798. _canvas.width = _elWidth;
  57799. _canvas.height = _elHeight;
  57800. _canvas.style.width = _canvas.width + 'px';
  57801. _canvas.style.height = _canvas.height + 'px';
  57802. _canvas.className = 'rs-canvas';
  57803. _dom.appendChild( _canvas );
  57804. _ctx.fillStyle = '#444444';
  57805. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  57806. }
  57807. function _draw ( v, alarm ) {
  57808. _current += ( v - _current ) * 0.1;
  57809. _max *= 0.99;
  57810. if ( _current > _max ) _max = _current;
  57811. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  57812. if ( alarm ) {
  57813. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  57814. } else {
  57815. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  57816. }
  57817. }
  57818. _init();
  57819. return {
  57820. draw: _draw
  57821. };
  57822. }
  57823. function StackGraph ( _dom, _num ) {
  57824. var _canvas = document.createElement( 'canvas' ),
  57825. _ctx = _canvas.getContext( '2d' );
  57826. function _init () {
  57827. _canvas.width = _elWidth;
  57828. _canvas.height = _elHeight * _num;
  57829. _canvas.style.width = _canvas.width + 'px';
  57830. _canvas.style.height = _canvas.height + 'px';
  57831. _canvas.className = 'rs-canvas';
  57832. _dom.appendChild( _canvas );
  57833. _ctx.fillStyle = '#444444';
  57834. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  57835. }
  57836. function _draw ( v ) {
  57837. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  57838. var th = 0;
  57839. iterateKeys( v, function ( j ) {
  57840. var h = v[ j ] * _canvas.height;
  57841. _ctx.fillStyle = _colours[ j ];
  57842. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  57843. th += h;
  57844. } );
  57845. }
  57846. _init();
  57847. return {
  57848. draw: _draw
  57849. };
  57850. }
  57851. function PerfCounter ( id, group ) {
  57852. var _id = id,
  57853. _time,
  57854. _value = 0,
  57855. _total = 0,
  57856. _averageValue = 0,
  57857. _accumValue = 0,
  57858. _accumStart = performance.now(),
  57859. _accumSamples = 0,
  57860. _dom = document.createElement( 'div' ),
  57861. _spanId = document.createElement( 'span' ),
  57862. _spanValue = document.createElement( 'div' ),
  57863. _spanValueText = document.createTextNode( '' ),
  57864. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  57865. _graph = new Graph( _dom, _id, _def ),
  57866. _started = false;
  57867. _spanId.className = 'rs-counter-id';
  57868. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  57869. _spanValue.className = 'rs-counter-value';
  57870. _spanValue.appendChild( _spanValueText );
  57871. _dom.appendChild( _spanId );
  57872. _dom.appendChild( _spanValue );
  57873. if ( group ) group.div.appendChild( _dom );
  57874. else _div.appendChild( _dom );
  57875. _time = performance.now();
  57876. function _average ( v ) {
  57877. if ( _def && _def.average ) {
  57878. _accumValue += v;
  57879. _accumSamples++;
  57880. var t = performance.now();
  57881. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  57882. _averageValue = _accumValue / _accumSamples;
  57883. _accumValue = 0;
  57884. _accumStart = t;
  57885. _accumSamples = 0;
  57886. }
  57887. }
  57888. }
  57889. function _start () {
  57890. _time = performance.now();
  57891. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  57892. _started = true;
  57893. }
  57894. function _end () {
  57895. _value = performance.now() - _time;
  57896. if( _settings.userTimingAPI ) {
  57897. performance.mark( _id + '-end' );
  57898. if( _started ) {
  57899. performance.measure( _id, _id + '-start', _id + '-end' );
  57900. }
  57901. }
  57902. _average( _value );
  57903. }
  57904. function _tick () {
  57905. _end();
  57906. _start();
  57907. }
  57908. function _draw () {
  57909. var v = ( _def && _def.average ) ? _averageValue : _value;
  57910. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  57911. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  57912. _graph.draw( _value, a );
  57913. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  57914. }
  57915. function _frame () {
  57916. var t = performance.now();
  57917. var e = t - _time;
  57918. _total++;
  57919. if ( e > 1000 ) {
  57920. if ( _def && _def.interpolate === false ) {
  57921. _value = _total;
  57922. } else {
  57923. _value = _total * 1000 / e;
  57924. }
  57925. _total = 0;
  57926. _time = t;
  57927. _average( _value );
  57928. }
  57929. }
  57930. function _set ( v ) {
  57931. _value = v;
  57932. _average( _value );
  57933. }
  57934. return {
  57935. set: _set,
  57936. start: _start,
  57937. tick: _tick,
  57938. end: _end,
  57939. frame: _frame,
  57940. value: function () {
  57941. return _value;
  57942. },
  57943. draw: _draw
  57944. };
  57945. }
  57946. function sample () {
  57947. var _value = 0;
  57948. function _set ( v ) {
  57949. _value = v;
  57950. }
  57951. return {
  57952. set: _set,
  57953. value: function () {
  57954. return _value;
  57955. }
  57956. };
  57957. }
  57958. function _perf ( idArg ) {
  57959. var id = idArg.toLowerCase();
  57960. if ( id === undefined ) id = 'default';
  57961. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  57962. var group = null;
  57963. if ( _settings && _settings.groups ) {
  57964. iterateKeys( _settings.groups, function ( j ) {
  57965. var g = _settings.groups[ parseInt( j, 10 ) ];
  57966. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  57967. group = g;
  57968. }
  57969. } );
  57970. }
  57971. var p = new PerfCounter( id, group );
  57972. _perfCounters[ id ] = p;
  57973. return p;
  57974. }
  57975. function _init () {
  57976. if ( _settings.plugins ) {
  57977. if ( !_settings.values ) _settings.values = {};
  57978. if ( !_settings.groups ) _settings.groups = [];
  57979. if ( !_settings.fractions ) _settings.fractions = [];
  57980. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  57981. _settings.plugins[ j ].attach( _perf );
  57982. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  57983. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  57984. } );
  57985. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  57986. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  57987. }
  57988. } else {
  57989. _settings.plugins = {};
  57990. }
  57991. _base = document.createElement( 'div' );
  57992. _base.className = 'rs-base';
  57993. _div = document.createElement( 'div' );
  57994. _div.className = 'rs-container';
  57995. _div.style.height = 'auto';
  57996. _base.appendChild( _div );
  57997. document.body.appendChild( _base );
  57998. if ( !_settings ) return;
  57999. if ( _settings.groups ) {
  58000. iterateKeys( _settings.groups, function ( j ) {
  58001. var g = _settings.groups[ parseInt( j, 10 ) ];
  58002. var div = document.createElement( 'div' );
  58003. div.className = 'rs-group';
  58004. g.div = div;
  58005. var h1 = document.createElement( 'h1' );
  58006. h1.textContent = g.caption;
  58007. h1.addEventListener( 'click', function ( e ) {
  58008. this.classList.toggle( 'hidden' );
  58009. e.preventDefault();
  58010. }.bind( div ) );
  58011. _div.appendChild( h1 );
  58012. _div.appendChild( div );
  58013. } );
  58014. }
  58015. if ( _settings.fractions ) {
  58016. iterateKeys( _settings.fractions, function ( j ) {
  58017. var f = _settings.fractions[ parseInt( j, 10 ) ];
  58018. var div = document.createElement( 'div' );
  58019. div.className = 'rs-fraction';
  58020. var legend = document.createElement( 'div' );
  58021. legend.className = 'rs-legend';
  58022. var h = 0;
  58023. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  58024. var p = document.createElement( 'p' );
  58025. p.textContent = _settings.fractions[ j ].steps[ k ];
  58026. p.style.color = _colours[ h ];
  58027. legend.appendChild( p );
  58028. h++;
  58029. } );
  58030. div.appendChild( legend );
  58031. div.style.height = h * _elHeight + 'px';
  58032. f.div = div;
  58033. var graph = new StackGraph( div, h );
  58034. f.graph = graph;
  58035. _div.appendChild( div );
  58036. } );
  58037. }
  58038. }
  58039. function _update () {
  58040. iterateKeys( _settings.plugins, function ( j ) {
  58041. _settings.plugins[ j ].update();
  58042. } );
  58043. iterateKeys( _perfCounters, function ( j ) {
  58044. _perfCounters[ j ].draw();
  58045. } );
  58046. if ( _settings && _settings.fractions ) {
  58047. iterateKeys( _settings.fractions, function ( j ) {
  58048. var f = _settings.fractions[ parseInt( j, 10 ) ];
  58049. var v = [];
  58050. var base = _perfCounters[ f.base.toLowerCase() ];
  58051. if ( base ) {
  58052. base = base.value();
  58053. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  58054. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  58055. var val = _perfCounters[ s ];
  58056. if ( val ) {
  58057. v.push( val.value() / base );
  58058. }
  58059. } );
  58060. }
  58061. f.graph.draw( v );
  58062. } );
  58063. }
  58064. /*if( _height != _div.clientHeight ) {
  58065. _height = _div.clientHeight;
  58066. _base.style.height = _height + 2 * _elHeight + 'px';
  58067. console.log( _base.clientHeight );
  58068. }*/
  58069. }
  58070. _init();
  58071. return function ( id ) {
  58072. if ( id ) return _perf( id );
  58073. return {
  58074. element: _base,
  58075. update: _update
  58076. };
  58077. };
  58078. }
  58079. if (typeof module === 'object') {
  58080. module.exports = window.rStats;
  58081. }
  58082. },{}],208:[function(_dereq_,module,exports){
  58083. // https://stackoverflow.com/a/36213464
  58084. if (!String.prototype.startsWith) {
  58085. String.prototype.startsWith = function(searchString, position){
  58086. position = position || 0;
  58087. return this.substr(position, searchString.length) === searchString;
  58088. };
  58089. }
  58090. },{}],209:[function(_dereq_,module,exports){
  58091. /*
  58092. * Copyright 2015 Google Inc. All Rights Reserved.
  58093. * Licensed under the Apache License, Version 2.0 (the "License");
  58094. * you may not use this file except in compliance with the License.
  58095. * You may obtain a copy of the License at
  58096. *
  58097. * http://www.apache.org/licenses/LICENSE-2.0
  58098. *
  58099. * Unless required by applicable law or agreed to in writing, software
  58100. * distributed under the License is distributed on an "AS IS" BASIS,
  58101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58102. * See the License for the specific language governing permissions and
  58103. * limitations under the License.
  58104. */
  58105. var Util = {};
  58106. Util.base64 = function(mimeType, base64) {
  58107. return 'data:' + mimeType + ';base64,' + base64;
  58108. };
  58109. Util.isMobile = function() {
  58110. var check = false;
  58111. (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);
  58112. return check;
  58113. };
  58114. Util.isIOS = function() {
  58115. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  58116. };
  58117. Util.isIFrame = function() {
  58118. try {
  58119. return window.self !== window.top;
  58120. } catch (e) {
  58121. return true;
  58122. }
  58123. };
  58124. Util.appendQueryParameter = function(url, key, value) {
  58125. // Determine delimiter based on if the URL already GET parameters in it.
  58126. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  58127. url += delimiter + key + '=' + value;
  58128. return url;
  58129. };
  58130. // From http://goo.gl/4WX3tg
  58131. Util.getQueryParameter = function(name) {
  58132. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  58133. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  58134. results = regex.exec(location.search);
  58135. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  58136. };
  58137. Util.isLandscapeMode = function() {
  58138. return (window.orientation == 90 || window.orientation == -90);
  58139. };
  58140. module.exports = Util;
  58141. },{}],210:[function(_dereq_,module,exports){
  58142. /*
  58143. * Copyright 2015 Google Inc. All Rights Reserved.
  58144. * Licensed under the Apache License, Version 2.0 (the "License");
  58145. * you may not use this file except in compliance with the License.
  58146. * You may obtain a copy of the License at
  58147. *
  58148. * http://www.apache.org/licenses/LICENSE-2.0
  58149. *
  58150. * Unless required by applicable law or agreed to in writing, software
  58151. * distributed under the License is distributed on an "AS IS" BASIS,
  58152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58153. * See the License for the specific language governing permissions and
  58154. * limitations under the License.
  58155. */
  58156. var Util = _dereq_('./util.js');
  58157. /**
  58158. * Android and iOS compatible wakelock implementation.
  58159. *
  58160. * Refactored thanks to dkovalev@.
  58161. */
  58162. function AndroidWakeLock() {
  58163. var video = document.createElement('video');
  58164. video.addEventListener('ended', function() {
  58165. video.play();
  58166. });
  58167. this.request = function() {
  58168. if (video.paused) {
  58169. // Base64 version of videos_src/no-sleep-60s.webm.
  58170. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  58171. video.play();
  58172. }
  58173. };
  58174. this.release = function() {
  58175. video.pause();
  58176. video.src = '';
  58177. };
  58178. }
  58179. function iOSWakeLock() {
  58180. var timer = null;
  58181. this.request = function() {
  58182. if (!timer) {
  58183. timer = setInterval(function() {
  58184. window.location.href = '/';
  58185. setTimeout(window.stop, 0);
  58186. }, 15000);
  58187. }
  58188. }
  58189. this.release = function() {
  58190. if (timer) {
  58191. clearInterval(timer);
  58192. timer = null;
  58193. }
  58194. }
  58195. }
  58196. function getWakeLock() {
  58197. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  58198. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  58199. return iOSWakeLock;
  58200. } else {
  58201. return AndroidWakeLock;
  58202. }
  58203. }
  58204. module.exports = getWakeLock();
  58205. },{"./util.js":209}]},{},[170])(170)
  58206. });
  58207. //# sourceMappingURL=aframe-master.js.map